diff --git a/.github/actions/build-params/action.yml b/.github/actions/build-params/action.yml index 97cadefee0..7bb94e4a7f 100644 --- a/.github/actions/build-params/action.yml +++ b/.github/actions/build-params/action.yml @@ -25,12 +25,8 @@ runs: id: build-params shell: bash run: | - # Respect build parameters of the dispatch. - if [ ${{ github.event_name }} == "repository_dispatch" ]; then - echo "label=${{ github.event.client_payload.label }}" >> $GITHUB_OUTPUT - # If it's a pull request or `trying` push, annotate with `pr#` and publish to `edge/pr#`. - elif [ ${{ github.event_name }} == "pull_request" ]; then + if [ ${{ github.event_name }} == "pull_request" ]; then echo "label=pr${{ github.event.number }}" >> $GITHUB_OUTPUT echo "channel=edge/pr${{ github.event.number }}" >> $GITHUB_OUTPUT diff --git a/.github/actions/check-lint/action.yml b/.github/actions/check-lint/action.yml new file mode 100644 index 0000000000..87a75f37bc --- /dev/null +++ b/.github/actions/check-lint/action.yml @@ -0,0 +1,40 @@ +name: 'Check Lint' +description: 'Waits for and verifies whether the Lint workflow completes successfully' + +inputs: + sha: + description: 'The SHA to check for lint results' + required: false + default: ${{ github.event.pull_request.head.sha || github.sha }} + +outputs: + conclusion: + description: 'Conclusion of the lint check' + value: ${{ steps.wait-lint.outputs.conclusion }} + +runs: + using: 'composite' + steps: + - name: Wait for Lint workflow + uses: fountainhead/action-wait-for-check@v1.2.0 + id: wait-lint + with: + token: ${{ github.token }} + checkName: Lint + ref: ${{ inputs.sha }} + timeoutSeconds: 120 + intervalSeconds: 5 + + - name: Fail on timeout + if: ${{ steps.wait-lint.outputs.conclusion == 'timed_out' }} + shell: bash + run: | + echo "##[error] Timed out checking for linting result" + exit 1 + + - name: Fail on unexpected conclusion + shell: bash + if: ${{ steps.wait-lint.outputs.conclusion != 'success' && steps.wait-lint.outputs.conclusion != 'failure' }} + run: | + echo "##[error] Unexpected conclusion: ${{ steps.wait-lint.outputs.conclusion }}" + exit 1 diff --git a/.github/actions/checkout/action.yml b/.github/actions/checkout/action.yml index 28dc2aa894..e69de29bb2 100644 --- a/.github/actions/checkout/action.yml +++ b/.github/actions/checkout/action.yml @@ -1,19 +0,0 @@ -name: Checkout -description: Get tags and submodules for the Multipass repository - -runs: - using: composite - steps: - - name: Check out submodules - shell: bash - run: | - git submodule sync - # This repository can't do depth. - git -c protocol.version=2 submodule update --init 3rd-party/xz-decoder/xz-embedded - git -c protocol.version=2 submodule update --init --force --depth=1 --recursive - git -C 3rd-party/vcpkg fetch --unshallow - - - name: Fetch tags - shell: bash - run: | - git fetch --recurse-submodules origin +refs/tags/*:refs/tags/* diff --git a/.github/actions/lint/action.yml b/.github/actions/lint/action.yml index d759c6984a..c9639e0986 100644 --- a/.github/actions/lint/action.yml +++ b/.github/actions/lint/action.yml @@ -52,7 +52,8 @@ runs: set -e -o pipefail git submodule update --init 3rd-party/flutter if [ ! -f "3rd-party/flutter/bin/dart" ]; then - echo "##[error] Flutter submodule not initialized. Run 'git submodule update --init 3rd-party/flutter' to fix this issue." + echo -n "##[error] Flutter submodule not initialized. " + echo "Run 'git submodule update --init 3rd-party/flutter' to fix this issue." exit 1 fi @@ -61,6 +62,7 @@ runs: run: | set -e -o pipefail if ! 3rd-party/flutter/bin/dart format --output=none --set-exit-if-changed src/client/gui; then - echo "##[error] Flutter code is not properly formatted. Run '3rd-party/flutter/bin/dart format' to fix formatting." + echo -n "##[error] Flutter code is not properly formatted. " + echo "Run '3rd-party/flutter/bin/dart format' to fix formatting." exit 1 fi diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml deleted file mode 100644 index 172b955052..0000000000 --- a/.github/workflows/integration.yml +++ /dev/null @@ -1,226 +0,0 @@ -name: Integration - -on: - workflow_dispatch: - inputs: - snap-channel: - description: Snap Store channel - mac-x86-package: - description: macOS x86 package URL - mac-arm-package: - description: macOS ARM package URL - win-package: - description: Windows package URL - -jobs: - GetMatrix: - runs-on: ubuntu-latest - - outputs: - matrix: ${{ steps.set-matrix.outputs.matrix }} - - steps: - - name: Determine job matrix - id: set-matrix - run: | - set -euo pipefail - - MATRIX="" - - if [ -n '${{ github.event.inputs.snap-channel }}' ]; then - MATRIX+='{"os": "Linux", "vm": "linux", "driver": "qemu"}' - MATRIX+='{"os": "Linux", "vm": "linux", "driver": "lxd"}' - fi - - if [ -n '${{ github.event.inputs.mac-x86-package }}' ]; then - MATRIX+='{"os": "macOS", "vm": "macos-11", "driver": "qemu", "arch": "x86_64" }' - MATRIX+='{"os": "macOS", "vm": "macos-12", "driver": "qemu", "arch": "x86_64" }' - fi - - if [ -n '${{ github.event.inputs.mac-arm-package }}' ]; then - MATRIX+='{"os": "macOS", "driver": "qemu", "arch": "arm64" }' - fi - - if [ -n '${{ github.event.inputs.win-package }}' ]; then - MATRIX+='{"os": "Windows", "vm": "windows-10", "driver": "hyperv"}' - MATRIX+='{"os": "Windows", "vm": "windows-11", "driver": "hyperv"}' - fi - - echo "${MATRIX}" | jq -cs '{"include": . }' | awk '{ print "matrix=" $0 }' >> $GITHUB_OUTPUT - - CI: - needs: GetMatrix - - runs-on: testflinger - - # Windows is pretty slow unfortunately. - timeout-minutes: 120 - - strategy: - matrix: ${{ fromJSON(needs.GetMatrix.outputs.matrix) }} - - env: - TESTFLINGER_FILE: testflinger-${{ matrix.os }}-${{ matrix.driver }}.yaml - - steps: - - name: Write the testflinger job - uses: DamianReeves/write-file-action@v1.3 - with: - path: ${{ env.TESTFLINGER_FILE }} - write-mode: overwrite - contents: | - job_queue: ${{ matrix.os == 'macOS' && matrix.arch == 'arm64' && 'macos-arm' || matrix.vm }} - output_timeout: 2400 - provision_data: - ${{ matrix.vm && format('vmx: /Users/cibot/Virtual Machines.localized/{0}.vmwarevm/{0}.vmx', matrix.vm) || '' }} - snapshot: Testflinger - ${{ matrix.os == 'Linux' && 'image_url: https://cloud-images.ubuntu.com/releases/jammy/release/ubuntu-22.04-server-cloudimg-amd64.img' || '' }} - ${{ matrix.vm == 'windows-10' && 'username: ieuser' || '' }} - ${{ matrix.vm == 'windows-11' && 'username: user' || '' }} - vmx_config: - memsize: 4096 - vhv.enable: true - vpmc.enable: true - - test_data: - test_cmds: | - set -xeuo pipefail - - MP=multipass - [ '${{ matrix.os }}' == 'macOS' ] && MP=/usr/local/bin/multipass - - function _run() {{ - ssh ${{ '${{SSH_OPTS}} "${{DEVICE_USER}}@${{DEVICE_IP}}" -- "${{@}}"' }} - }} - - # Retry $1 times, with $2 seconds in between tries - function _retry() {{ - tries=$1 - interval=$2 - shift 2 - for try in $( seq $tries ); do - RC=0 - ${{ '"${{@}}"' }} || RC=$? - [ $RC -eq 0 -o $try -eq $tries ] && return $RC - sleep $interval; - done - }} - - # Retry $1 times, with $2 seconds in between tries, until $3 greps - function _retry_grep() {{ - tries=$1 - interval=$2 - pattern=$3 - shift 3 - for try in $( seq $tries ); do - RC=0 - ${{ '"${{@}}"' }} | grep --quiet -e "$pattern" || RC=$? - [ $RC -eq 0 -o $try -eq $tries ] && return $RC - sleep $interval; - done - }} - - # Log journal entries on bad exit - function _exit() {{ - RC=$? - if [ '${{ matrix.os }}' == 'Linux' ]; then - [ $RC -eq 0 ] || _run sudo journalctl -u snap.multipass* - elif [ '${{ matrix.os }}' == 'macOS' ]; then - [ $RC -eq 0 ] || _run sudo cat /Library/Logs/Multipass/multipassd.log - # Authenticate the root user - _run $MP set local.passphrase=foobar || true - # Sleep 20 seconds to allow daemon to restart - sleep 20 - _run sudo $MP authenticate foobar || true - ( echo y; echo y ) | _run sudo PATH=/bin:/usr/local/bin /bin/sh "/Library/Application\\ Support/com.canonical.multipass/uninstall.sh" || true - _run sudo rm -rf /Library/Logs/Multipass - fi - }} - trap _exit EXIT - - function _ps() {{ - _run powershell -noprofile -noninteractive -command ${{ '${{@}}' }} - }} - - function _install() {{ - PACKAGE="$1" - - if [ '${{ matrix.os }}' == 'Linux' ]; then - # Give snapd time to settle - _retry 5 30 _run sudo sh -c "snap\ list\ multipass && sudo snap refresh multipass --channel ${PACKAGE} || sudo snap install multipass --channel ${PACKAGE}" - - elif [ '${{ matrix.os }}' == 'macOS' ]; then - _run curl --location --output multipass.pkg "${PACKAGE}" - _run sudo installer -dumplog -target / -pkg multipass.pkg - - elif [ '${{ matrix.os }}' == 'Windows' ]; then - _ps "(New-Object System.Net.WebClient).DownloadFile('${PACKAGE}', 'multipass-installer.exe')" - _run .\\multipass-installer.exe /S - fi - }} - - if [ '${{ matrix.os }}' == 'Linux' ]; then - OVERRIDE_CONF="/etc/systemd/system/snap.multipass.multipassd.service.d/override.conf" - _run sudo mkdir -p $( dirname ${OVERRIDE_CONF} ) - _run sudo tee ${OVERRIDE_CONF} < testflinger_job - - testflinger-cli poll "${JOB_ID}" - [ "$( testflinger-cli results ${JOB_ID} | jq -r .test_status )" == "0" ] - - on_retry_command: | - testflinger-cli cancel "$( cat testflinger_job )" - - - name: Cancel the job - if: ${{ cancelled() }} - run: | - if [ -f testflinger_job ]; then testflinger-cli cancel "$( cat testflinger_job )"; fi diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000000..e4c657eccc --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,27 @@ +name: Lint + +on: + push: + branches: + - main + - release/[0-9]+.[0-9]+ + tags: + - v[0-9]+.[0-9]+.[0-9]+ + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + merge_group: + types: [checks_requested] + +jobs: + Lint: + name: Lint + runs-on: ubuntu-latest + + steps: + - name: Check out code + uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - name: Lint the code + uses: ./.github/actions/lint diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index cb401673d2..d98f5d1e86 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -3,10 +3,10 @@ name: Linux on: push: branches: - - main - - release/[0-9]+.[0-9]+ + - main + - release/[0-9]+.[0-9]+ tags: - - v[0-9]+.[0-9]+.[0-9]+ + - v[0-9]+.[0-9]+.[0-9]+ pull_request: types: [opened, synchronize, reopened, ready_for_review] merge_group: @@ -17,19 +17,19 @@ concurrency: cancel-in-progress: true jobs: - Lint: + CheckLint: runs-on: ubuntu-latest - if: ${{ !cancelled() && contains('pull_request merge_group', github.event_name) }} + outputs: + conclusion: ${{ steps.check-lint.outputs.conclusion }} steps: - - name: Check out code - uses: actions/checkout@v4 - with: - fetch-depth: 2 + - name: Check out code + uses: actions/checkout@v4 - - name: Lint the code - uses: ./.github/actions/lint + - name: Check Lint Status + id: check-lint + uses: ./.github/actions/check-lint GetMatrix: runs-on: ubuntu-latest @@ -47,26 +47,19 @@ jobs: {"build-type": "Clang"} {"build-type": "Release"}' - if ${{ github.event_name != 'merge_group' }}; then + if ${{ github.event_name != 'merge_group' && github.repository == 'canonical/multipass'}}; then MATRIX+='{"build-type": "Coverage" }' fi echo "${MATRIX}" | jq -cs '{"include": . }' | awk '{ print "matrix=" $0 }' >> $GITHUB_OUTPUT BuildAndTest: - needs: [Lint, GetMatrix] - - # Allow skipped Lint - # Let Lint fail on pull requests - if: ${{ !cancelled() && - ( - success() || - needs.Lint.result == 'skipped' || - ( - needs.Lint.result == 'failure' && - github.event_name == 'pull_request' - ) - ) + needs: [GetMatrix, CheckLint] + + # Proceed if Lint failed on a PR (but not if cancelled) + if: ${{ !cancelled() && success() && + (needs.CheckLint.outputs.conclusion == 'success' || + (needs.CheckLint.outputs.conclusion == 'failure' && github.event_name == 'pull_request')) }} outputs: @@ -102,11 +95,8 @@ jobs: - name: Check out code uses: actions/checkout@v4 with: - # Need to fetch it all for submodules to work. - fetch-depth: 0 - - - name: Check out tags and submodules - uses: ./.github/actions/checkout + fetch-depth: 0 # Need full history to derive version + submodules: 'recursive' - name: Determine build parameters id: build-params @@ -115,9 +105,11 @@ jobs: - name: Patch env: PATCH_PREFIX: .github/workflows/linux - run: | + run: > [ ! -f ${PATCH_PREFIX}.patch ] || patch -p1 --no-backup-if-mismatch < ${PATCH_PREFIX}.patch - [ ! -f ${PATCH_PREFIX}-${{ matrix.build-type }}.patch ] || patch -p1 --no-backup-if-mismatch < ${PATCH_PREFIX}-${{ matrix.build-type }}.patch + + [ ! -f ${PATCH_PREFIX}-${{ matrix.build-type }}.patch ] || + patch -p1 --no-backup-if-mismatch < ${PATCH_PREFIX}-${{ matrix.build-type }}.patch - name: Set up vcpkg id: setup-vcpkg @@ -135,12 +127,12 @@ jobs: # Find common base between main and HEAD to use as cache key. git -c protocol.version=2 fetch --no-tags --prune --progress --no-recurse-submodules origin main - echo "key=$( git merge-base origin/main ${{ github.sha }} )" >> $GITHUB_OUTPUT + echo "cache-key=$( git merge-base origin/main ${{ github.sha }} )" >> $GITHUB_OUTPUT - name: CCache uses: actions/cache@v4 with: - key: ccache-${{ runner.os }}-${{ matrix.build-type }}-${{ steps.setup-ccache.outputs.key }} + key: ccache-${{ runner.os }}-${{ matrix.build-type }}-${{ steps.setup-ccache.outputs.cache-key }} restore-keys: | ccache-${{ runner.os }}-${{ matrix.build-type }}- path: ~/.ccache @@ -155,9 +147,11 @@ jobs: echo "build=${MULTIPASS_PART}/build" >> $GITHUB_OUTPUT - name: Build + env: + LABEL: ${{ steps.build-params.outputs.label }} run: | # Inject the build label. - sed -i "/cmake-parameters:/a \ - -DMULTIPASS_BUILD_LABEL=${{ steps.build-params.outputs.label }}" snap/snapcraft.yaml + sed -i "/cmake-parameters:/a \ - -DMULTIPASS_BUILD_LABEL=${LABEL}" snap/snapcraft.yaml # Inject vcpkg GH Actions cache env vars if they exist if [ -n "${ACTIONS_CACHE_URL}" ]; then @@ -251,7 +245,6 @@ jobs: # do not cause job to fail if there are no coredumps available. continue-on-error: true run: | - set -o xtrace # Check whether the test executable is crashed or not. # If so, we'll need to pull the core dump and the executable from the container to the @@ -262,7 +255,8 @@ jobs: mkdir -p /tmp/coredump instance_name=`/snap/bin/lxc --project snapcraft --format=csv --columns=n list | grep multipass` # Pull the crashed executable from the container - /snap/bin/lxc --project snapcraft file pull -p -r "$instance_name/root/parts/multipass/build/bin/multipass_tests" /tmp/coredump/multipass_tests + /snap/bin/lxc --project snapcraft file pull \ + -p -r "$instance_name/root/parts/multipass/build/bin/multipass_tests" /tmp/coredump/multipass_tests echo "Pulled the executable." # Pull the coredump folder /snap/bin/lxc --project snapcraft file pull -p -r "$instance_name/coredump" /tmp/coredump @@ -306,11 +300,13 @@ jobs: if-no-files-found: error retention-days: 30 - # Publish the snap to the store if a channel was determined and we have access to secrets. + # Publish the snap to the store if all is good, a channel was determined, and we have access to secrets. Publish-Snap: needs: BuildAndTest - # Need to explicitly continue on Lint getting skipped. - if: ${{ !cancelled() && success() + if: ${{ + !cancelled() + && success() + && github.repository == 'canonical/multipass' && needs.BuildAndTest.outputs.channel != '' && (github.event_name == 'push' || github.event_name == 'merge_group' @@ -334,64 +330,3 @@ jobs: SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_TOKEN }} run: | snapcraft upload *.snap --release ${{ needs.BuildAndTest.outputs.channel }} - - # Dispatch to the private side - Dispatch: - needs: - - BuildAndTest - - Publish-Snap - - # Only dispatch if we have access to secrets. - # Need to explicitly continue on Lint getting skipped. - if: ${{ !cancelled() && success() - && (github.event_name == 'push' - || github.event_name == 'merge_group' - || github.event.pull_request.head.repo.full_name == github.repository) - }} - - runs-on: ubuntu-latest - - steps: - - name: Determine dispatch parameters - id: dispatch-params - run: | - if [ "${{ github.event_name }}" == "pull_request" ]; then - echo "head_ref=${{ github.head_ref }}" >> $GITHUB_OUTPUT - echo "head_sha=${{ github.event.pull_request.head.sha }}" >> $GITHUB_OUTPUT - else - echo "head_ref=${{ github.ref }}" >> $GITHUB_OUTPUT - echo "head_sha=${{ github.sha }}" >> $GITHUB_OUTPUT - fi - - - name: Dispatch Linux integration tests - if: ${{ github.event_name == 'push' }} - uses: Saviq/workflow-dispatch@dist - with: - token: ${{ secrets.PRIVATE_GITHUB_TOKEN }} - workflow: Integration - ref: ${{ steps.dispatch-params.outputs.ref }} - sha: ${{ steps.dispatch-params.outputs.sha }} - inputs: | - { - "snap-channel": "${{ needs.BuildAndTest.outputs.channel }}" - } - # This action will fail if `ref` moved on from `sha` to avoid mistargeting Integration runs. - continue-on-error: true - - - name: Dispatch macOS and Windows builds - uses: peter-evans/repository-dispatch@v3 - with: - token: ${{ secrets.PRIVATE_GITHUB_TOKEN }} - repository: ${{ secrets.PRIVATE_GITHUB_REPO }} - event-type: public_build - client-payload: | - { - "repository": "${{ github.repository }}", - "head_ref": "${{ steps.dispatch-params.outputs.head_ref }}", - "head_sha": "${{ steps.dispatch-params.outputs.head_sha }}", - "ref": "${{ github.ref }}", - "sha": "${{ github.sha }}", - "draft": "${{ github.event.pull_request.draft }}", - "label": "${{ needs.BuildAndTest.outputs.label }}", - "dispatch_ci": "${{ github.event_name == 'push' }}" - } diff --git a/.github/workflows/windows-macos.yml b/.github/workflows/windows-macos.yml new file mode 100644 index 0000000000..5551a1a9d0 --- /dev/null +++ b/.github/workflows/windows-macos.yml @@ -0,0 +1,379 @@ +name: WindowsMacOS + +on: + push: + branches: + - main + - release/[0-9]+.[0-9]+ + tags: + - v[0-9]+.[0-9]+.[0-9]+ + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + merge_group: + types: [checks_requested] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number && format('pr{0}', github.event.number) || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'merge_group' }} + +env: + HOMEBREW_NO_AUTO_UPDATE: 1 + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + S3_BUCKET: multipass-ci + +jobs: + CheckLint: + runs-on: ubuntu-latest + + outputs: + conclusion: ${{ steps.check-lint.outputs.conclusion }} + + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Check Lint Status + id: check-lint + uses: ./.github/actions/check-lint + + GetMatrix: + runs-on: ubuntu-latest + + outputs: + matrix: ${{ steps.set-matrix.outputs.matrix }} + + steps: + - name: Determine build matrix + id: set-matrix + run: | + set -euo pipefail + + MATRIX='{"include": [' + MATRIX+='{"runs-on": "windows-latest"},' + MATRIX+='{"runs-on": "multipass-macos-12-x64", "arch": "x86_64", "target": "12"},' + MATRIX+='{"runs-on": "multipass-macos-12-arm", "arch": "arm64", "target": "12"}' + MATRIX+=']}' + + echo "matrix=${MATRIX}" >> $GITHUB_OUTPUT + + BuildAndTest: + needs: [CheckLint, GetMatrix] + + # Proceed if Lint failed on a PR + if: | + success() && + (needs.CheckLint.outputs.conclusion == 'success' || + (needs.CheckLint.outputs.conclusion == 'failure' && github.event_name == 'pull_request')) + + strategy: + matrix: ${{ fromJSON(needs.GetMatrix.outputs.matrix) }} + fail-fast: ${{ github.event_name == 'merge_group' }} + + outputs: + build-label: ${{ steps.build-params.outputs.label }} + mac-x86-package: ${{ steps.publish-data.outputs.macOS-x86_64-package }} + mac-arm-package: ${{ steps.publish-data.outputs.macOS-arm64-package }} + + runs-on: ${{ matrix.runs-on }} + + env: + BUILD_DIR: ${{ github.workspace }}/build + CCACHE_DIR: ${{ github.workspace }}/build/ccache + MACOSX_DEPLOYMENT_TARGET: ${{ matrix.target }} + + steps: + - name: Check out code + uses: actions/checkout@v4 + with: + fetch-depth: 0 # Need full history to derive version + submodules: 'recursive' + + - name: Enable symlinks + if: ${{ runner.os == 'Windows' }} + run: git config --local core.symlinks true + + - name: Disable auto CRLF on Windows + if: ${{ runner.os == 'Windows' }} + run: git config --local core.autocrlf false + + - name: Determine build parameters + id: build-params + uses: ./.github/actions/build-params + + - name: Set preferred tar + if: ${{ runner.os == 'macOS' }} + id: preferred-tar + run: | + # Prepend gnu-tar's (future) location to the path, to prioritize it over system tar + # Needed for cache: https://github.com/actions/cache?tab=readme-ov-file#pre-requisites + echo "$( brew --prefix gnu-tar )/libexec/gnubin" >> ${GITHUB_PATH} + + - name: Set the arch wrapper + if: ${{ matrix.arch }} + run: echo "ARCH_WRAPPER=arch -arch ${{ matrix.arch }}" >> ${GITHUB_ENV} + + - name: Install dependencies from brew + if: ${{ runner.os == 'macOS' }} + run: | + ${{ env.ARCH_WRAPPER }} \ + brew install \ + cmake \ + coreutils \ + dylibbundler \ + git \ + glib \ + gnu-tar \ + libev \ + libffi \ + ninja \ + openssl@3 \ + pixman \ + pkg-config \ + python \ + wget + + - name: Install specific QEMU from Choco + if: ${{ runner.os == 'Windows' }} + uses: crazy-max/ghaction-chocolatey@v3 + with: + args: install --yes qemu --version=2023.4.24 + + - name: Install other packages from Choco + if: ${{ runner.os == 'Windows' }} + uses: crazy-max/ghaction-chocolatey@v3 + with: + args: install --yes wget unzip + + - name: Set up vcpkg + id: setup-vcpkg + uses: lukka/run-vcpkg@v11 + with: + vcpkgDirectory: '${{ github.workspace }}/3rd-party/vcpkg' + + - name: Set up CCache + if: ${{ runner.os == 'macOS' }} + id: setup-ccache + run: | # TODO increase the cache size for standard runners + ${{ env.ARCH_WRAPPER }} brew install ccache + ccache --max-size=700M + + # Find common base between main and HEAD to use as cache key. + # This avoids PRs from publishing caches. + git -c protocol.version=2 fetch --no-tags --prune --progress --no-recurse-submodules origin main + echo "cache-key=$( git merge-base origin/main ${{ github.sha }} )" >> $GITHUB_OUTPUT + echo "$( brew --prefix ccache )/libexec" >> ${GITHUB_PATH} + + - name: CCache + if: ${{ runner.os == 'macOS' }} + uses: actions/cache@v4 + with: + key: "ccache-${{ runner.os }}-${{ env.MACOSX_DEPLOYMENT_TARGET }}-${{ matrix.arch }}-\ + ${{ steps.setup-ccache.outputs.cache-key }}" + restore-keys: | + ccache-${{ runner.os }}-${{ env.MACOSX_DEPLOYMENT_TARGET }}-${{ matrix.arch }} + path: ${{ env.CCACHE_DIR }} + + - name: Install OpenSSL from Choco + if: ${{ runner.os == 'Windows' }} + uses: crazy-max/ghaction-chocolatey@v3 + with: + args: install --yes openssl --version=3.1.1 + + - name: Install Windows ADK + if: ${{ runner.os == 'Windows' }} + uses: crazy-max/ghaction-chocolatey@v3 + with: + args: install --yes windows-adk-deploy + + - name: Install cmake + if: ${{ runner.os == 'Windows' }} + uses: lukka/get-cmake@v4.0.1 + + - name: Install Qt + uses: jurplel/install-qt-action@v4 + with: + version: 6.2.4 + setup-python: false + aqtversion: '==3.1.*' + py7zrversion: '==0.20.*' + timeout-minutes: 20 + + - name: Set up MSVC + if: ${{ runner.os == 'Windows' }} + uses: ilammy/msvc-dev-cmd@v1 + + - name: Configure + run: > + ${{ env.ARCH_WRAPPER }} + cmake + -B${{ env.BUILD_DIR }} + -DCMAKE_BUILD_TYPE=RelWithDebInfo + -GNinja + -DCMAKE_PREFIX_PATH=${{ env.Qt6_Dir }} + -DMULTIPASS_UPSTREAM=origin + -DMULTIPASS_BUILD_LABEL=${{ steps.build-params.outputs.label }} + ${{ runner.os == 'Windows' && '-DCMAKE_C_COMPILER=cl.exe -DCMAKE_CXX_COMPILER=cl.exe' || '' }} + ${{ github.workspace }} + + - name: Throttle parallel build processes on arm64 + if: ${{ runner.os == 'macOS' && matrix.arch == 'arm64' }} + run: echo CMAKE_BUILD_PARALLEL_LEVEL=2 >> ${GITHUB_ENV} + + - name: Build + run: ${{ env.ARCH_WRAPPER }} cmake --build ${{ env.BUILD_DIR }} + + - name: Clear CCache stats + if: ${{ runner.os == 'macOS' }} + run: ccache --show-stats --zero-stats + + - name: Test + working-directory: ${{ env.BUILD_DIR }} + run: | + ${{ env.ARCH_WRAPPER }} bin/multipass_tests + + - name: Package + id: cmake-package + working-directory: ${{ env.BUILD_DIR }} + run: > + ${{ env.ARCH_WRAPPER }} cmake --build . --target package + + echo "name=$( ${{ runner.os != 'Windows' && 'basename *.pkg' || + '( Get-ChildItem .\packages\en-US\multipass-*.msi ).Name' }} ) " >> + ${{ runner.os != 'Windows' && '$GITHUB_OUTPUT' || '$env:GITHUB_OUTPUT' }} + + echo "path=$( ${{ runner.os != 'Windows' && 'greadlink -f *.pkg' || + '( Get-ChildItem .\packages\en-US\multipass-*.msi ).FullName' }} )" >> + ${{ runner.os != 'Windows' && '$GITHUB_OUTPUT' || '$env:GITHUB_OUTPUT' }} + + - name: Get package logs + if: ${{ failure() && steps.cmake-package.outcome == 'failure' }} + run: > + ${{ format('cat {0}/_CPack_Packages/{1}', env.BUILD_DIR, + runner.os == 'Windows' && 'win64/External/WiXOutput.log' || 'Darwin/productbuild/InstallOutput.log') }} + + - name: Upload package + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.cmake-package.outputs.name }} + path: ${{ steps.cmake-package.outputs.path }} + if-no-files-found: error + retention-days: 7 + + # Put the package on S3 for public consumption + - name: Publish package on S3 + id: s3-upload + uses: canonical/actions/s3-upload@release + with: + path: ${{ steps.cmake-package.outputs.path }} + bucket: ${{ env.S3_BUCKET }} + prefix: ${{ steps.build-params.outputs.label }} + public: true + storage-class: ONEZONE_IA + timeout-minutes: 5 + + # This shows up on this run's page + - name: Report public URL + run: | + echo "##[warning] Public URL: ${{ steps.s3-upload.outputs.url }}" + + - name: Store publishing outputs + if: always() + id: publish-data + run: > + echo "${{ runner.os }}-${{ matrix.arch }}-package=${{ steps.cmake-package.outputs.name }}" >> + ${{ runner.os != 'Windows' && '$GITHUB_OUTPUT' || '$env:GITHUB_OUTPUT' }} + + CombineAndPublishMacOSPackage: + # Want to run even if one of the builds above failed + if: always() + + needs: [BuildAndTest] + + runs-on: macos-13 + + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Retrieve the macOS x86 package + id: retrieve-x86 + if: ${{ needs.BuildAndTest.outputs.mac-x86-package }} + uses: actions/download-artifact@v4 + with: + name: ${{ needs.BuildAndTest.outputs.mac-x86-package }} + + - name: Retrieve the macOS ARM package + id: retrieve-arm + if: ${{ needs.BuildAndTest.outputs.mac-arm-package }} + uses: actions/download-artifact@v4 + with: + name: ${{ needs.BuildAndTest.outputs.mac-arm-package }} + + - name: Set the arch wrapper + run: > + echo "ARCH_WRAPPER=arch -arch $( sysctl machdep.cpu.brand_string | grep -q Apple && + echo arm64 || echo x86_64 )" >> ${GITHUB_ENV} + + - name: Combine the macOS package + id: combine-package + if: ${{ steps.retrieve-x86.outputs.download-path && steps.retrieve-arm.outputs.download-path }} + run: | + ${ARCH_WRAPPER} brew install python + ${ARCH_WRAPPER} brew install coreutils + ${ARCH_WRAPPER} python3 -m pip install --user --upgrade lxml + + PKG=${{ needs.BuildAndTest.outputs.mac-x86-package }} + PKG=${PKG/.x86_64/} + ${ARCH_WRAPPER} packaging/macos/merge_pkgs.py \ + ${{ needs.BuildAndTest.outputs.mac-x86-package }} \ + ${{ needs.BuildAndTest.outputs.mac-arm-package }} \ + ${PKG} + + ${ARCH_WRAPPER} packaging/macos/sign-and-notarize.sh \ + --app-signer - \ + ${PKG} + + echo "name=${PKG}" >> $GITHUB_OUTPUT + echo "path=$( greadlink -f ${PKG} )" >> $GITHUB_OUTPUT + + - name: Upload combined macOS package + if: ${{ steps.combine-package.outputs.path }} + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.combine-package.outputs.name }} + path: ${{ steps.combine-package.outputs.path }} + if-no-files-found: error + retention-days: 7 + + - name: Publish combined macOS package on S3 + if: ${{ steps.combine-package.outputs.path }} + id: s3-upload + uses: canonical/actions/s3-upload@release + with: + path: ${{ steps.combine-package.outputs.path }} + bucket: ${{ env.S3_BUCKET }} + prefix: ${{ needs.BuildAndTest.outputs.build-label }} + public: true + storage-class: ONEZONE_IA + timeout-minutes: 5 + + - name: Report public URL + run: | + echo "##[warning] Public URL: ${{ steps.s3-upload.outputs.url }}" + + DeleteSeparateMacPackages: + if: ${{ success() && needs.CombineAndPublishMacOSPackage.result == 'success' }} + + needs: [BuildAndTest, CombineAndPublishMacOSPackage] + + runs-on: ubuntu-latest + + steps: + - name: Delete unused artifacts from github + uses: geekyeggo/delete-artifact@v5 + with: + name: | + ${{ needs.BuildAndTest.outputs.mac-x86-package }} + ${{ needs.BuildAndTest.outputs.mac-arm-package }} + failOnError: false diff --git a/.gitignore b/.gitignore index 9d7db71493..5547864f2b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .vs .vscode cmake-build-* +.DS_Store CMakeLists.txt.user build @@ -27,3 +28,8 @@ src/client/gui/.dart_tool src/client/gui/flutter*.log .flutter-plugins .flutter-plugins-dependencies + +# wix build artifacts +packaging/windows/wix/obj/* +packaging/windows/custom-actions/packages/* +packaging/windows/custom-actions/x64/* diff --git a/.gitmodules b/.gitmodules index b57fea2b41..35448feba7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -14,6 +14,9 @@ [submodule "3rd-party/scope_guard"] path = 3rd-party/scope_guard url = https://github.com/ricab/scope_guard.git +[submodule "3rd-party/jsoncpp"] + path = 3rd-party/jsoncpp + url = https://github.com/open-source-parsers/jsoncpp.git [submodule "3rd-party/vcpkg"] path = 3rd-party/vcpkg url = https://github.com/microsoft/vcpkg diff --git a/3rd-party/CMakeLists.txt b/3rd-party/CMakeLists.txt index b0a5fa7f0b..2eb166e65d 100644 --- a/3rd-party/CMakeLists.txt +++ b/3rd-party/CMakeLists.txt @@ -86,6 +86,20 @@ target_include_directories(yaml INTERFACE target_link_libraries(yaml INTERFACE yaml-cpp) +include(ExternalProject) + +# QEMU itself +if (APPLE AND "qemu" IN_LIST MULTIPASS_BACKENDS) + add_subdirectory(qemu) +endif () + +if(MSVC) + set(JSONCPP_WITH_PKGCONFIG_SUPPORT OFF CACHE BOOL "Disable pkgconfig in jsoncpp" FORCE) + set(JSONCPP_WITH_POST_BUILD_UNITTEST OFF CACHE BOOL "Disable unit tests in jsoncpp" FORCE) + set(JSONCPP_WITH_TESTS OFF CACHE BOOL "Disable test executables in jsoncpp lib" FORCE) + add_subdirectory(jsoncpp) +endif() + # libssh config add_subdirectory(libssh) diff --git a/3rd-party/jsoncpp b/3rd-party/jsoncpp new file mode 160000 index 0000000000..9059f5cad0 --- /dev/null +++ b/3rd-party/jsoncpp @@ -0,0 +1 @@ +Subproject commit 9059f5cad030ba11d37818847443a53918c327b1 diff --git a/3rd-party/libssh/CMakeLists.txt b/3rd-party/libssh/CMakeLists.txt index 20a3602806..374fb1556a 100644 --- a/3rd-party/libssh/CMakeLists.txt +++ b/3rd-party/libssh/CMakeLists.txt @@ -17,7 +17,11 @@ set(WITH_EXAMPLES FALSE) set(WITH_SERVER TRUE) set(WITH_SFTP TRUE) -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-implicit-function-declaration -Wno-incompatible-pointer-types -Wno-int-conversion") +if(MSVC) + add_definitions(-Dssize_t=SSIZE_T) +else() + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-implicit-function-declaration -Wno-incompatible-pointer-types -Wno-int-conversion") +endif() set(LIBSSH_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/libssh/include diff --git a/3rd-party/qemu/CMakeLists.txt b/3rd-party/qemu/CMakeLists.txt new file mode 100644 index 0000000000..80b932435e --- /dev/null +++ b/3rd-party/qemu/CMakeLists.txt @@ -0,0 +1,82 @@ +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . +# + +## Ensure build deps are available +pkg_check_modules(GLIB REQUIRED glib-2.0) +pkg_check_modules(PIXMAN REQUIRED pixman-1) + +cmake_policy(SET CMP0097 NEW) # Use new empty GIT_SUBMODULES behavior + +include(FetchContent) +set(FETCHCONTENT_QUIET FALSE) +set(QEMU_SOURCE_DIR "${CMAKE_BINARY_DIR}/3rd-party/qemu") + +FetchContent_Declare(qemu + SOURCE_DIR ${QEMU_SOURCE_DIR} + GIT_REPOSITORY https://github.com/canonical/qemu.git + GIT_TAG v8.2.1+9p-uid-gid-map + GIT_SHALLOW TRUE + GIT_SUBMODULES "" + GIT_PROGRESS TRUE +) +FetchContent_MakeAvailable(qemu) + +ExternalProject_Add(qemu + SOURCE_DIR ${QEMU_SOURCE_DIR} + CONFIGURE_COMMAND test -f /config-host.mak || + /configure + --prefix=${CMAKE_BINARY_DIR} + --firmwarepath=${CMAKE_BINARY_DIR}/Resources/qemu/ + --ninja=ninja + --target-list=${HOST_ARCH}-softmmu + --enable-hvf + --enable-virtfs + --disable-bochs + --disable-cloop + --disable-docs + --disable-guest-agent + --disable-parallels + --disable-qed + --disable-libiscsi + --disable-vnc + --disable-xen + --disable-dmg + --disable-replication + --disable-snappy + --disable-lzo + --disable-live-block-migration + --disable-vvfat + --disable-curl + --disable-tests + --disable-nettle + --disable-libusb + --disable-bzip2 + --disable-gcrypt + --disable-gnutls + --disable-libvduse + --disable-vduse-blk-export + BUILD_COMMAND ninja + TEST_COMMAND "" +) + +install(PROGRAMS ${CMAKE_BINARY_DIR}/bin/qemu-img ${CMAKE_BINARY_DIR}/bin/qemu-system-${HOST_ARCH} + DESTINATION bin + COMPONENT multipassd +) + +install(FILES ${CMAKE_BINARY_DIR}/share/qemu/edk2-${HOST_ARCH}-code.fd + ${CMAKE_BINARY_DIR}/share/qemu/efi-virtio.rom + ${CMAKE_BINARY_DIR}/share/qemu/vgabios-stdvga.bin + DESTINATION Resources/qemu + COMPONENT multipassd +) diff --git a/BUILD.osx.md b/BUILD.osx.md new file mode 100644 index 0000000000..81b5cf80b5 --- /dev/null +++ b/BUILD.osx.md @@ -0,0 +1,90 @@ +Build instructions for Mac OS +============================= + +Environment Setup +----------------- +### XCode +Can be installed via the App Store. Once this is done, you may need to install the command line tooling too, to do this run: + + xcode-select --install + +Ensure you have development Frameworks for at least OS X 10.8 installed, with the typical compiler toolchain and "git". Avoid the version of cmake supplied, we need a newer one (see later). + +### Qt6 +#### Option 1: Using Qt official sources +Install the latest stable version of Qt6 LTS (6.2.4 at the moment): . + +If it tells you that XCode 5.0.0 needs to be installed, go to XCode > Preferences > Locations and make a selection in the _Command Line Tools_ box. + +Add Qt6 to your PATH environment variable, adding to your `.bash_profile` file the following line: + + export PATH=$PATH:~/Qt/6.2.4/clang_64/bin + +Adjust accordingly if you customized the Qt install directory. + +#### Option 2: Using Homebrew +Install Qt6: + + brew install qt6 + +### Cmake/OpenSSL +Building a Multipass package requires cmake 3.9 or greater. OpenSSL is also necessary at build time. The most convenient means to obtain these dependencies is with Homebrew . + + brew install cmake openssl@3 + +Building +--------------------------------------- + cd + git submodule update --init --recursive + +To build with official Qt sources do: + + cmake -Bbuild -H. -GNinja -DCMAKE_PREFIX_PATH=~/Qt/6.2.4/clang_64 + +Alternatively if using Qt6 from Homebrew, do + + cmake -Bbuild -H. -GNinja -DCMAKE_PREFIX_PATH=/usr/local/opt/qt6 + +or, if on Apple silicon, brew will store the Qt binaries in a different location. Additionally, OpenSSL will be in a similar location; `/opt/homebrew/Cellar/openssl@3`, which can be set in the project level `CMakeLists.txt` file. + + cmake -Bbuild -H. -GNinja -DCMAKE_PREFIX_PATH=/opt/homebrew/opt/qt6 + +Then start the build with: + + cd build/ + ninja + +Take care to adjust the `CMAKE_PREFIX_PATH` to the location you installed Qt above, or else cmake will complain about missing Qt6. + +Building in QtCreator +--------------------- +QtCreator will be missing all the environment adjustments made above. To get cmake to successfully configure, open the project and adjust the Build Environment (click the "Projects" icon of the left pane, scroll down). Then add the entries to the $PATH as above, and add the variables reported by `opem config env`. CMake should now succeed, and QtCreator allow you to edit the project files. + + +Creating a Package +------------------ +This is as simple as running + + ninja package + +or + + cpack + +Once it is complete, you will have a Multipass.pkg file in the build directory. + + +Tips and Tricks for development on OSX +====================================== + +Getting console output +---------------------- +To get console output from Multipass while installed, from one shell run: + + sudo launchctl debug system/com.canonical.multipassd --stdout --stderr + +and then from another shell, restart the multipassd daemon with + + sudo launchctl kickstart -k system/com.canonical.multipassd + +The console output from multipassd will appear on the former shell. diff --git a/BUILD.windows.md b/BUILD.windows.md new file mode 100644 index 0000000000..09cad57407 --- /dev/null +++ b/BUILD.windows.md @@ -0,0 +1,123 @@ +Build instructions for Windows 10 +================================= + +Environment Setup +----------------- +### Chocolatey +Install chocolatey, a package manager, to download the rest of the dependencies: + +Press Windows Key+X and Run Windows PowerShell(Admin) then follow the chocolatey instructions to "Install with Powershell.exe" + +After chocolatey is installed you can now install the rest of the dependencies: + + choco install visualstudio2019buildtools visualstudio2019-workload-vctools cmake ninja cmder qemu-img openssl -yfd + +You may have to disable Windows Defender Real-time protection if you want the packages to install quicker. +Search for Windows Defender Security Center, go to Virus & threat protection, then Virus and thread protection settings, disable Real-time protection. + +NOTE: visualcpp-build-tools is only the installer package. For this reason, choco cannot detect any new compiler tool updates so choco upgrade +will report no new updates available. To update the compiler and related tooling, you will need to search for "Add or remove programs", +find "Microsoft Visual Studio Installer" and click "Modify". + +### Git +You need to enable symlinks in Windows Git, have a look at [the git-for-windows docs](https://github.com/git-for-windows/git/wiki/Symbolic-Links). + +### Qt6 +Install the latest stable version of Qt6 (6.2.4 at the moment): . + +In the online installer, under Qt, select MSVC 2019 64-bit. + +If you already have Qt installed, run the MaintenanceTool included in the Qt directory to update to the latest version. + +Alternatively, download the [qtbase archive](https://download.qt.io/online/qtsdkrepository/windows_x86/desktop/qt6_624/qt.qt6.624.win64_msvc2019_64/6.2.4-0-202203140926qtbase-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64.7z) and extract it to `C:\Qt` (so it ends up in `C:\Qt\6.2.4`). + +### Path setup +You'll have to manually add CMake and Qt to your account's PATH variable. + +Search for "Edit environment variables for your account" then edit your Path variable. +Add the following: + `C:\Program Files\CMake\bin` + `C:\Qt\6.2.4\msvc2019_64\bin` + +### Cmder setup +Cmder is a sane terminal emulator for windows, which includes git and SSH support among other things. + +The following will setup a task that you can use to build things with the VS2019 compiler toolchain. + +Run cmder which should be installed by default on C:\tools\cmder\Cmder.exe +Click on the green "+" sign on the right lower corner of cmder +Select "Setup tasks..." +Click the "+" button to add a new task +In the task parameters box add (basically copying from cmd:Cmder task): + ``/icon "%CMDER_ROOT%\icons\cmder.ico"`` +In the commands box, add: + ``cmd /k ""%ConEmuDir%\..\init.bat" && "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Auxiliary\Build\vcvarsall.bat" x86_amd64" -new_console:d:%USERPROFILE%`` + +Give the task a name (first box), such as vs2019 and click Save Settings. + +Building +--------------------------------------- + +Run cmder, click on the green "+" and click on the vs2019 task +This will open a new terminal tab and run the VS2019 setup. CMake can now find the VS compiler. + + cd + git submodule update --init --recursive + mkdir build + cd build + cmake -GNinja -DCMAKE_BUILD_TYPE=RelWithDebInfo ../ + ninja + +This builds multipass and multipassd. +To create an installer, run `ninja package` + +Building (alternative, PowerShell only) +--------------------------------------- + +Using a Visual-Studio command-prompt-enabled PowerShell to build the project is also possible. +Open a new PowerShell terminal, then invoke the following commands: + +```pwsh +# Try to determine the Visual Studio install path +$VSPath = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -products Microsoft.VisualStudio.Product.BuildTools -latest -property installationPath + +# Import the PowerShell module +Import-Module "$VSPath\Common7\Tools\Microsoft.VisualStudio.DevShell.dll" + +# Enable VS developer PowerShell +Enter-VsDevShell -VsInstallPath "$VSPath" -DevCmdArguments '-arch=x64' +``` + +Then, follow the steps in the previous "Building" step to build the project. + +Running multipass +--------------------------------------- + +### Enable Hyper-V +Before starting multipassd, you'll have to enable the Hyper-V functionality in Windows 10 Pro. +See: https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/enable-hyper-v + + Press Windows Key + X, Select Windows PowerShell (Admin) + Run "Enable-WindowsOptionalFeature -Online -FeatureName:Microsoft-Hyper-V -All" + +### Start the daemon (multipassd) + Press Windows Key + X, Select Windows PowerShell (Admin) + Run multipassd (for example: multipassd --logger=stderr) + Alternatively, you can install multipassd as a Windows Service (Run "multipassd /install") + To stop and uninstall the Windows service, Run "multipassd /uninstall" + +### Run multipass + With the multipassd daemon now running on another shell (or as a windows service) you can now run multipass. + Press Windows Key + X, Select Windows PowerShell, or alternatively run cmd.exe on the search bar + Try "multipass help" + +### Permissions/privileges for multipassd +multipassd needs Administrator privileges in order to create symlinks when using mounts and to manage Hyper-V instances. + +If you don't need symlink support you can run multipassd on a less privileged shell but your user account +needs to be part of the Hyper-V Administrators group: + + Press Windows key + X, Select "Computer Management" + Under System Tools->Local Users and Groups->Groups + Select on Hyper-V Administrators, add your account + Sign out or reboot for changes to take effect diff --git a/CMakeLists.txt b/CMakeLists.txt index fdea0d490a..e4f0839f2d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,7 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) cmake_policy(SET CMP0079 NEW) # Allow target_link_libraries() in subdirs include(src/cmake/environment-utils.cmake) @@ -132,6 +132,20 @@ if(cmake_build_type_lower MATCHES "coverage") endif() endif() +if(UNIX) + set(HOST_ARCH ${CMAKE_HOST_SYSTEM_PROCESSOR}) + + if (${HOST_ARCH} STREQUAL "arm64") + set(HOST_ARCH "aarch64") + endif () + + if (APPLE AND ${HOST_ARCH} MATCHES "x86_64") + list(APPEND MULTIPASS_BACKENDS virtualbox) + endif() + + list(APPEND MULTIPASS_BACKENDS qemu) +endif() + # OpenSSL config find_package(OpenSSL REQUIRED) @@ -164,7 +178,7 @@ function(determine_version OUTPUT_VARIABLE) OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) - execute_process(COMMAND git describe --long + execute_process(COMMAND git describe --long --abbrev=8 WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} OUTPUT_VARIABLE GIT_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE) @@ -261,11 +275,14 @@ if(MSVC) add_definitions(-DLIBSSH_STATIC) # otherwise adds declspec specifiers to libssh apis add_definitions(-D_SILENCE_ALL_CXX17_DEPRECATION_WARNINGS) add_definitions(-DWIN32_LEAN_AND_MEAN) + set(MULTIPASS_BACKENDS hyperv virtualbox) + set(MULTIPASS_PLATFORM windows) else() add_compile_options(-Werror -Wall -pedantic -fPIC -Wno-error=deprecated-declarations) if(APPLE) add_definitions(-DMULTIPASS_PLATFORM_APPLE) + set(MULTIPASS_PLATFORM macos) add_definitions(-DMULTIPASS_COMPILER_APPLE_CLANG) else() # Linux diff --git a/data/icon.ico b/data/icon.ico new file mode 100644 index 0000000000..384e10c669 Binary files /dev/null and b/data/icon.ico differ diff --git a/include/multipass/console.h b/include/multipass/console.h index 98959021b1..3ca83e7a9c 100644 --- a/include/multipass/console.h +++ b/include/multipass/console.h @@ -22,8 +22,6 @@ #include -#include -#include #include namespace multipass diff --git a/include/multipass/constants.h b/include/multipass/constants.h index 879364a24d..00ad8bfe3b 100644 --- a/include/multipass/constants.h +++ b/include/multipass/constants.h @@ -44,6 +44,7 @@ constexpr auto home_automount_dir = "Home"; constexpr auto multipass_storage_env_var = "MULTIPASS_STORAGE"; constexpr auto driver_env_var = "MULTIPASS_VM_DRIVER"; +constexpr auto blueprints_url_env_var = "MULTIPASS_BLUEPRINTS_URL"; constexpr auto winterm_profile_guid = "{aaaa9e6d-1e09-4be6-b76c-82b4ba1885fb}"; // identifies the primary Multipass profile in Windows Terminal diff --git a/include/multipass/platform.h b/include/multipass/platform.h index a3e3a0ba95..56dff1665a 100644 --- a/include/multipass/platform.h +++ b/include/multipass/platform.h @@ -53,9 +53,6 @@ class Platform : public Singleton Platform(const Singleton::PrivatePass&) noexcept; // Get information on the network interfaces that are seen by the platform, indexed by name virtual std::map get_network_interfaces_info() const; - virtual QString get_blueprints_url_override() const; - virtual bool is_alias_supported(const std::string& alias, const std::string& remote) const; - virtual bool is_remote_supported(const std::string& remote) const; virtual bool is_backend_supported(const QString& backend) const; // temporary (?) virtual int chown(const char* path, unsigned int uid, unsigned int gid) const; virtual bool set_permissions(const std::filesystem::path& path, @@ -78,7 +75,6 @@ class Platform : public Singleton virtual SettingSpec::Set extra_client_settings() const; virtual QString default_driver() const; virtual QString default_privileged_mounts() const; - virtual bool is_image_url_supported() const; [[nodiscard]] virtual std::string bridge_nomenclature() const; virtual int get_cpus() const; virtual long long get_total_ram() const; diff --git a/include/multipass/vm_image_vault.h b/include/multipass/vm_image_vault.h index 3adaf70fbc..2b23c31c87 100644 --- a/include/multipass/vm_image_vault.h +++ b/include/multipass/vm_image_vault.h @@ -75,7 +75,6 @@ class VMImageVault : private DisabledCopyMove const Query& query, const PrepareAction& prepare, const ProgressMonitor& monitor, - const bool unlock, const std::optional& checksum, const Path& save_dir) = 0; virtual void remove(const std::string& name) = 0; diff --git a/packaging/FrameworkUtilities.cmake b/packaging/FrameworkUtilities.cmake new file mode 100644 index 0000000000..3b9df873a7 --- /dev/null +++ b/packaging/FrameworkUtilities.cmake @@ -0,0 +1,78 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +include(GetPrerequisites) + +# +# get_binary_rpaths(BINARY RPATHS_VAR) +# +# Analyses the $BINARY and places a list of rpaths specified in $RPATHS_VAR_OUT +# +function(get_binary_rpaths binary rpaths_var) + cmake_parse_arguments(RPATHS "" "LOADER_PATH" "" ${ARGN}) + + find_program(otool_cmd "otool") + mark_as_advanced(otool_cmd) + + if(otool_cmd) + execute_process( + COMMAND "${otool_cmd}" -l "${binary}" + OUTPUT_VARIABLE load_cmds_ov + ) + string(REGEX REPLACE "[^\n]+cmd LC_RPATH\n[^\n]+\n[^\n]+path ([^\n]+) \\(offset[^\n]+\n" "rpath \\1\n" load_cmds_ov "${load_cmds_ov}") + if(RPATHS_LOADER_PATH) + string(REGEX REPLACE "rpath @loader_path" "rpath ${RPATHS_LOADER_PATH}" load_cmds_ov "${load_cmds_ov}") + else() + string(REGEX REPLACE "rpath @loader_path[^\n]+" "" load_cmds_ov "${load_cmds_ov}") + endif() + string(REGEX REPLACE "rpath @executable_path[^\n]+" "" load_cmds_ov "${load_cmds_ov}") + string(REGEX MATCHALL "rpath [^\n]+" load_cmds_ov "${load_cmds_ov}") + string(REGEX REPLACE "rpath " "" load_cmds_ov "${load_cmds_ov}") + if(load_cmds_ov) + foreach(rpath ${load_cmds_ov}) + gp_append_unique(${rpaths_var} "${rpath}") + endforeach() + endif() + endif() + + set(${rpaths_var} ${${rpaths_var}} PARENT_SCOPE) +endfunction() + + +# +# install_frameworks(BINARY FRAMEWORK_DESTINATION) +# +# Analyses the $BINARY to determine all the frameworks/libraries it has an rpath dependency on. +# Then it tracks down those frameworks/libraries on the filesystem and copies them (preserving the +# rpath-specified directory structure) into the $FRAMEWORK_DESTINATION +# +# Note: this does not update the rpath specified in $BINARY. Better to use: +# set_target_properties( PROPERTIES INSTALL_RPATH "@executable_path/../lib" ) +# +function(install_frameworks binary framework_destination) + message(STATUS "Attempting to auto-copy all the $rpath linked frameworks of ${binary} into the install directory ${framework_destination}") + get_binary_rpaths("${binary}" BINARY_RPATHS ${ARGN}) + get_prerequisites("${binary}" RPATHED_LIBS 1 1 0 "" "${BINARY_RPATHS}") + + foreach(rpath ${BINARY_RPATHS}) + foreach(lib ${RPATHED_LIBS}) + string(REPLACE "@rpath" "" lib "${lib}") + message(STATUS "Checking for ${rpath}${lib}") + if(EXISTS "${rpath}${lib}") + message(STATUS "copying COMMAND ${CMAKE_COMMAND} -E copy ${rpath}${lib} ${framework_destination}${lib}") + execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${rpath}${lib}" "${framework_destination}${lib}") + endif() + endforeach() + endforeach() +endfunction() diff --git a/packaging/cleanup.cmake b/packaging/cleanup.cmake new file mode 100644 index 0000000000..b76d1d41d2 --- /dev/null +++ b/packaging/cleanup.cmake @@ -0,0 +1,19 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +file(REMOVE_RECURSE "${CPACK_TEMPORARY_INSTALL_DIRECTORY}/multipassd${CPACK_PACKAGING_INSTALL_PREFIX}/lib/pkgconfig") +file(REMOVE "${CPACK_TEMPORARY_INSTALL_DIRECTORY}/multipassd${CPACK_PACKAGING_INSTALL_PREFIX}/lib/libgtest.a") +file(REMOVE "${CPACK_TEMPORARY_INSTALL_DIRECTORY}/multipassd${CPACK_PACKAGING_INSTALL_PREFIX}/lib/libgtest_main.a") +file(REMOVE "${CPACK_TEMPORARY_INSTALL_DIRECTORY}/multipassd${CPACK_PACKAGING_INSTALL_PREFIX}/lib/libgmock.a") +file(REMOVE "${CPACK_TEMPORARY_INSTALL_DIRECTORY}/multipassd${CPACK_PACKAGING_INSTALL_PREFIX}/lib/libgmock_main.a") diff --git a/packaging/cpack.cmake b/packaging/cpack.cmake new file mode 100644 index 0000000000..a3b258321d --- /dev/null +++ b/packaging/cpack.cmake @@ -0,0 +1,169 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +# Helpful docs: +# https://cmake.org/Wiki/CMake:Component_Install_With_CPack +# https://cmake.org/Wiki/CMake:CPackConfiguration +# +# Vital concept to understand are "Components" - a component is a collection of files to be installed. +# Any file to be packaged for installation must be part of a component - note the COMPONENT flag for +# "install". CPack then includes it in the generated package, to be installed at the destination +# specified in the "install" (plus a CPack-only prefix set below). +# +# Components are intended to be self-contained, as they may be installed individually. Components also +# smap directly to the options made visible to the user in the installer. +# + +set(CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION ON) # helps avoid errors + +set(CPACK_COMPONENTS_GROUPING ALL_COMPONENTS_IN_ONE) +set(CPACK_COMPONENTS_ALL multipassd multipass multipass_gui) + +set(CPACK_COMPONENT_MULTIPASSD_DISPLAY_NAME "Multipass Daemon") +set(CPACK_COMPONENT_MULTIPASSD_DESCRIPTION + "Background process that creates and manages virtual machines") +set(CPACK_COMPONENT_MULTIPASS_DISPLAY_NAME "Clients (CLI and GUI)") +set(CPACK_COMPONENT_MULTIPASS_DESCRIPTION + "Command line tool to talk to the multipass daemon") +set(CPACK_COMPONENT_MULTIPASS_GUI_DISPLAY_NAME "Multipass Desktop GUI") +set(CPACK_COMPONENT_MULTIPASS_GUI_DESCRIPTION + "Desktop client for Multipass") + +set(CPACK_COMPONENT_MULTIPASSD_REQUIRED TRUE) +set(CPACK_COMPONENT_MULTIPASS_REQUIRED TRUE) +set(CPACK_COMPONENT_MULTIPASS_GUI_REQUIRED TRUE) + +# set default CPack Packaging options +set(CPACK_PACKAGE_NAME "multipass") +set(CPACK_PACKAGE_VENDOR "canonical") +set(CPACK_PACKAGE_CONTACT "contact@canonical.com") +set(CPACK_PACKAGE_VERSION "${MULTIPASS_VERSION}") + +if (APPLE) + set(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}.${HOST_ARCH}") +endif() + +#set(CPACK_PACKAGE_ICON "${PROJECT_SOURCE_DIR}/cmake/sac_logo.png") + +if (CMAKE_BUILD_TYPE STREQUAL "Release") + set(CPACK_STRIP_FILES 1) +endif () + +# set (CPACK_PACKAGE_DESCRIPTION_FILE ...) +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Easily create, control and connect to Ubuntu instances") + +if (MSVC) + # multipassd depends on qemu-img.exe indirectly (called to convert qcow images to VHDX format) + find_program(QEMU_IMG qemu-img.exe PATH_SUFFIXES "qemu") + if (NOT QEMU_IMG) + message(FATAL_ERROR "qemu-img not found!") + endif() + + # InstallRequiredSystemLibraries finds the VC redistributable dlls shipped with the Visual Studio compiler tools + # and creats an install(PROGRAMS ...) rule using the destination and component IDs setup below. + set(CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION bin) + set(CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT multipassd) + if(cmake_build_type_lower STREQUAL "debug") + set(CMAKE_INSTALL_DEBUG_LIBRARIES TRUE) + set(CMAKE_INSTALL_UCRT_LIBRARIES TRUE) + endif() + include(InstallRequiredSystemLibraries) + + # The qemu-img path found may actually be a chocolatey generated shim. Thankfully such shims have a command line + # option that returns the actual executable target of the shim. + execute_process(COMMAND ${QEMU_IMG} --shimgen-noop + OUTPUT_VARIABLE QEMU_IMG_OUTPUT) + string(REGEX MATCH "path to executable: (.*)[\n\r\t ]+working" QEMU_IMG_OUTPUT_REGEX_MATCH "${QEMU_IMG_OUTPUT}") + if (CMAKE_MATCH_1) + set(REAL_QEMU_IMG ${CMAKE_MATCH_1}) + string(REPLACE "\\" "/" REAL_QEMU_IMG ${REAL_QEMU_IMG}) + string(STRIP ${REAL_QEMU_IMG} REAL_QEMU_IMG) + else() + set(REAL_QEMU_IMG ${QEMU_IMG}) + endif() + + # Finally copy the real qemu-img executable into our package + install(FILES "${REAL_QEMU_IMG}" DESTINATION bin COMPONENT multipassd) + + # fixup_bundle determines the dependencies of the given executable and copies them into the final package. + # fixup_bundle assumes the copy destination is the same directory of the given executable, hence why it's pre-fixed + # with CMAKE_INSTALL_PREFIX as that contains the correct directory where the package is assembled. + # The third parameter of fixup_bundle is a directory to search for dependencies; here we assume qemu-img.exe deps + # are contained in the same source directory where it was copied from + get_filename_component(QEMU_IMG_DIR ${REAL_QEMU_IMG} DIRECTORY) + install(CODE " + include(BundleUtilities) + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/bin/qemu-img.exe\" \"\" \"${QEMU_IMG_DIR}\") + " COMPONENT multipassd) + + set(CPACK_SOURCE_DIR "${CMAKE_SOURCE_DIR}") + set(CPACK_BUILD_TYPE "${CMAKE_BUILD_TYPE}") + + set(CPACK_GENERATOR External) + set(CPACK_EXTERNAL_ENABLE_STAGING ON) + + set(CPACK_EXTERNAL_PACKAGE_SCRIPT "${CMAKE_SOURCE_DIR}/packaging/windows/CPackExternal.cmake") +endif() + +if(APPLE) + set(CPACK_OSX_DEPLOYMENT_TARGET "${CMAKE_OSX_DEPLOYMENT_TARGET}") + set(CPACK_RESOURCE_FILE_WELCOME "${PROJECT_SOURCE_DIR}/packaging/macos/WELCOME.html") + set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/packaging/macos/LICENCE.html") + set(CPACK_RESOURCE_FILE_README "${PROJECT_SOURCE_DIR}/packaging/macos/README.html") + set(CPACK_GENERATOR "productbuild") + set(CPACK_productbuild_COMPONENT_INSTALL ON) + + set(CPACK_PACKAGING_INSTALL_PREFIX "/Library/Application Support/com.canonical.multipass") + list(APPEND CPACK_INSTALL_COMMANDS "bash -x ${CMAKE_SOURCE_DIR}/packaging/macos/fixup-qt6-libs-rpath.sh ${CMAKE_BINARY_DIR}") + list(APPEND CPACK_INSTALL_COMMANDS "bash -x ${CMAKE_SOURCE_DIR}/packaging/macos/install-ssl-libs.sh ${CMAKE_BINARY_DIR}") + list(APPEND CPACK_INSTALL_COMMANDS "bash -x ${CMAKE_SOURCE_DIR}/packaging/macos/fixup-qemu-and-deps.sh ${CMAKE_BINARY_DIR}") + + set(MULTIPASSD_PLIST "com.canonical.multipassd.plist") + configure_file("${CMAKE_SOURCE_DIR}/packaging/macos/${MULTIPASSD_PLIST}.in" + "${CMAKE_BINARY_DIR}/${MULTIPASSD_PLIST}" @ONLY) + configure_file("${CMAKE_SOURCE_DIR}/packaging/macos/postinstall-multipassd.sh.in" + "${CMAKE_BINARY_DIR}/postinstall-multipassd.sh" @ONLY) + configure_file("${CMAKE_SOURCE_DIR}/packaging/macos/postinstall-multipass.sh.in" + "${CMAKE_BINARY_DIR}/postinstall-multipass.sh" @ONLY) + configure_file("${CMAKE_SOURCE_DIR}/packaging/macos/postinstall-multipass-gui.sh.in" + "${CMAKE_BINARY_DIR}/postinstall-multipass-gui.sh" @ONLY) + + install(FILES "${CMAKE_BINARY_DIR}/${MULTIPASSD_PLIST}" DESTINATION Resources COMPONENT multipassd) + install(DIRECTORY "${CMAKE_SOURCE_DIR}/completions" DESTINATION Resources COMPONENT multipass) + install(DIRECTORY "${CMAKE_BINARY_DIR}/lib/" DESTINATION lib COMPONENT multipassd) + + set(CPACK_COMPONENT_MULTIPASS_GUI_PLIST "${CMAKE_SOURCE_DIR}/packaging/macos/multipass-gui-component.plist") + + set(CPACK_PREFLIGHT_MULTIPASSD_SCRIPT "${CMAKE_SOURCE_DIR}/packaging/macos/preinstall-multipassd.sh") + set(CPACK_POSTFLIGHT_MULTIPASSD_SCRIPT "${CMAKE_BINARY_DIR}/postinstall-multipassd.sh") + set(CPACK_POSTFLIGHT_MULTIPASS_SCRIPT "${CMAKE_BINARY_DIR}/postinstall-multipass.sh") + set(CPACK_POSTFLIGHT_MULTIPASS_GUI_SCRIPT "${CMAKE_BINARY_DIR}/postinstall-multipass-gui.sh") + + # Cleans up the installed package + set(CPACK_PRE_BUILD_SCRIPTS "${CMAKE_SOURCE_DIR}/packaging/cleanup.cmake") + + # Signs the binaries using ad-hoc signing + set(CPACK_POST_BUILD_SCRIPTS "${CMAKE_SOURCE_DIR}/packaging/macos/post_build.cmake") + + # CPack doesn't support a direct way to customise the Distribution.dist file, but the template + # CPack.distribution.dist.in is searched for in the CMAKE_MODULE_PATH before CMAKE_ROOT, so as a hack, + # point it to a local directory with our custom template + set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/packaging/macos") + + install(FILES "${CMAKE_SOURCE_DIR}/packaging/macos/uninstall.sh" + DESTINATION . COMPONENT multipassd) +endif() + +# must be last +include(CPack) diff --git a/packaging/macos/CPack.distribution.dist.in b/packaging/macos/CPack.distribution.dist.in new file mode 100644 index 0000000000..3e5ca18a1e --- /dev/null +++ b/packaging/macos/CPack.distribution.dist.in @@ -0,0 +1,29 @@ + + + @CPACK_PACKAGE_NAME@ + + + + + + + + + @CPACK_PACKAGEMAKER_CHOICES@ + + + + diff --git a/packaging/macos/Info.plist b/packaging/macos/Info.plist new file mode 100644 index 0000000000..3d3c9efea4 --- /dev/null +++ b/packaging/macos/Info.plist @@ -0,0 +1,25 @@ + + + + + CFBundleExecutable + + CFBundleIdentifier + + CFBundleName + Multipass + CFBundlePackageType + APPL + LSMinimumSystemVersion + 10.15 + CFBundleIconFile + icon.icns + + LSUIElement + + + NSHighResolutionCapable + + + + diff --git a/packaging/macos/LICENCE.html b/packaging/macos/LICENCE.html new file mode 100644 index 0000000000..0ed6298251 --- /dev/null +++ b/packaging/macos/LICENCE.html @@ -0,0 +1,1641 @@ + + + + + +

Multipass

+ +

Copyright © Canonical Ltd.

+

GPL-3.0

+ +

https://github.com/canonical/multipass/

+ +

Open source projects used directly:

+ + +
+ +

Additional binaries used from homebrew:

+ + +
+ +

Licensing:

+

Below is a summary of the licensing used in the respective projects. See their source repositories, linked above, for details.

+ +
    +
  • fmt: BSD 2-Clause "Simplified" License; Copyright (c) 2012 - 2016, Victor Zverovich
  • +
  • grpc: Apache License 2.0
  • +
  • abseil-cpp: Apache License 2.0
  • +
  • c-ares: MIT License; Copyright (c) 2007 - 2018, Daniel Stenberg with many contributors, see AUTHORS file.
  • +
  • gflags: BSD 3-Clause "New" or "Revised" License; Copyright (c) 2006, Google Inc.
  • +
  • protobuf: BSD 3-Clause "New" or "Revised" License; Copyright 2008 Google Inc.
  • +
  • zlib: zlib License; (C) 1995-2017 Jean-loup Gailly and Mark Adler
  • +
  • libssh: +
      +
    • GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information
    • +
    • OpenSSL Exception
    • +
    +
  • +
  • poco: Boost Software License - Version 1.0 - August 17th, 2003
  • +
  • qt: GNU LGPL Version 3; Copyright (c) 2016 The Qt Company
  • +
  • semver: MIT License; Copyright (c) 2015 Marko Živanović
  • +
  • xz-embedded: zx-embedded License;
  • +
  • yaml-cpp: MIT License; Copyright (c) 2008-2015 Jesse Beder.
  • +
  • gettext (libintl): GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information
  • +
  • glib: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information
  • +
  • gmp: GNU LGPL Version 3 License; See AUTHORS file for Copyright information
  • +
  • gnutls: GNU LGPL Version 2.1 and 3 Licenses; See AUTHORS file for Copyright information
  • +
  • libffi: libffi License; Copyright (c) 1996-2014 Anthony Green, Red Hat, Inc and others.
  • +
  • libtasn1: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information
  • +
  • libunistring: GNU LGPL Version 3 License; See AUTHORS file for Copyright information
  • +
  • nettle: GNU LGPL Version 3 License; See AUTHORS file for Copyright information
  • +
  • p11-kit: p11-kit License;
  • +
  • pcre: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information
  • +
  • qemu (qemu-img): GNU GPL Version 2 License; See AUTHORS file for Copyright information
  • +
  • openssl: +
      +
    • OpenSSL; Copyright (c) 1998-2020 The OpenSSL Project.
    • +
    • SSLeay; Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
    • +
    +
+
+ +

Licenses:

+

Below are the contents of all the licenses used across all the projects distributed along with Multipass.

+ +

Apache License 2.0

+

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:

+
    +
  1. You must give any other recipients of the Work or Derivative Works a +copy of this License; and
  2. + +
  3. You must cause any modified files to carry prominent notices stating +that You changed the files; and
  4. + +
  5. 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
  6. + +
  7. 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. +
  8. + +
+ +

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

+ + +
+ +

Boost Software License - Version 1.0 - August 17th, 2003

+

Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following:

+ +

The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor.

+ +

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, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE.

+
+ +

BSD 2-Clause "Simplified" License

+

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 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 HOLDER 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.

+
+ +

BSD 3-Clause "New" or "Revised" License

+

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 Google Inc. 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 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. +

+
+ +

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

+
+ +

GNU GENERAL PUBLIC LICENSE
+Version 2, June 1991

+ +

Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

+ +

Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.

+ +

Preamble

+ +

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.

+ +

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

+ +

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

+ +

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

+ +

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

+ +

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

+ +

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

+ +

The precise terms and conditions for copying, distribution and modification follow.

+ +

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

+ +

0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".

+ +

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.

+ +

1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.

+ +

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

+ +

2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

+ +
+

a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.

+ +

b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.

+ +

c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)

+
+ +

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

+ +

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.

+ +

In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.

+ +

3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:

+ +
+

a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

+ +

b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

+ +

c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)

+
+ +

The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.

+ +

If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.

+ +

4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

+ +

5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.

+ +

6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.

+ +

7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.

+ +

If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.

+ +

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.

+ +

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

+ +

8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.

+ +

9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

+ +

Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.

+ +

10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

+ +

NO WARRANTY

+ +

11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

+ +

12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

+ +

END OF TERMS AND CONDITIONS

+
+ +

GNU LGPL Version 2.1 License

+ +

GNU LESSER GENERAL PUBLIC LICENSE
+Version 2.1, February 1999

+ +

Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

+ +

Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.

+ +

[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.]

+ +

Preamble

+ +

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.

+ +

This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. +

+

When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.

+ +

To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. +

+

For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.

+ +

We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.

+ +

To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.

+

+ Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.

+ +

Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.

+ +

When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.

+ +

We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.

+ +

For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. +

+

In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.

+ +

Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. +

+

The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.

+ +

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

+ +

0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".

+ +

A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.

+ +

The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)

+ +

"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.

+ +

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.

+ +

1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. +

+

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

+ +

2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: +

+ +
+

a) The modified work must itself be a software library.

+

b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.

+

c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.

+

d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.

+ + +

(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) +

+

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. +

+

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. +

+

In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. +

+

3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.

+ +

Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. +

+

This option is useful when you wish to copy part of the code of the Library into a program that is not a library. +

+

4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. +

+ +

If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.

+ +

5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.

+ +

However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.

+ +

When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.

+ +

If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)

+ +

Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.

+ +

6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.

+

+ You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:

+ +

a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)

+ +

b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.

+

+c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.

+ +

d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.

+ +

e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.

+
+ +

For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.

+ +

It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.

+ +

7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:

+ +
+

a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.

+ +

b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.

+ +

8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

+

+9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.

+

+10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.

+ +

11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.

+

+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.

+ +

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.

+ +

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

+

+12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.

+

+13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.

+

+14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

+

+NO WARRANTY

+

+15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

+

+16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

+ + +

END OF TERMS AND CONDITIONS

+
+ +

GNU LGPL Version 3 License

+ +

GNU LESSER GENERAL PUBLIC LICENSE
+Version 3, 29 June 2007

+ +

Copyright (C) 2007 Free Software Foundation, Inc. http://fsf.org/

+ +

Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed.

+ +

This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below.

+ +0. Additional Definitions. + +

As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License.

+ +

"The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below.

+ +

An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library.

+ +

A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version".

+ +

The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version.

+ +

The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work.

+ +1. Exception to Section 3 of the GNU GPL. + +

You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL.

+ +2. Conveying Modified Versions. + +

If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version:

+ +
  • a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or
  • + +
  • b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy.
  • +
3. Object Code Incorporating Material from Library Header Files. + +

The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following:

+ +
  • a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License.
  • + +
  • b) Accompany the object code with a copy of the GNU GPL and this license + document.
  • +
4. Combined Works. + +

You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following:

+ +
  • a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License.
  • + +
  • b) Accompany the Combined Work with a copy of the GNU GPL and this license + document.
  • + +
  • c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document.
  • + +
  • d) Do one of the following: + +
    • 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source.
    • + +
    • 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version.
    • + +
  • + +
  • e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.)
  • +
5. Combined Libraries. + +

You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following:

+ +
  • a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License.
  • + +
  • b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work.
  • + +
6. Revised Versions of the GNU Lesser General Public License. + +

The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation.

+ +

If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library.

+
+ +

ISC License

+

Copyright (c) 2015, Google Inc.

+ +

+Permission to use, copy, modify, and/or 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. +

+
+ +

MIT License

+

+Permission to use, copy, modify, and distribute this software and its documentation +for any purpose and without fee is hereby granted, provided that the above copyright +notice appear in all copies and that both that copyright notice and this permission +notice appear in supporting documentation, and that the name of M.I.T. not be used +in advertising or publicity pertaining to distribution of the software without +specific, written prior permission. M.I.T. makes no representations about the +suitability of this software for any purpose. It is provided "as is" without express +or implied warranty. +

+
+ +

OpenSSL License

+ +

Copyright (c) 1998-2011 The OpenSSL 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.

+ +

3. All advertising materials mentioning features or use of this + software must display the following acknowledgment: + "This product includes software developed by the OpenSSL Project + for use in the OpenSSL Toolkit. (http://www.openssl.org/)"

+ +

4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + endorse or promote products derived from this software without + prior written permission. For written permission, please contact + openssl-core@openssl.org.

+ +

5. Products derived from this software may not be called "OpenSSL" + nor may "OpenSSL" appear in their names without prior written + permission of the OpenSSL Project.

+ +

6. Redistributions of any form whatsoever must retain the following + acknowledgment: + "This product includes software developed by the OpenSSL Project + for use in the OpenSSL Toolkit (http://www.openssl.org/)"

+ +

THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY +EXPRESSED 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 OpenSSL PROJECT OR +ITS 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.

+ +

This product includes cryptographic software written by Eric Young +(eay@cryptsoft.com). This product includes software written by Tim +Hudson (tjh@cryptsoft.com).

+
+ +

SSLeay License

+

Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
+All rights reserved.

+ +

This package is an SSL implementation written
+by Eric Young (eay@cryptsoft.com).
+The implementation was written so as to conform with Netscapes SSL.

+ +

This library is free for commercial and non-commercial use as long as +the following conditions are aheared to. The following conditions +apply to all code found in this distribution, be it the RC4, RSA, +lhash, DES, etc., code; not just the SSL code. The SSL documentation +included with this distribution is covered by the same copyright terms +except that the holder is Tim Hudson (tjh@cryptsoft.com).

+ +

Copyright remains Eric Young's, and as such any Copyright notices in +the code are not to be removed.
+If this package is used in a product, Eric Young should be given attribution +as the author of the parts of the library used.
+This can be in the form of a textual message at program startup or +in documentation (online or textual) provided with the package.

+ +

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 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. All advertising materials mentioning features or use of this software + must display the following acknowledgement:
+ "This product includes cryptographic software written by
+ Eric Young (eay@cryptsoft.com)"

+

The word 'cryptographic' can be left out if the rouines from the library + being used are not cryptographic related :-).

+

4. If you include any Windows specific code (or a derivative thereof) from + the apps directory (application code) you must include an acknowledgement:
+ "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"

+ +

THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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.

+ +

The licence and distribution terms for any publically available version or +derivative of this code cannot be changed. i.e. this code cannot simply be +copied and put under another distribution licence
+[including the GNU Public Licence.] +

+
+ +

libssh OpenSSL Exception

+

+Linking with OpenSSL
+ 17. In addition, as a special exception, we give permission to link the code of +its release of libssh with the OpenSSL project's "OpenSSL" library (or with modified +versions of it that use the same license as the "OpenSSL" library), and distribute +the linked executables. You must obey the GNU Lesser General Public License in all +respects for all of the code used other than "OpenSSL". If you modify this file, you +may extend this exception to your version of the file, but you are not obligated to +do so. If you do not wish to do so, delete this exception statement from your +version. +

+
+ +

libffi License

+

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. +

+
+ +

p11-kit License

+ +

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.

+

* The names of contributors to this software may not 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. +

+
+ +

xz-embedded License

+

+All the files in this package have been written by Lasse Collin +and/or Igor Pavlov. All these files have been put into the +public domain. You can do whatever you want with these files.

+ +

As usual, this software is provided "as is", without any warranty. +

+
+ +

zlib License

+

+This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software.

+ +

Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions:

+ +

1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required.

+

2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software.

+

3. This notice may not be removed or altered from any source distribution.

+ +
  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+

If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code.

+ +

If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. +

+ + + diff --git a/packaging/macos/README.html b/packaging/macos/README.html new file mode 100644 index 0000000000..6152fb9f10 --- /dev/null +++ b/packaging/macos/README.html @@ -0,0 +1,27 @@ + + + + + + +

A couple details:

+
    +
  • Use a keyboard shortcut (⌘⌥U) to open a shell in your primary instance
  • +
  • Your home directory will be automatically mounted in
    ~/Home in the primary instance
  • +
  • There's a checkbox under the "About" item in the system menu to toggle the system menu starting automatically on login
  • +
+
+ +Make sure to check out the latest release notes on GitHub. + +

Minimum System Requirements

+
    +
  • macOS 13 Ventura or later.
  • +
+ + + diff --git a/packaging/macos/WELCOME.html b/packaging/macos/WELCOME.html new file mode 100644 index 0000000000..f6834e1d7e --- /dev/null +++ b/packaging/macos/WELCOME.html @@ -0,0 +1,20 @@ + + + + + +

Multipass: Ubuntu at your fingertips.

+ +

Welcome to the Multipass package installer. This will set up Multipass on your computer.

+ +

Multipass gives you Ubuntu VMs in seconds. Just run multipass launch and it will do all the setup for you.

+ +

For more information, visit canonical.com/multipass.

+ +

You will be guided through the steps necessary to install this software.

+ + diff --git a/packaging/macos/com.canonical.multipassd.plist.in b/packaging/macos/com.canonical.multipassd.plist.in new file mode 100644 index 0000000000..30ec02fe8b --- /dev/null +++ b/packaging/macos/com.canonical.multipassd.plist.in @@ -0,0 +1,41 @@ + + + + + Label + com.canonical.multipassd + + EnvironmentVariables + + PATH + @CPACK_PACKAGING_INSTALL_PREFIX@/bin:/usr/bin:/bin:/usr/sbin:/sbin + + + ProgramArguments + + @CPACK_PACKAGING_INSTALL_PREFIX@/bin/multipassd + --verbosity + debug + + + KeepAlive + + + Sockets + + Listeners + + SockServiceName + 50051 + SockType + stream + + + + StandardOutPath + /Library/Logs/Multipass/multipassd.log + StandardErrorPath + /Library/Logs/Multipass/multipassd.log + + + diff --git a/packaging/macos/fixup-qemu-and-deps.sh b/packaging/macos/fixup-qemu-and-deps.sh new file mode 100755 index 0000000000..3294e40cb9 --- /dev/null +++ b/packaging/macos/fixup-qemu-and-deps.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +set -euo pipefail + +CMAKE_BINARY_DIR=$1 +EXECUTABLE_PATH="@executable_path/../lib" + +otool_qemu_system=$(otool -L ${CMAKE_BINARY_DIR}/bin/qemu-system-*) +otool_qemu_img=$(otool -L ${CMAKE_BINARY_DIR}/bin/qemu-img) + +if ! echo $otool_qemu_system | grep -q @rpath && ! echo $otool_qemu_system | grep -q ${EXECUTABLE_PATH}; then + dylibbundler -of -x ${CMAKE_BINARY_DIR}/bin/qemu-system-* -b -d ${CMAKE_BINARY_DIR}/lib/ -p @rpath -i /usr/lib + install_name_tool -add_rpath "@executable_path/../lib" ${CMAKE_BINARY_DIR}/bin/qemu-system-* +fi + +if ! echo $otool_qemu_img | grep -q @rpath && ! echo $otool_qemu_img | grep -q ${EXECUTABLE_PATH}; then + dylibbundler -of -x ${CMAKE_BINARY_DIR}/bin/qemu-img -b -d ${CMAKE_BINARY_DIR}/lib/ -p @rpath -i /usr/lib + install_name_tool -add_rpath "@executable_path/../lib" "${CMAKE_BINARY_DIR}/bin/qemu-img" +fi diff --git a/packaging/macos/fixup-qt6-libs-rpath.sh b/packaging/macos/fixup-qt6-libs-rpath.sh new file mode 100644 index 0000000000..7108bde9da --- /dev/null +++ b/packaging/macos/fixup-qt6-libs-rpath.sh @@ -0,0 +1,79 @@ +#!/bin/bash + +# Script: fixup-qt6-libs-rpath.sh +# If using the Brew Qt6 libraries, they have a problem: they're trickier to relocate as +# they're not compiled with rpath enabled. +# Ref: https://github.com/Homebrew/homebrew-core/issues/3219#issuecomment-235763791 +# +# To make them work in a relocatable package, need to edit the paths to these libs in all +# the binaries to use rpaths. +# +# The libs shipped by Qt do not have this issue. + +set -u + +QT_FRAMEWORKS="QtCore QtNetwork QtWidgets QtDBus QtPrintSupport" +BINARIES="multipass multipassd sshfs_server" +QT6_PATH="$(brew --prefix qt6)" + +if [ $# -ne 1 ]; then + echo "Argument required" + exit 1; +fi + +CMAKE_BINARY_DIR=$1 +BINARY_DIR="$1/bin" + +# Check if brew libs used. If not, nothing to do +if ! otool -L "$BINARY_DIR/multipass" | grep -q "${QT6_PATH}"; then + echo "Not using Qt6 from Homebrew, nothing to do" + exit 0; +fi + +# Copy libs to temporary location +LIB_DIR="$CMAKE_BINARY_DIR/lib" + +RPATH_CHANGES=() +QT_VERSION=$( basename $( readlink ${QT6_PATH} ) ) +CELLAR_PATH="$(brew --prefix)/Cellar/qt" +for framework in ${QT_FRAMEWORKS}; do + framework_dir="${framework}.framework/Versions/A" + framework_path="${framework_dir}/${framework}" + + RPATH_CHANGES+=("-change") + RPATH_CHANGES+=("${QT6_PATH}/${QT_VERSION}/lib/${framework_path}") + RPATH_CHANGES+=("@rpath/${framework_path}") + + RPATH_CHANGES+=("-change") + RPATH_CHANGES+=("${QT6_PATH}/lib/${framework_path}") + RPATH_CHANGES+=("@rpath/${framework_path}") + + RPATH_CHANGES+=("-change") + RPATH_CHANGES+=("${CELLAR_PATH}/${QT_VERSION}/lib/${framework_path}") + RPATH_CHANGES+=("@rpath/${framework_path}") + + mkdir -p "${LIB_DIR}/${framework_dir}" + cp -fv "${QT6_PATH}/lib/${framework_path}" \ + "${LIB_DIR}/${framework_dir}" + chmod +w "${LIB_DIR}/${framework_path}" + + dylibbundler -of -x "${LIB_DIR}/${framework_path}" -b -d ${CMAKE_BINARY_DIR}/lib/ -p @rpath -i /usr/lib/ -i @rpath -i @executable_path -i @loader_path + + # Add rpaths for package + install_name_tool -add_rpath "@loader_path/../../../" "${LIB_DIR}/${framework_path}" + + install_name_tool "-id" "@rpath/${framework_path}" "${LIB_DIR}/${framework_path}" + + QT6_DEPS=$(otool -L ${QT6_PATH}/lib/${framework_path} | grep ${CELLAR_PATH} | awk -F '\t' -F ' ' '{ print $1 }') + for dep in ${QT6_DEPS:-}; do + BASE_DEP=$( basename ${dep} ) + install_name_tool "-change" "${dep}" "@rpath/${BASE_DEP}.framework/Versions/A/${BASE_DEP}" "${LIB_DIR}/${framework_path}" + done + + chmod -w "${LIB_DIR}/${framework_path}" +done + +# Edit the binaries to point to these newly edited libs +for binary in ${BINARIES}; do + install_name_tool "${RPATH_CHANGES[@]}" "${BINARY_DIR}/${binary}" +done diff --git a/packaging/macos/icon.icns b/packaging/macos/icon.icns new file mode 100644 index 0000000000..ecc77d3260 Binary files /dev/null and b/packaging/macos/icon.icns differ diff --git a/packaging/macos/install-ssl-libs.sh b/packaging/macos/install-ssl-libs.sh new file mode 100644 index 0000000000..1422d01680 --- /dev/null +++ b/packaging/macos/install-ssl-libs.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +# Script: fixup-ssl-libs-rpath.sh +# The Brew SSL libraries have a problem: they're trickier to relocate as +# they're not compiled with rpath enabled. +# Ref: https://github.com/Homebrew/homebrew-core/issues/3219#issuecomment-235763791 +# +# To make them work in a relocatable package, need to edit the paths to these libs in all +# the binaries to use rpaths. + +set -euo pipefail + +SSL_PATH="$(brew --prefix openssl@3)" +SSL_LIBS="ssl crypto" +BINARIES="bin/multipass bin/multipassd bin/sshfs_server lib/libssh.dylib lib/libdart_ffi.dylib" + +if [ $# -ne 1 ]; then + echo "Argument required" + exit 1 +fi + +CMAKE_BINARY_DIR=$1 +LIB_DIR="${CMAKE_BINARY_DIR}/lib" + +# Determine all the rpaths +RPATH_CHANGES=() +for lib in ${SSL_LIBS}; do + lib_path="$(perl -MCwd=realpath -e "print realpath '${SSL_PATH}/lib/lib${lib}.dylib'")" + lib_name="$( basename ${lib_path} )" + RPATH_CHANGES+=("-change") + RPATH_CHANGES+=("${lib_path}") + RPATH_CHANGES+=("@rpath/${lib_name}") + + RPATH_CHANGES+=("-change") + RPATH_CHANGES+=("${SSL_PATH}/lib/${lib_name}") + RPATH_CHANGES+=("@rpath/${lib_name}") +done + +# Install and modify all the libraries +for lib in ${SSL_LIBS}; do + lib_path="$(perl -MCwd=realpath -e "print realpath '${SSL_PATH}/lib/lib${lib}.dylib'")" + lib_name="$( basename ${lib_path} )" + target_path="${LIB_DIR}/${lib_name}" + install -m 644 "${lib_path}" "${target_path}" + install_name_tool "${RPATH_CHANGES[@]}" "${target_path}" + chmod 444 "${target_path}" +done + +# Edit the binaries to point to these newly edited libs +for binary in ${BINARIES}; do + install_name_tool "${RPATH_CHANGES[@]}" "${CMAKE_BINARY_DIR}/${binary}" +done diff --git a/packaging/macos/merge_pkgs.py b/packaging/macos/merge_pkgs.py new file mode 100755 index 0000000000..a3e7f926b1 --- /dev/null +++ b/packaging/macos/merge_pkgs.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 + +import itertools +from pathlib import Path +import pprint +import re +import shutil +import subprocess +import sys +import tempfile + +from lxml import etree + +ARCH_RE=re.compile(r"\.(x86_64|aarch64)") + +OS_VERSION_XPATH="//allowed-os-versions/os-version" + +x86_src, arm_src, dest = (Path(arg) for arg in sys.argv[1:4]) + +with tempfile.TemporaryDirectory() as workdir: + workdir = Path(workdir) + x86_work, arm_work, dest_work = (workdir / path.name for path in (x86_src, arm_src, dest)) + + subprocess.check_call(["pkgutil", "--expand", x86_src, x86_work]) + subprocess.check_call(["pkgutil", "--expand", arm_src, arm_work]) + + def target(parent, path): + return dest_work / ARCH_RE.sub("", str(path.relative_to(parent))) + + def copy(parent, path): + target_path = target(parent, path) + target_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(path, target_path, follow_symlinks=False) + + for path in x86_work.rglob("*"): + # Copy metadata + if path.is_dir() or path.name in ("Bom", "Payload"): + continue + copy(x86_work, path) + + for payload in itertools.chain(*(work.glob("*.pkg/Payload") for work in (x86_work, arm_work))): + # Unpack payload + unpacked = payload.with_suffix(".unpacked") + unpacked.mkdir() + # need to use system tar for deprecated cpio support + subprocess.check_call(["/usr/bin/tar", "-xzf", payload, "-C", unpacked]) + + multipass_gui_component = "multipass_gui" + + for path in x86_work.glob("*.pkg/Payload.unpacked/**/*"): + if path.is_dir() or multipass_gui_component in str(path.absolute()): + continue + + target_path = target(x86_work, path) + + if path.name != "Info.plist" and ({"bin", "lib"} & set(path.parts)): + arm_path = arm_work / ARCH_RE.sub(".aarch64", str(path.relative_to(x86_work))) + if arm_path.exists(): + target_path.parent.mkdir(parents=True, exist_ok=True) + # If it's a binary, exists on arm and it is not universal, make it a universal one + binary_archs = subprocess.run(["lipo", "-archs", arm_path], capture_output=True).stdout.decode().rstrip() + if binary_archs == "arm64": + subprocess.check_call(["lipo", "-create", "-output", target_path, path, arm_path]) + else: + subprocess.check_call(["cp", arm_path, target_path]) + continue + + # Copy all other paths over + copy(x86_work, path) + + for path in arm_work.glob("*.pkg/Payload.unpacked/**/*"): + # Copy all remaining ARM-specific paths + target_path = target(arm_work, path) + + if (path.is_dir() and not path.is_symlink()) or target_path.exists(): + continue + + copy(arm_work, path) + + # Fix the Distribution file + dist_path = str(dest_work / "Distribution") + dist = etree.parse(dist_path) + x86_dist = etree.parse(str(x86_work / "Distribution")) + arm_dist = etree.parse(str(arm_work / "Distribution")) + + # Set the host architectures + dist.find("options").attrib["hostArchitectures"] = ",".join( + set(v for v in itertools.chain(*( + d.find("options").attrib["hostArchitectures"].split(",") for d in (x86_dist, arm_dist))) + ) + ) + version = ARCH_RE.sub("", dist.find("product").attrib["version"]) + dist.find("product").attrib["version"] = version + + for pkg in dist.findall("pkg-ref"): + if "version" in pkg.attrib: + pkg.attrib["version"] = version + + if pkg.text: + pkg.text = ARCH_RE.sub("", pkg.text) + + # Set the minimum OSX version + dist.xpath(OS_VERSION_XPATH)[0].attrib["min"] = ( + min(x86_dist.xpath(OS_VERSION_XPATH)[0].attrib["min"], arm_dist.xpath(OS_VERSION_XPATH)[0].attrib["min"]) + ) + + dist.write(str(dist_path), pretty_print=True, xml_declaration=True) + + # Recreate the package + pkgs = dest_work / "Packages" + pkgs.mkdir() + for component in ("multipass", "multipassd"): + pkg = dest_work / f"multipass-{version}-Darwin-{component}.pkg" + subprocess.check_call(["pkgbuild", "--root", pkg / "Payload.unpacked", + "--identifier", f"com.canonical.multipass.{component}", + "--scripts", pkg / "Scripts", + "--version", version, + "--install-location", "/", + pkgs / pkg.name]) + + # Handle multipass-gui seperately since we need to pass in a component plist + pkg = dest_work / f"multipass-{version}-Darwin-{multipass_gui_component}.pkg" + component_plist = "component.plist" + + subprocess.check_call(["pkgbuild", "--analyze", "--root", pkg / "Payload.unpacked", + component_plist]) + subprocess.check_call(["plutil", "-replace", "BundleIsRelocatable", + "-bool", "false", + component_plist]) + subprocess.check_call(["pkgbuild", "--root", pkg / "Payload.unpacked", + "--identifier", f"com.canonical.multipass.{multipass_gui_component}", + "--scripts", pkg / "Scripts", + "--component-plist", component_plist, + "--version", version, + "--install-location", "/", + pkgs / pkg.name]) + + subprocess.check_call(["productbuild", "--distribution", dist_path, + "--package-path", pkgs, + "--resources", dest_work / "Resources", + "--version", version, + dest]) diff --git a/packaging/macos/multipass-gui-component.plist b/packaging/macos/multipass-gui-component.plist new file mode 100644 index 0000000000..0f39206fd3 --- /dev/null +++ b/packaging/macos/multipass-gui-component.plist @@ -0,0 +1,65 @@ + + + + + + BundleHasStrictIdentifier + + BundleIsRelocatable + + BundleIsVersionChecked + + BundleOverwriteAction + upgrade + ChildBundles + + + BundleOverwriteAction + + RootRelativeBundlePath + Library/Application Support/com.canonical.multipass/bin/Multipass.app/Contents/Frameworks/FlutterMacOS.framework + + + BundleOverwriteAction + + RootRelativeBundlePath + Library/Application Support/com.canonical.multipass/bin/Multipass.app/Contents/Frameworks/App.framework + + + + RootRelativeBundlePath + Library/Application Support/com.canonical.multipass/bin/Multipass.app + + + diff --git a/packaging/macos/post_build.cmake b/packaging/macos/post_build.cmake new file mode 100644 index 0000000000..e2e6bdee23 --- /dev/null +++ b/packaging/macos/post_build.cmake @@ -0,0 +1,23 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +cmake_minimum_required(VERSION 3.20) + +foreach(PACKAGE IN LISTS CPACK_PACKAGE_FILES) + cmake_path(GET PACKAGE PARENT_PATH PACKAGE_DIR) + execute_process( + COMMAND "${CPACK_MODULE_PATH}/sign-and-notarize.sh" --app-signer - ${PACKAGE} + WORKING_DIRECTORY ${PACKAGE_DIR} + ) +endforeach() diff --git a/packaging/macos/postinstall-multipass-gui.sh.in b/packaging/macos/postinstall-multipass-gui.sh.in new file mode 100644 index 0000000000..cb150f686f --- /dev/null +++ b/packaging/macos/postinstall-multipass-gui.sh.in @@ -0,0 +1,11 @@ +#!/bin/bash +set -e + +# This script links the Multipass GUI bundle into /Applications + +the_app="Multipass.app" +mkdir -p "${3}/Applications/${the_app}" +bundle_path="${3}@CPACK_PACKAGING_INSTALL_PREFIX@/bin/${the_app}" +ln -fsv "${bundle_path}/Contents" "${3}Applications/${the_app}/Contents" + +echo 0 diff --git a/packaging/macos/postinstall-multipass.sh.in b/packaging/macos/postinstall-multipass.sh.in new file mode 100644 index 0000000000..bc5d40fe18 --- /dev/null +++ b/packaging/macos/postinstall-multipass.sh.in @@ -0,0 +1,37 @@ +#!/bin/bash +set -e + +### Remove old "ubuntu" binary +if [ -e "${3}@CPACK_PACKAGING_INSTALL_PREFIX@/bin/ubuntu" ]; then + rm -v "${3}@CPACK_PACKAGING_INSTALL_PREFIX@/bin/ubuntu" +fi +if [ -e "${3}usr/local/bin/ubuntu" ]; then + rm -v "${3}usr/local/bin/ubuntu" +fi + +### /usr/local/bin doesn't exist on a clean OSX install, yet it is in the default $PATH! +mkdir -p ${3}usr/local/bin + +### Set up symlink to new multipass binary +ln -fsv "${3}@CPACK_PACKAGING_INSTALL_PREFIX@/bin/multipass" "${3}usr/local/bin/multipass" + +### Set up symlink for bash competions +# If HomeBrew installed (only looking for default path) +if [ -d "${3}$(brew --prefix)/etc/bash_completion.d" ]; then + ln -fsv "${3}@CPACK_PACKAGING_INSTALL_PREFIX@/Resources/completions/bash/multipass" \ + "${3}$(brew --prefix)/etc/bash_completion.d/multipass" + echo "Installed Bash completion file for HomeBrew" +else + echo "HomeBrew is not installed" +fi + +# If MacPorts installed +if [ -d "${3}opt/local/share/bash-completion/completions/" ]; then + ln -fsv "${3}@CPACK_PACKAGING_INSTALL_PREFIX@/Resources/completions/bash/multipass" \ + "${3}opt/local/share/bash-completion/completions/multipass" + echo "Installed Bash completion for MacPorts" +else + echo "MacPorts is not installed" +fi + +echo 0 diff --git a/packaging/macos/postinstall-multipassd.sh.in b/packaging/macos/postinstall-multipassd.sh.in new file mode 100644 index 0000000000..b5a208d1e1 --- /dev/null +++ b/packaging/macos/postinstall-multipassd.sh.in @@ -0,0 +1,21 @@ +#!/bin/bash +set -e + +# Launch agent location +LAUNCH_AGENT_SRC="$3@CPACK_PACKAGING_INSTALL_PREFIX@/Resources/@MULTIPASSD_PLIST@" +LAUNCH_AGENT_DEST="$3/Library/LaunchDaemons/@MULTIPASSD_PLIST@" + +# Uninstall old launch agent +if [ -f "$LAUNCH_AGENT_DEST" ]; then + launchctl unload -w "$LAUNCH_AGENT_DEST" + rm -fv "$LAUNCH_AGENT_DEST" +fi + +# Create log dir and ensure correct permissions +mkdir -p "$3/Library/Logs/Multipass" -m 755 + +# Install launch agent +cp -v "$LAUNCH_AGENT_SRC" "$LAUNCH_AGENT_DEST" +launchctl load -w "$LAUNCH_AGENT_DEST" + +exit 0 diff --git a/packaging/macos/preinstall-multipassd.sh b/packaging/macos/preinstall-multipassd.sh new file mode 100644 index 0000000000..67c30cf94c --- /dev/null +++ b/packaging/macos/preinstall-multipassd.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -e + +# Check CPU supports Hypervisor.framework's requirements +# Ref: https://developer.apple.com/documentation/hypervisor +CPU_OK=`sysctl -n kern.hv_support` + +# TODO: Create an installer plugin to generate a user-friendly dialog if +# the CPU is missing required features for multipass + +if [ "$CPU_OK" -ne "1" ] ; then + echo "Your CPU is missing required features for the Hypervisor.framework" + exit 1 +fi + +if [ $( sw_vers -productVersion | cut -d. -f1 ) -lt 13 ]; then + echo "Multipass currently requires macOS 13 or newer" + exit 1 +fi + +# Clear the target directories to avoid any leftovers +# Hardcoding the path to avoid the potential for `rm -rf /` +rm -rf "${3}/Library/Application Support/com.canonical.multipass" "${3}/Applications/Multipass.app" +rm -f /Applications/Multipass.app +GUI_AUTOSTART_PLIST="$HOME/Library/LaunchAgents/com.canonical.multipass.gui.autostart.plist" +[ -L $GUI_AUTOSTART_PLIST ] && rm -f $GUI_AUTOSTART_PLIST + +exit 0 diff --git a/packaging/macos/sign-and-notarize.sh b/packaging/macos/sign-and-notarize.sh new file mode 100755 index 0000000000..2af985c70e --- /dev/null +++ b/packaging/macos/sign-and-notarize.sh @@ -0,0 +1,296 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Open installer package, codesign its contents, then signs and notarizes it + +### check that we have all required tools +for i in codesign pkgbuild productsign xcrun xmllint ; do + if [ ! -x "$(which ${i})" ]; then + echo "Unable to execute command $i, cannot continue" + exit 1 + fi +done + +# handle arguments +POSITIONAL=() + +function help_and_exit { + echo "Usage:" + echo " $(basename "$0") --app-signer --installer-signer --notarize-id --notarize-password PKGFILE" + echo "" + echo "This utility takes a MacOS installer package to expands it, codesign its contents, repack and sign." + echo "It can also submit the signed package to Apple's notarization facility, retrieve the result and if successful, update the package." + echo "" + echo "Argument details are as follows:" + echo " --app-signer --installer-signer " + echo "These identities are SHA1 keys identifying cert+private-key pairs provided by Apple. Use 'security find-identity -v' to see which you have available" + echo "Note there are separate identities for application signing and installer signing" + echo "" + echo "Optional notarization requires:" + echo " --notarize-id --notarize-password " + echo "These are your Apple ID and the app-specific password for 'altool' - refer to this doc for details:" + echo "https://developer.apple.com/documentation/security/notarizing_your_app_before_distribution/customizing_the_notarization_workflow " + echo "" + echo "You may also need to pass --notarize-provider , see \`xcrun altool --list-providers\` if you have more than one." + exit 1 +} + +while [[ $# -gt 0 ]]; do + key=$1 + case $key in + --app-signer) + SIGN_APP="$2" + shift 2 + ;; + --installer-signer) + SIGN_PKG="$2" + shift 2 + ;; + --notarize-id) + NOTARIZE_ID="$2" + shift 2 + ;; + --notarize-password) + NOTARIZE_PASSWORD="$2" + shift 2 + ;; + --notarize-provider) + NOTARIZE_PROVIDER="$2" + shift 2 + ;; + -h|--help) + help_and_exit + ;; + *) # unknown option + POSITIONAL+=("$1") + shift + ;; + esac +done + +set -- "${POSITIONAL[@]}" # restore positional parameters + +if [[ ${#POSITIONAL[@]} != 1 ]]; then + help_and_exit +fi +PKGFILE="$1" + + +if [ -z "${SIGN_APP+x}" ]; then + echo "Missing --app-signer argument" + help_and_exit +fi + +if [ "${SIGN_APP}" != "-" ] && [ -z "${SIGN_PKG+x}" ]; then + echo "Missing --installer-signer argument" + help_and_exit +fi + +if [ ! -f "${PKGFILE}" ]; then + echo "${PKGFILE}: file not found" + exit 1 +fi + +if [ -n "${NOTARIZE_ID+x}" ] && [ -z "${NOTARIZE_PASSWORD:-}" ]; then + echo -n "Apple Developer account password: " + read -s NOTARIZE_PASSWORD + echo +fi + +function check_already_signed +{ + PKG="$1" + spctl --assess --type install "$PKG" &> /dev/null + status1=$? + codesign --verify --deep "$PKG" &> /dev/null + status2=$? + [ $status1 -eq 0 ] && [ $status2 -eq 0 ] +} + +if check_already_signed "${PKGFILE}"; then + echo "${PKGFILE} is already signed, aborting" + exit 1 +fi + + +PKGFILENAME=$(basename "${PKGFILE}") +if [ -f "${PKGFILENAME}" ]; then + echo "Making backup copy of ${PKGFILE}" + cp -v "${PKGFILE}" "${PKGFILENAME}.orig" +fi + +function sign_installer { + PKG="$1" + mv "$PKG" "tmp.${PKG}" + productsign --sign "${SIGN_PKG}" "tmp.${PKG}" "$PKG" + rm "tmp.${PKG}" +} + +function entitlements { + FILE="$( mktemp -u ).plist" + ENTITLEMENTS=( "$@" ) + [ "${SIGN_APP}" == "-" ] && ENTITLEMENTS+=( "com.apple.security.cs.disable-library-validation" ) + [ ${#ENTITLEMENTS[@]} -eq 0 ] && return + + ARGS=() + for entitlement in "${ENTITLEMENTS[@]}"; do + ARGS+=( "-c" "Add :${entitlement} bool true" ) + done; + + /usr/libexec/PlistBuddy "${ARGS[@]}" ${FILE} > /dev/null + echo --entitlements ${FILE} +} + +function codesign_binaries { + DIR="$1" + # sign every file in the directory + find "${DIR}" -type f -print0 | xargs -0L1 \ + codesign -v --timestamp --options runtime --force --strict \ + $( entitlements ) \ + --prefix com.canonical.multipass. \ + --sign "${SIGN_APP}" + + # sign qemu with the right entitlements + find "${DIR}" -type f -name qemu-system-* -print0 | xargs -0L1 \ + codesign -v --timestamp --options runtime --force --strict \ + $( entitlements com.apple.security.hypervisor \ + com.apple.security.cs.disable-executable-page-protection ) \ + --identifier com.canonical.multipass.qemu \ + --sign "${SIGN_APP}" + + # sign every bundle in the directory + find "${DIR}" -type d -name '*.app' -print0 | xargs -0L1 \ + codesign -v --timestamp --options runtime --force --strict --deep \ + $( entitlements ) \ + --prefix com.canonical.multipass. \ + --sign "${SIGN_APP}" +} + +SCRIPTDIR=$(perl -MCwd=realpath -e "print realpath '$0/..'") + +WORKDIR=$(mktemp -d) +function clean_workdir +{ + rm -rf "${WORKDIR}" +} +trap clean_workdir EXIT + +echo "Work directory: ${WORKDIR}" +PKG_ROOT="${WORKDIR}/root" + +# Extract main package +pkgutil --expand "${PKGFILE}" "${PKG_ROOT}" + +# For each component in the package, extract their Payloads +pushd "${PKG_ROOT}" +for i in *.pkg ; do + mkdir "${WORKDIR}/${i}" + tar xzvpf "${i}/Payload" -C "${WORKDIR}/${i}" + + codesign_binaries "${WORKDIR}/${i}" + + rm "${i}/Payload" + tar -czv --format cpio -f "${i}/Payload" -C "${WORKDIR}/${i}" . +done +popd + +# Compress final result back into package and sign +pkgutil --flatten "${PKG_ROOT}" "${PKGFILENAME}" + +if [ -n "${SIGN_PKG+x}" ]; then + sign_installer "${PKGFILENAME}" + + echo "Signed install package: ${PKGFILENAME}" +fi + +#### +#### Notarization ###### +#### + +if [ -z "${NOTARIZE_ID+x}" ] || [ -z "${NOTARIZE_PASSWORD+x}" ]; then + echo "Required Notarization credentials not supplied (--notarize-id, --notarize-password), bailing" + exit 0 +fi + + +# Extract necessary metadata from pkg +TITLE=$(xmllint --xpath "string(//title)" "${PKG_ROOT}/Distribution") +VERSION=$(xmllint --xpath "string(//product/@version)" "${PKG_ROOT}/Distribution") +echo "Title: '${TITLE}'" +echo "Version: '${VERSION}'" + +# Generate a unique bundle id for this submission (replacing + with -) +BUNDLE_ID="${TITLE}.${VERSION//+/-}.$(date +%s)" + +# send notarization +echo -n "Sending ${PKGFILENAME} for notarization..." +_tmpout=$(mktemp) + +# optional notarization provider (now "team ID" in notarytool) +if [ -n "${NOTARIZE_PROVIDER}" ]; then + NOTARIZE_OPTS=( --team-id "${NOTARIZE_PROVIDER}" ) +fi + +xcrun notarytool submit \ + --wait \ + --apple-id "${NOTARIZE_ID}" \ + --password "${NOTARIZE_PASSWORD}" \ + "${NOTARIZE_OPTS[@]}" "${PKGFILENAME}" 2>&1 | tee "${_tmpout}" + +# check the request uuid +_requuid=$(cat "${_tmpout}" | grep "RequestUUID" | awk '{ print $3 }') +echo "RequestUUID: ${_requuid}" + +if [ -z "${_requuid}" ]; then + echo "There was an error:" + echo "===================================================================" + cat "${_tmpout}" + echo "===================================================================" + echo "Error getting RequestUUID, notarization unsuccessful" + exit 3 +fi + +echo "Waiting for notarization to be complete (this could take up to an hour, depending on Apple's servers).." + +function print_tasks +{ + echo "Waiting cancelled!" + echo "" + echo "To manually monitor notarization process with" + echo " xcrun altool --notarization-info '${_requuid}' --username '${NOTARIZE_ID}' --password '${NOTARIZE_PASSWORD}'" + echo "and if successful, staple the notarization to the package with" + echo " xcrun stapler staple -v '${PKGFILENAME}'" +} +trap print_tasks SIGINT + + +for c in {80..0}; do + sleep 60 + xcrun notarytool info \ + --username "${NOTARIZE_ID}" \ + --password "${NOTARIZE_PASSWORD}" \ + "${_requuid}" 2>&1 | tee ${_tmpout} + _status=$(cat "${_tmpout}" | grep "Status:" | awk '{ print $2 }') + if [ "${_status}" == "invalid" ]; then + echo "Error: Got invalid notarization!" + echo "===================================================================" + cat "${_tmpout}" + echo "===================================================================" + exit 4 + fi + + if [ "${_status}" == "success" ]; then + echo -n "Notarization successful! Stapling..." + xcrun stapler staple -v "${PKGFILENAME}" + break + fi + echo "Notarization in progress, waiting..." +done + +# Verifying notarized +if ! xcrun stapler validate "${PKGFILENAME}" | grep worked ; then + echo "Error: final package verification failed"; + exit 5 +fi + +echo "..done. ${PKGFILENAME} is notarized and ready to upload" diff --git a/packaging/macos/uninstall.sh b/packaging/macos/uninstall.sh new file mode 100755 index 0000000000..d189f2e5c4 --- /dev/null +++ b/packaging/macos/uninstall.sh @@ -0,0 +1,80 @@ +#!/bin/sh +set -eu + +if [ "$EUID" -ne 0 ]; then + echo "This script needs to run as root" + exit 1 +fi + +while true; do + read -p "Are you sure you want to remove Multipass from your system? [Y/N] " yn + case $yn in + [Yy]* ) break;; + [Nn]* ) echo "Aborted"; exit;; + * ) echo "Please answer yes or no.";; + esac +done + +DELETE_VMS=0 + +while true; do + read -p "Do you want to delete all your Multipass VMs and daemon data too? [Y/N] " yn + case $yn in + [Yy]* ) DELETE_VMS=1; break;; + [Nn]* ) DELETE_VMS=0; break;; + * ) echo "Please answer yes or no.";; + esac +done + +if [ $DELETE_VMS -eq 1 ]; then + echo "Removing VMs:" + multipass delete -vv --purge --all || echo "Failed to delete multipass VMs from underlying driver" >&2 +fi + +LAUNCH_AGENT_DEST="/Library/LaunchDaemons/com.canonical.multipassd.plist" + +echo . +echo "Removing the Multipass daemon launch agent:" +launchctl unload -w "$LAUNCH_AGENT_DEST" + +if [ $DELETE_VMS -eq 1 ]; then + echo "Removing daemon data:" + rm -rfv "/var/root/Library/Application Support/multipassd" + rm -rfv "/var/root/Library/Application Support/multipass-client-certificate" + rm -rfv "/var/root/Library/Preferences/multipassd" + rm -fv "/Library/Keychains/multipass_root_cert.pem" +fi + +echo . +echo "Removing Multipass:" +rm -fv "$LAUNCH_AGENT_DEST" + +rm -fv /usr/local/bin/multipass +rm -rfv /Applications/Multipass.app + +rm -rfv "/Library/Application Support/com.canonical.multipass" +rm -rfv "/var/root/Library/Caches/multipassd" + +# GUI Autostart +rm -fv "$HOME/Library/LaunchAgents/com.canonical.multipass.gui.autostart.plist" + +# Bash completions +rm -rfv "/usr/local/etc/bash_completion.d/multipass" +rm -rf "/opt/local/share/bash-completion/completions/multipass" + +# Log files +rm -rfv "/Library/Logs/Multipass" + +echo . +echo "Removing package installation receipts" +rm -fv "/private/var/db/receipts/com.canonical.multipass.multipassd.bom" +rm -fv "/private/var/db/receipts/com.canonical.multipass.multipassd.plist" +rm -fv "/private/var/db/receipts/com.canonical.multipass.multipass.bom" +rm -fv "/private/var/db/receipts/com.canonical.multipass.multipass.plist" + +echo . +echo "Uninstall complete" + +if [ $DELETE_VMS -eq 0 ]; then + echo "Your Multipass VMs were preserved in /var/root/Library/Application Support/multipassd" +fi diff --git a/packaging/windows/CPackExternal.cmake b/packaging/windows/CPackExternal.cmake new file mode 100644 index 0000000000..1ffc958f52 --- /dev/null +++ b/packaging/windows/CPackExternal.cmake @@ -0,0 +1,55 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU General Public License version 3 as published by the Free +# Software Foundation. +# +# 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 . + +set(PRIMING_DIR + "${CPACK_TEMPORARY_DIRECTORY}/priming") + +file( + GLOB subdirectories + LIST_DIRECTORIES true + "${CPACK_TEMPORARY_DIRECTORY}/*") + +foreach(subdirectory ${subdirectories}) + file(COPY "${subdirectory}/" DESTINATION "${PRIMING_DIR}") +endforeach() + +if (CPACK_BUILD_TYPE STREQUAL "Release" OR CPACK_BUILD_TYPE STREQUAL "RelWithDebInfo") + set(CPACK_BUILD_TYPE "Release") +else() + set(CPACK_BUILD_TYPE "Debug") +endif() + +string(REGEX REPLACE "-[^.]+|\\+.+|\\.(pr|ci).+" "" BUILD_VERSION ${CPACK_PACKAGE_VERSION}) + +execute_process( + COMMAND + msbuild /Restore /verbosity:normal /p:RestorePackagesConfig=true + /p:Configuration=${CPACK_BUILD_TYPE} + /p:PublishDir=${PRIMING_DIR} + /p:OutputPath=${CPACK_OUTPUT_FILE_PREFIX}/packages + /p:BuildVersion=${BUILD_VERSION} + /p:OutputName=${CPACK_PACKAGE_FILE_NAME} + WORKING_DIRECTORY "${CPACK_SOURCE_DIR}/packaging/windows/wix" + OUTPUT_VARIABLE build_output + RESULT_VARIABLE result) + +file(REMOVE_RECURSE "${PRIMING_DIR}") + +file(WRITE ${CPACK_TEMPORARY_DIRECTORY}\\..\\WiXOutput.log "${build_output}") + +if(result) + message(FATAL_ERROR "CPack failed to build WiX package: ${build_output}") +else() + message(STATUS ${build_output}) +endif() diff --git a/packaging/windows/LICENCE.rtf b/packaging/windows/LICENCE.rtf new file mode 100644 index 0000000000..3a8884bcb9 --- /dev/null +++ b/packaging/windows/LICENCE.rtf @@ -0,0 +1,2060 @@ +{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Segoe UI;}{\f1 Courier;}}\fs20 +{\colortbl;\red255\green0\blue0;\red0\green0\blue255;} +\widowctrl\hyphauto + +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 Multipass\par} +{\pard \ql \f0 \sa180 \li0 \fi0 Copyright \u169 ? Canonical Ltd.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 GPL-3.0 license\par} +{\pard \ql \f0 \sa180 \li0 \fi0 https://github.com/canonical/multipass/\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 Open source projects used directly:\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab fmt: https://github.com/fmtlib/fmt\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab grpc: https://github.com/grpc/grpc\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab abseil-cpp: https://github.com/abseil/abseil-cpp\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab c-ares: https://github.com/c-ares/c-ares\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab gflags: https://github.com/gflags/gflags\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab protobuf: https://github.com/google/protobuf\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab zlib: https://github.com/madler/zlib\sa180\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab libssh: https://git.libssh.org/projects/libssh.git/\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab poco: https://github.com/pocoproject/poco\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab qt: https://www.qt.io/\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab semver: https://github.com/zmarko/semver\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab xz-embedded: https://git.tukaani.org/?p=xz-embedded.git\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab yaml-cpp: https://github.com/jbeder/yaml-cpp\sa180\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 Additional binaries used:\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab qemu (qemu-img): https://chocolatey.org/packages/qemu-img\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab OpenSSL (libssl-1_1-x64.dll & libcrypto-1_1-x64.dll): https://chocolatey.org/packages/openssl\sa180\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 Licensing:\par} +{\pard \ql \f0 \sa180 \li0 \fi0 Below is a summary of the licensing used in the respective projects. See their source repositories, linked above, for details.\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab fmt: BSD 2-Clause \u8220"Simplified\u8221" License; Copyright (c) 2012 - 2016, Victor Zverovich\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab grpc: Apache License 2.0\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab abseil-cpp: Apache License 2.0\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab c-ares: MIT License; Copyright (c) 2007 - 2018, Daniel Stenberg with many contributors, see AUTHORS file.\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab gflags: BSD 3-Clause \u8220"New\u8221" or \u8220"Revised\u8221" License; Copyright (c) 2006, Google Inc.\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab protobuf: BSD 3-Clause \u8220"New\u8221" or \u8220"Revised\u8221" License; Copyright 2008 Google Inc.\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab zlib: zlib License; (C) 1995-2017 Jean-loup Gailly and Mark Adler\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab libssh:\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab OpenSSL Exception\sa180\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab poco: Boost Software License - Version 1.0 - August 17th, 2003\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab qt: GNU LGPL Version 3; Copyright (c) 2016 The Qt Company\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab semver: MIT License; Copyright (c) 2015 Marko \u381 ?ivanovi\u263 ?\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab xz-embedded: zx-embedded License;\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab yaml-cpp: MIT License; Copyright (c) 2008-2015 Jesse Beder.\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab gettext (libintl): GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab glib: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab gmp: GNU LGPL Version 3 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab gnutls: GNU LGPL Version 2.1 and 3 Licenses; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab libffi: libffi License; Copyright (c) 1996-2014 Anthony Green, Red Hat, Inc and others.\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab libtasn1: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab libunistring: GNU LGPL Version 3 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab nettle: GNU LGPL Version 3 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab p11-kit: p11-kit License;\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab pcre: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab qemu (qemu-img): GNU GPL Version 2 License; See AUTHORS file for Copyright information\par} +{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab OpenSSL (libssl-1_1-x64.dll & libcrypto-1_1-x64.dll):\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab OpenSSL; Copyright (c) 1998-2020 The OpenSSL Project.\par} +{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab SSLeay; Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)\sa180\sa180\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 Licenses:\par} +{\pard \ql \f0 \sa180 \li0 \fi0 Below are the contents of all the licenses used across all the projects distributed along with Multipass.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 Apache License 2.0\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Apache License\line + Version 2.0, January 2004\line + http://www.apache.org/licenses/\line +\line + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\line +\line + 1. Definitions.\line +\line + "License" shall mean the terms and conditions for use, reproduction,\line + and distribution as defined by Sections 1 through 9 of this document.\line +\line + "Licensor" shall mean the copyright owner or entity authorized by\line + the copyright owner that is granting the License.\line +\line + "Legal Entity" shall mean the union of the acting entity and all\line + other entities that control, are controlled by, or are under common\line + control with that entity. For the purposes of this definition,\line + "control" means (i) the power, direct or indirect, to cause the\line + direction or management of such entity, whether by contract or\line + otherwise, or (ii) ownership of fifty percent (50%) or more of the\line + outstanding shares, or (iii) beneficial ownership of such entity.\line +\line + "You" (or "Your") shall mean an individual or Legal Entity\line + exercising permissions granted by this License.\line +\line + "Source" form shall mean the preferred form for making modifications,\line + including but not limited to software source code, documentation\line + source, and configuration files.\line +\line + "Object" form shall mean any form resulting from mechanical\line + transformation or translation of a Source form, including but\line + not limited to compiled object code, generated documentation,\line + and conversions to other media types.\line +\line + "Work" shall mean the work of authorship, whether in Source or\line + Object form, made available under the License, as indicated by a\line + copyright notice that is included in or attached to the work\line + (an example is provided in the Appendix below).\line +\line + "Derivative Works" shall mean any work, whether in Source or Object\line + form, that is based on (or derived from) the Work and for which the\line + editorial revisions, annotations, elaborations, or other modifications\line + represent, as a whole, an original work of authorship. For the purposes\line + of this License, Derivative Works shall not include works that remain\line + separable from, or merely link (or bind by name) to the interfaces of,\line + the Work and Derivative Works thereof.\line +\line + "Contribution" shall mean any work of authorship, including\line + the original version of the Work and any modifications or additions\line + to that Work or Derivative Works thereof, that is intentionally\line + submitted to Licensor for inclusion in the Work by the copyright owner\line + or by an individual or Legal Entity authorized to submit on behalf of\line + the copyright owner. For the purposes of this definition, "submitted"\line + means any form of electronic, verbal, or written communication sent\line + to the Licensor or its representatives, including but not limited to\line + communication on electronic mailing lists, source code control systems,\line + and issue tracking systems that are managed by, or on behalf of, the\line + Licensor for the purpose of discussing and improving the Work, but\line + excluding communication that is conspicuously marked or otherwise\line + designated in writing by the copyright owner as "Not a Contribution."\line +\line + "Contributor" shall mean Licensor and any individual or Legal Entity\line + on behalf of whom a Contribution has been received by Licensor and\line + subsequently incorporated within the Work.\line +\line + 2. Grant of Copyright License. Subject to the terms and conditions of\line + this License, each Contributor hereby grants to You a perpetual,\line + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\line + copyright license to reproduce, prepare Derivative Works of,\line + publicly display, publicly perform, sublicense, and distribute the\line + Work and such Derivative Works in Source or Object form.\line +\line + 3. Grant of Patent License. Subject to the terms and conditions of\line + this License, each Contributor hereby grants to You a perpetual,\line + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\line + (except as stated in this section) patent license to make, have made,\line + use, offer to sell, sell, import, and otherwise transfer the Work,\line + where such license applies only to those patent claims licensable\line + by such Contributor that are necessarily infringed by their\line + Contribution(s) alone or by combination of their Contribution(s)\line + with the Work to which such Contribution(s) was submitted. If You\line + institute patent litigation against any entity (including a\line + cross-claim or counterclaim in a lawsuit) alleging that the Work\line + or a Contribution incorporated within the Work constitutes direct\line + or contributory patent infringement, then any patent licenses\line + granted to You under this License for that Work shall terminate\line + as of the date such litigation is filed.\line +\line + 4. Redistribution. You may reproduce and distribute copies of the\line + Work or Derivative Works thereof in any medium, with or without\line + modifications, and in Source or Object form, provided that You\line + meet the following conditions:\line +\line + (a) You must give any other recipients of the Work or\line + Derivative Works a copy of this License; and\line +\line + (b) You must cause any modified files to carry prominent notices\line + stating that You changed the files; and\line +\line + (c) You must retain, in the Source form of any Derivative Works\line + that You distribute, all copyright, patent, trademark, and\line + attribution notices from the Source form of the Work,\line + excluding those notices that do not pertain to any part of\line + the Derivative Works; and\line +\line + (d) If the Work includes a "NOTICE" text file as part of its\line + distribution, then any Derivative Works that You distribute must\line + include a readable copy of the attribution notices contained\line + within such NOTICE file, excluding those notices that do not\line + pertain to any part of the Derivative Works, in at least one\line + of the following places: within a NOTICE text file distributed\line + as part of the Derivative Works; within the Source form or\line + documentation, if provided along with the Derivative Works; or,\line + within a display generated by the Derivative Works, if and\line + wherever such third-party notices normally appear. The contents\line + of the NOTICE file are for informational purposes only and\line + do not modify the License. You may add Your own attribution\line + notices within Derivative Works that You distribute, alongside\line + or as an addendum to the NOTICE text from the Work, provided\line + that such additional attribution notices cannot be construed\line + as modifying the License.\line +\line + You may add Your own copyright statement to Your modifications and\line + may provide additional or different license terms and conditions\line + for use, reproduction, or distribution of Your modifications, or\line + for any such Derivative Works as a whole, provided Your use,\line + reproduction, and distribution of the Work otherwise complies with\line + the conditions stated in this License.\line +\line + 5. Submission of Contributions. Unless You explicitly state otherwise,\line + any Contribution intentionally submitted for inclusion in the Work\line + by You to the Licensor shall be under the terms and conditions of\line + this License, without any additional terms or conditions.\line + Notwithstanding the above, nothing herein shall supersede or modify\line + the terms of any separate license agreement you may have executed\line + with Licensor regarding such Contributions.\line +\line + 6. Trademarks. This License does not grant permission to use the trade\line + names, trademarks, service marks, or product names of the Licensor,\line + except as required for reasonable and customary use in describing the\line + origin of the Work and reproducing the content of the NOTICE file.\line +\line + 7. Disclaimer of Warranty. Unless required by applicable law or\line + agreed to in writing, Licensor provides the Work (and each\line + Contributor provides its Contributions) on an "AS IS" BASIS,\line + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\line + implied, including, without limitation, any warranties or conditions\line + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\line + PARTICULAR PURPOSE. You are solely responsible for determining the\line + appropriateness of using or redistributing the Work and assume any\line + risks associated with Your exercise of permissions under this License.\line +\line + 8. Limitation of Liability. In no event and under no legal theory,\line + whether in tort (including negligence), contract, or otherwise,\line + unless required by applicable law (such as deliberate and grossly\line + negligent acts) or agreed to in writing, shall any Contributor be\line + liable to You for damages, including any direct, indirect, special,\line + incidental, or consequential damages of any character arising as a\line + result of this License or out of the use or inability to use the\line + Work (including but not limited to damages for loss of goodwill,\line + work stoppage, computer failure or malfunction, or any and all\line + other commercial damages or losses), even if such Contributor\line + has been advised of the possibility of such damages.\line +\line + 9. Accepting Warranty or Additional Liability. While redistributing\line + the Work or Derivative Works thereof, You may choose to offer,\line + and charge a fee for, acceptance of support, warranty, indemnity,\line + or other liability obligations and/or rights consistent with this\line + License. However, in accepting such obligations, You may act only\line + on Your own behalf and on Your sole responsibility, not on behalf\line + of any other Contributor, and only if You agree to indemnify,\line + defend, and hold each Contributor harmless for any liability\line + incurred by, or claims asserted against, such Contributor by reason\line + of your accepting any such warranty or additional liability.\line +\line + END OF TERMS AND CONDITIONS\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 Boost Software License - Version 1.0 - August 17th, 2003\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Permission is hereby granted, free of charge, to any person or organization\line +obtaining a copy of the software and accompanying documentation covered by\line +this license (the "Software") to use, reproduce, display, distribute,\line +execute, and transmit the Software, and to prepare derivative works of the\line +Software, and to permit third-parties to whom the Software is furnished to\line +do so, all subject to the following:\line +\line +The copyright notices in the Software and this entire statement, including\line +the above license grant, this restriction and the following disclaimer,\line +must be included in all copies of the Software, in whole or in part, and\line +all derivative works of the Software, unless such copies or derivative\line +works are solely in the form of machine-executable object code generated by\line +a source language processor.\line +\line +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\line +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\line +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\line +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\line +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\line +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\line +DEALINGS IN THE SOFTWARE.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 BSD 2-Clause \u8220"Simplified\u8221" License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 All rights reserved.\line +\line +Redistribution and use in source and binary forms, with or without modification,\line +are permitted provided that the following conditions are met:\line +\line +Redistributions of source code must retain the above copyright notice, this list\line +of conditions and the following disclaimer.\line +\line +Redistributions in binary form must reproduce the above copyright notice, this list\line +of conditions and the following disclaimer in the documentation and/or other\line +materials provided with the distribution.\line +\line +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY\line +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\line +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\line +SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\line +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT\line +OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\line +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\line +TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\line +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 BSD 3-Clause \u8220"New\u8221" or \u8220"Revised\u8221" License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 All rights reserved.\line +\line +Redistribution and use in source and binary forms, with or without\line +modification, are permitted provided that the following conditions are\line +met:\line +\line +* Redistributions of source code must retain the above copyright\line + notice, this list of conditions and the following disclaimer.\line +* Redistributions in binary form must reproduce the above\line + copyright notice, this list of conditions and the following disclaimer\line + in the documentation and/or other materials provided with the\line + distribution.\line +* Neither the name of Google Inc. nor the names of its\line + contributors may be used to endorse or promote products derived from\line + this software without specific prior written permission.\line +\line +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\line +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\line +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\line +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\line +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\line +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\line +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\line +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\line +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\line +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\line +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 GNU GPL Version 3 License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 GNU GENERAL PUBLIC LICENSE\line + Version 3, 29 June 2007\line +\line + Copyright (C) 2007 Free Software Foundation, Inc. \line + Everyone is permitted to copy and distribute verbatim copies\line + of this license document, but changing it is not allowed.\line +\line + Preamble\line +\line + The GNU General Public License is a free, copyleft license for\line +software and other kinds of works.\line +\line + The licenses for most software and other practical works are designed\line +to take away your freedom to share and change the works. By contrast,\line +the GNU General Public License is intended to guarantee your freedom to\line +share and change all versions of a program--to make sure it remains free\line +software for all its users. We, the Free Software Foundation, use the\line +GNU General Public License for most of our software; it applies also to\line +any other work released this way by its authors. You can apply it to\line +your programs, too.\line +\line + When we speak of free software, we are referring to freedom, not\line +price. Our General Public Licenses are designed to make sure that you\line +have the freedom to distribute copies of free software (and charge for\line +them if you wish), that you receive source code or can get it if you\line +want it, that you can change the software or use pieces of it in new\line +free programs, and that you know you can do these things.\line +\line + To protect your rights, we need to prevent others from denying you\line +these rights or asking you to surrender the rights. Therefore, you have\line +certain responsibilities if you distribute copies of the software, or if\line +you modify it: responsibilities to respect the freedom of others.\line +\line + For example, if you distribute copies of such a program, whether\line +gratis or for a fee, you must pass on to the recipients the same\line +freedoms that you received. You must make sure that they, too, receive\line +or can get the source code. And you must show them these terms so they\line +know their rights.\line +\line + Developers that use the GNU GPL protect your rights with two steps:\line +(1) assert copyright on the software, and (2) offer you this License\line +giving you legal permission to copy, distribute and/or modify it.\line +\line + For the developers' and authors' protection, the GPL clearly explains\line +that there is no warranty for this free software. For both users' and\line +authors' sake, the GPL requires that modified versions be marked as\line +changed, so that their problems will not be attributed erroneously to\line +authors of previous versions.\line +\line + Some devices are designed to deny users access to install or run\line +modified versions of the software inside them, although the manufacturer\line +can do so. This is fundamentally incompatible with the aim of\line +protecting users' freedom to change the software. The systematic\line +pattern of such abuse occurs in the area of products for individuals to\line +use, which is precisely where it is most unacceptable. Therefore, we\line +have designed this version of the GPL to prohibit the practice for those\line +products. If such problems arise substantially in other domains, we\line +stand ready to extend this provision to those domains in future versions\line +of the GPL, as needed to protect the freedom of users.\line +\line + Finally, every program is threatened constantly by software patents.\line +States should not allow patents to restrict development and use of\line +software on general-purpose computers, but in those that do, we wish to\line +avoid the special danger that patents applied to a free program could\line +make it effectively proprietary. To prevent this, the GPL assures that\line +patents cannot be used to render the program non-free.\line +\line + The precise terms and conditions for copying, distribution and\line +modification follow.\line +\line + TERMS AND CONDITIONS\line +\line + 0. Definitions.\line +\line + "This License" refers to version 3 of the GNU General Public License.\line +\line + "Copyright" also means copyright-like laws that apply to other kinds of\line +works, such as semiconductor masks.\line +\line + "The Program" refers to any copyrightable work licensed under this\line +License. Each licensee is addressed as "you". "Licensees" and\line +"recipients" may be individuals or organizations.\line +\line + To "modify" a work means to copy from or adapt all or part of the work\line +in a fashion requiring copyright permission, other than the making of an\line +exact copy. The resulting work is called a "modified version" of the\line +earlier work or a work "based on" the earlier work.\line +\line + A "covered work" means either the unmodified Program or a work based\line +on the Program.\line +\line + To "propagate" a work means to do anything with it that, without\line +permission, would make you directly or secondarily liable for\line +infringement under applicable copyright law, except executing it on a\line +computer or modifying a private copy. Propagation includes copying,\line +distribution (with or without modification), making available to the\line +public, and in some countries other activities as well.\line +\line + To "convey" a work means any kind of propagation that enables other\line +parties to make or receive copies. Mere interaction with a user through\line +a computer network, with no transfer of a copy, is not conveying.\line +\line + An interactive user interface displays "Appropriate Legal Notices"\line +to the extent that it includes a convenient and prominently visible\line +feature that (1) displays an appropriate copyright notice, and (2)\line +tells the user that there is no warranty for the work (except to the\line +extent that warranties are provided), that licensees may convey the\line +work under this License, and how to view a copy of this License. If\line +the interface presents a list of user commands or options, such as a\line +menu, a prominent item in the list meets this criterion.\line +\line + 1. Source Code.\line +\line + The "source code" for a work means the preferred form of the work\line +for making modifications to it. "Object code" means any non-source\line +form of a work.\line +\line + A "Standard Interface" means an interface that either is an official\line +standard defined by a recognized standards body, or, in the case of\line +interfaces specified for a particular programming language, one that\line +is widely used among developers working in that language.\line +\line + The "System Libraries" of an executable work include anything, other\line +than the work as a whole, that (a) is included in the normal form of\line +packaging a Major Component, but which is not part of that Major\line +Component, and (b) serves only to enable use of the work with that\line +Major Component, or to implement a Standard Interface for which an\line +implementation is available to the public in source code form. A\line +"Major Component", in this context, means a major essential component\line +(kernel, window system, and so on) of the specific operating system\line +(if any) on which the executable work runs, or a compiler used to\line +produce the work, or an object code interpreter used to run it.\line +\line + The "Corresponding Source" for a work in object code form means all\line +the source code needed to generate, install, and (for an executable\line +work) run the object code and to modify the work, including scripts to\line +control those activities. However, it does not include the work's\line +System Libraries, or general-purpose tools or generally available free\line +programs which are used unmodified in performing those activities but\line +which are not part of the work. For example, Corresponding Source\line +includes interface definition files associated with source files for\line +the work, and the source code for shared libraries and dynamically\line +linked subprograms that the work is specifically designed to require,\line +such as by intimate data communication or control flow between those\line +subprograms and other parts of the work.\line +\line + The Corresponding Source need not include anything that users\line +can regenerate automatically from other parts of the Corresponding\line +Source.\line +\line + The Corresponding Source for a work in source code form is that\line +same work.\line +\line + 2. Basic Permissions.\line +\line + All rights granted under this License are granted for the term of\line +copyright on the Program, and are irrevocable provided the stated\line +conditions are met. This License explicitly affirms your unlimited\line +permission to run the unmodified Program. The output from running a\line +covered work is covered by this License only if the output, given its\line +content, constitutes a covered work. This License acknowledges your\line +rights of fair use or other equivalent, as provided by copyright law.\line +\line + You may make, run and propagate covered works that you do not\line +convey, without conditions so long as your license otherwise remains\line +in force. You may convey covered works to others for the sole purpose\line +of having them make modifications exclusively for you, or provide you\line +with facilities for running those works, provided that you comply with\line +the terms of this License in conveying all material for which you do\line +not control copyright. Those thus making or running the covered works\line +for you must do so exclusively on your behalf, under your direction\line +and control, on terms that prohibit them from making any copies of\line +your copyrighted material outside their relationship with you.\line +\line + Conveying under any other circumstances is permitted solely under\line +the conditions stated below. Sublicensing is not allowed; section 10\line +makes it unnecessary.\line +\line + 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\line +\line + No covered work shall be deemed part of an effective technological\line +measure under any applicable law fulfilling obligations under article\line +11 of the WIPO copyright treaty adopted on 20 December 1996, or\line +similar laws prohibiting or restricting circumvention of such\line +measures.\line +\line + When you convey a covered work, you waive any legal power to forbid\line +circumvention of technological measures to the extent such circumvention\line +is effected by exercising rights under this License with respect to\line +the covered work, and you disclaim any intention to limit operation or\line +modification of the work as a means of enforcing, against the work's\line +users, your or third parties' legal rights to forbid circumvention of\line +technological measures.\line +\line + 4. Conveying Verbatim Copies.\line +\line + You may convey verbatim copies of the Program's source code as you\line +receive it, in any medium, provided that you conspicuously and\line +appropriately publish on each copy an appropriate copyright notice;\line +keep intact all notices stating that this License and any\line +non-permissive terms added in accord with section 7 apply to the code;\line +keep intact all notices of the absence of any warranty; and give all\line +recipients a copy of this License along with the Program.\line +\line + You may charge any price or no price for each copy that you convey,\line +and you may offer support or warranty protection for a fee.\line +\line + 5. Conveying Modified Source Versions.\line +\line + You may convey a work based on the Program, or the modifications to\line +produce it from the Program, in the form of source code under the\line +terms of section 4, provided that you also meet all of these conditions:\line +\line + a) The work must carry prominent notices stating that you modified\line + it, and giving a relevant date.\line +\line + b) The work must carry prominent notices stating that it is\line + released under this License and any conditions added under section\line + 7. This requirement modifies the requirement in section 4 to\line + "keep intact all notices".\line +\line + c) You must license the entire work, as a whole, under this\line + License to anyone who comes into possession of a copy. This\line + License will therefore apply, along with any applicable section 7\line + additional terms, to the whole of the work, and all its parts,\line + regardless of how they are packaged. This License gives no\line + permission to license the work in any other way, but it does not\line + invalidate such permission if you have separately received it.\line +\line + d) If the work has interactive user interfaces, each must display\line + Appropriate Legal Notices; however, if the Program has interactive\line + interfaces that do not display Appropriate Legal Notices, your\line + work need not make them do so.\line +\line + A compilation of a covered work with other separate and independent\line +works, which are not by their nature extensions of the covered work,\line +and which are not combined with it such as to form a larger program,\line +in or on a volume of a storage or distribution medium, is called an\line +"aggregate" if the compilation and its resulting copyright are not\line +used to limit the access or legal rights of the compilation's users\line +beyond what the individual works permit. Inclusion of a covered work\line +in an aggregate does not cause this License to apply to the other\line +parts of the aggregate.\line +\line + 6. Conveying Non-Source Forms.\line +\line + You may convey a covered work in object code form under the terms\line +of sections 4 and 5, provided that you also convey the\line +machine-readable Corresponding Source under the terms of this License,\line +in one of these ways:\line +\line + a) Convey the object code in, or embodied in, a physical product\line + (including a physical distribution medium), accompanied by the\line + Corresponding Source fixed on a durable physical medium\line + customarily used for software interchange.\line +\line + b) Convey the object code in, or embodied in, a physical product\line + (including a physical distribution medium), accompanied by a\line + written offer, valid for at least three years and valid for as\line + long as you offer spare parts or customer support for that product\line + model, to give anyone who possesses the object code either (1) a\line + copy of the Corresponding Source for all the software in the\line + product that is covered by this License, on a durable physical\line + medium customarily used for software interchange, for a price no\line + more than your reasonable cost of physically performing this\line + conveying of source, or (2) access to copy the\line + Corresponding Source from a network server at no charge.\line +\line + c) Convey individual copies of the object code with a copy of the\line + written offer to provide the Corresponding Source. This\line + alternative is allowed only occasionally and noncommercially, and\line + only if you received the object code with such an offer, in accord\line + with subsection 6b.\line +\line + d) Convey the object code by offering access from a designated\line + place (gratis or for a charge), and offer equivalent access to the\line + Corresponding Source in the same way through the same place at no\line + further charge. You need not require recipients to copy the\line + Corresponding Source along with the object code. If the place to\line + copy the object code is a network server, the Corresponding Source\line + may be on a different server (operated by you or a third party)\line + that supports equivalent copying facilities, provided you maintain\line + clear directions next to the object code saying where to find the\line + Corresponding Source. Regardless of what server hosts the\line + Corresponding Source, you remain obligated to ensure that it is\line + available for as long as needed to satisfy these requirements.\line +\line + e) Convey the object code using peer-to-peer transmission, provided\line + you inform other peers where the object code and Corresponding\line + Source of the work are being offered to the general public at no\line + charge under subsection 6d.\line +\line + A separable portion of the object code, whose source code is excluded\line +from the Corresponding Source as a System Library, need not be\line +included in conveying the object code work.\line +\line + A "User Product" is either (1) a "consumer product", which means any\line +tangible personal property which is normally used for personal, family,\line +or household purposes, or (2) anything designed or sold for incorporation\line +into a dwelling. In determining whether a product is a consumer product,\line +doubtful cases shall be resolved in favor of coverage. For a particular\line +product received by a particular user, "normally used" refers to a\line +typical or common use of that class of product, regardless of the status\line +of the particular user or of the way in which the particular user\line +actually uses, or expects or is expected to use, the product. A product\line +is a consumer product regardless of whether the product has substantial\line +commercial, industrial or non-consumer uses, unless such uses represent\line +the only significant mode of use of the product.\line +\line + "Installation Information" for a User Product means any methods,\line +procedures, authorization keys, or other information required to install\line +and execute modified versions of a covered work in that User Product from\line +a modified version of its Corresponding Source. The information must\line +suffice to ensure that the continued functioning of the modified object\line +code is in no case prevented or interfered with solely because\line +modification has been made.\line +\line + If you convey an object code work under this section in, or with, or\line +specifically for use in, a User Product, and the conveying occurs as\line +part of a transaction in which the right of possession and use of the\line +User Product is transferred to the recipient in perpetuity or for a\line +fixed term (regardless of how the transaction is characterized), the\line +Corresponding Source conveyed under this section must be accompanied\line +by the Installation Information. But this requirement does not apply\line +if neither you nor any third party retains the ability to install\line +modified object code on the User Product (for example, the work has\line +been installed in ROM).\line +\line + The requirement to provide Installation Information does not include a\line +requirement to continue to provide support service, warranty, or updates\line +for a work that has been modified or installed by the recipient, or for\line +the User Product in which it has been modified or installed. Access to a\line +network may be denied when the modification itself materially and\line +adversely affects the operation of the network or violates the rules and\line +protocols for communication across the network.\line +\line + Corresponding Source conveyed, and Installation Information provided,\line +in accord with this section must be in a format that is publicly\line +documented (and with an implementation available to the public in\line +source code form), and must require no special password or key for\line +unpacking, reading or copying.\line +\line + 7. Additional Terms.\line +\line + "Additional permissions" are terms that supplement the terms of this\line +License by making exceptions from one or more of its conditions.\line +Additional permissions that are applicable to the entire Program shall\line +be treated as though they were included in this License, to the extent\line +that they are valid under applicable law. If additional permissions\line +apply only to part of the Program, that part may be used separately\line +under those permissions, but the entire Program remains governed by\line +this License without regard to the additional permissions.\line +\line + When you convey a copy of a covered work, you may at your option\line +remove any additional permissions from that copy, or from any part of\line +it. (Additional permissions may be written to require their own\line +removal in certain cases when you modify the work.) You may place\line +additional permissions on material, added by you to a covered work,\line +for which you have or can give appropriate copyright permission.\line +\line + Notwithstanding any other provision of this License, for material you\line +add to a covered work, you may (if authorized by the copyright holders of\line +that material) supplement the terms of this License with terms:\line +\line + a) Disclaiming warranty or limiting liability differently from the\line + terms of sections 15 and 16 of this License; or\line +\line + b) Requiring preservation of specified reasonable legal notices or\line + author attributions in that material or in the Appropriate Legal\line + Notices displayed by works containing it; or\line +\line + c) Prohibiting misrepresentation of the origin of that material, or\line + requiring that modified versions of such material be marked in\line + reasonable ways as different from the original version; or\line +\line + d) Limiting the use for publicity purposes of names of licensors or\line + authors of the material; or\line +\line + e) Declining to grant rights under trademark law for use of some\line + trade names, trademarks, or service marks; or\line +\line + f) Requiring indemnification of licensors and authors of that\line + material by anyone who conveys the material (or modified versions of\line + it) with contractual assumptions of liability to the recipient, for\line + any liability that these contractual assumptions directly impose on\line + those licensors and authors.\line +\line + All other non-permissive additional terms are considered "further\line +restrictions" within the meaning of section 10. If the Program as you\line +received it, or any part of it, contains a notice stating that it is\line +governed by this License along with a term that is a further\line +restriction, you may remove that term. If a license document contains\line +a further restriction but permits relicensing or conveying under this\line +License, you may add to a covered work material governed by the terms\line +of that license document, provided that the further restriction does\line +not survive such relicensing or conveying.\line +\line + If you add terms to a covered work in accord with this section, you\line +must place, in the relevant source files, a statement of the\line +additional terms that apply to those files, or a notice indicating\line +where to find the applicable terms.\line +\line + Additional terms, permissive or non-permissive, may be stated in the\line +form of a separately written license, or stated as exceptions;\line +the above requirements apply either way.\line +\line + 8. Termination.\line +\line + You may not propagate or modify a covered work except as expressly\line +provided under this License. Any attempt otherwise to propagate or\line +modify it is void, and will automatically terminate your rights under\line +this License (including any patent licenses granted under the third\line +paragraph of section 11).\line +\line + However, if you cease all violation of this License, then your\line +license from a particular copyright holder is reinstated (a)\line +provisionally, unless and until the copyright holder explicitly and\line +finally terminates your license, and (b) permanently, if the copyright\line +holder fails to notify you of the violation by some reasonable means\line +prior to 60 days after the cessation.\line +\line + Moreover, your license from a particular copyright holder is\line +reinstated permanently if the copyright holder notifies you of the\line +violation by some reasonable means, this is the first time you have\line +received notice of violation of this License (for any work) from that\line +copyright holder, and you cure the violation prior to 30 days after\line +your receipt of the notice.\line +\line + Termination of your rights under this section does not terminate the\line +licenses of parties who have received copies or rights from you under\line +this License. If your rights have been terminated and not permanently\line +reinstated, you do not qualify to receive new licenses for the same\line +material under section 10.\line +\line + 9. Acceptance Not Required for Having Copies.\line +\line + You are not required to accept this License in order to receive or\line +run a copy of the Program. Ancillary propagation of a covered work\line +occurring solely as a consequence of using peer-to-peer transmission\line +to receive a copy likewise does not require acceptance. However,\line +nothing other than this License grants you permission to propagate or\line +modify any covered work. These actions infringe copyright if you do\line +not accept this License. Therefore, by modifying or propagating a\line +covered work, you indicate your acceptance of this License to do so.\line +\line + 10. Automatic Licensing of Downstream Recipients.\line +\line + Each time you convey a covered work, the recipient automatically\line +receives a license from the original licensors, to run, modify and\line +propagate that work, subject to this License. You are not responsible\line +for enforcing compliance by third parties with this License.\line +\line + An "entity transaction" is a transaction transferring control of an\line +organization, or substantially all assets of one, or subdividing an\line +organization, or merging organizations. If propagation of a covered\line +work results from an entity transaction, each party to that\line +transaction who receives a copy of the work also receives whatever\line +licenses to the work the party's predecessor in interest had or could\line +give under the previous paragraph, plus a right to possession of the\line +Corresponding Source of the work from the predecessor in interest, if\line +the predecessor has it or can get it with reasonable efforts.\line +\line + You may not impose any further restrictions on the exercise of the\line +rights granted or affirmed under this License. For example, you may\line +not impose a license fee, royalty, or other charge for exercise of\line +rights granted under this License, and you may not initiate litigation\line +(including a cross-claim or counterclaim in a lawsuit) alleging that\line +any patent claim is infringed by making, using, selling, offering for\line +sale, or importing the Program or any portion of it.\line +\line + 11. Patents.\line +\line + A "contributor" is a copyright holder who authorizes use under this\line +License of the Program or a work on which the Program is based. The\line +work thus licensed is called the contributor's "contributor version".\line +\line + A contributor's "essential patent claims" are all patent claims\line +owned or controlled by the contributor, whether already acquired or\line +hereafter acquired, that would be infringed by some manner, permitted\line +by this License, of making, using, or selling its contributor version,\line +but do not include claims that would be infringed only as a\line +consequence of further modification of the contributor version. For\line +purposes of this definition, "control" includes the right to grant\line +patent sublicenses in a manner consistent with the requirements of\line +this License.\line +\line + Each contributor grants you a non-exclusive, worldwide, royalty-free\line +patent license under the contributor's essential patent claims, to\line +make, use, sell, offer for sale, import and otherwise run, modify and\line +propagate the contents of its contributor version.\line +\line + In the following three paragraphs, a "patent license" is any express\line +agreement or commitment, however denominated, not to enforce a patent\line +(such as an express permission to practice a patent or covenant not to\line +sue for patent infringement). To "grant" such a patent license to a\line +party means to make such an agreement or commitment not to enforce a\line +patent against the party.\line +\line + If you convey a covered work, knowingly relying on a patent license,\line +and the Corresponding Source of the work is not available for anyone\line +to copy, free of charge and under the terms of this License, through a\line +publicly available network server or other readily accessible means,\line +then you must either (1) cause the Corresponding Source to be so\line +available, or (2) arrange to deprive yourself of the benefit of the\line +patent license for this particular work, or (3) arrange, in a manner\line +consistent with the requirements of this License, to extend the patent\line +license to downstream recipients. "Knowingly relying" means you have\line +actual knowledge that, but for the patent license, your conveying the\line +covered work in a country, or your recipient's use of the covered work\line +in a country, would infringe one or more identifiable patents in that\line +country that you have reason to believe are valid.\line +\line + If, pursuant to or in connection with a single transaction or\line +arrangement, you convey, or propagate by procuring conveyance of, a\line +covered work, and grant a patent license to some of the parties\line +receiving the covered work authorizing them to use, propagate, modify\line +or convey a specific copy of the covered work, then the patent license\line +you grant is automatically extended to all recipients of the covered\line +work and works based on it.\line +\line + A patent license is "discriminatory" if it does not include within\line +the scope of its coverage, prohibits the exercise of, or is\line +conditioned on the non-exercise of one or more of the rights that are\line +specifically granted under this License. You may not convey a covered\line +work if you are a party to an arrangement with a third party that is\line +in the business of distributing software, under which you make payment\line +to the third party based on the extent of your activity of conveying\line +the work, and under which the third party grants, to any of the\line +parties who would receive the covered work from you, a discriminatory\line +patent license (a) in connection with copies of the covered work\line +conveyed by you (or copies made from those copies), or (b) primarily\line +for and in connection with specific products or compilations that\line +contain the covered work, unless you entered into that arrangement,\line +or that patent license was granted, prior to 28 March 2007.\line +\line + Nothing in this License shall be construed as excluding or limiting\line +any implied license or other defenses to infringement that may\line +otherwise be available to you under applicable patent law.\line +\line + 12. No Surrender of Others' Freedom.\line +\line + If conditions are imposed on you (whether by court order, agreement or\line +otherwise) that contradict the conditions of this License, they do not\line +excuse you from the conditions of this License. If you cannot convey a\line +covered work so as to satisfy simultaneously your obligations under this\line +License and any other pertinent obligations, then as a consequence you may\line +not convey it at all. For example, if you agree to terms that obligate you\line +to collect a royalty for further conveying from those to whom you convey\line +the Program, the only way you could satisfy both those terms and this\line +License would be to refrain entirely from conveying the Program.\line +\line + 13. Use with the GNU Affero General Public License.\line +\line + Notwithstanding any other provision of this License, you have\line +permission to link or combine any covered work with a work licensed\line +under version 3 of the GNU Affero General Public License into a single\line +combined work, and to convey the resulting work. The terms of this\line +License will continue to apply to the part which is the covered work,\line +but the special requirements of the GNU Affero General Public License,\line +section 13, concerning interaction through a network will apply to the\line +combination as such.\line +\line + 14. Revised Versions of this License.\line +\line + The Free Software Foundation may publish revised and/or new versions of\line +the GNU General Public License from time to time. Such new versions will\line +be similar in spirit to the present version, but may differ in detail to\line +address new problems or concerns.\line +\line + Each version is given a distinguishing version number. If the\line +Program specifies that a certain numbered version of the GNU General\line +Public License "or any later version" applies to it, you have the\line +option of following the terms and conditions either of that numbered\line +version or of any later version published by the Free Software\line +Foundation. If the Program does not specify a version number of the\line +GNU General Public License, you may choose any version ever published\line +by the Free Software Foundation.\line +\line + If the Program specifies that a proxy can decide which future\line +versions of the GNU General Public License can be used, that proxy's\line +public statement of acceptance of a version permanently authorizes you\line +to choose that version for the Program.\line +\line + Later license versions may give you additional or different\line +permissions. However, no additional obligations are imposed on any\line +author or copyright holder as a result of your choosing to follow a\line +later version.\line +\line + 15. Disclaimer of Warranty.\line +\line + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\line +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\line +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY\line +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\line +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\line +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\line +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\line +ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\line +\line + 16. Limitation of Liability.\line +\line + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\line +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\line +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\line +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\line +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\line +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\line +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\line +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\line +SUCH DAMAGES.\line +\line + 17. Interpretation of Sections 15 and 16.\line +\line + If the disclaimer of warranty and limitation of liability provided\line +above cannot be given local legal effect according to their terms,\line +reviewing courts shall apply local law that most closely approximates\line +an absolute waiver of all civil liability in connection with the\line +Program, unless a warranty or assumption of liability accompanies a\line +copy of the Program in return for a fee.\line +\line + END OF TERMS AND CONDITIONS\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 GNU GPL Version 2 License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 GNU GENERAL PUBLIC LICENSE\line + Version 2, June 1991\line +\line + Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\line + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\line + Everyone is permitted to copy and distribute verbatim copies\line + of this license document, but changing it is not allowed.\line +\line + Preamble\line +\line + The licenses for most software are designed to take away your\line +freedom to share and change it. By contrast, the GNU General Public\line +License is intended to guarantee your freedom to share and change free\line +software--to make sure the software is free for all its users. This\line +General Public License applies to most of the Free Software\line +Foundation's software and to any other program whose authors commit to\line +using it. (Some other Free Software Foundation software is covered by\line +the GNU Lesser General Public License instead.) You can apply it to\line +your programs, too.\line +\line + When we speak of free software, we are referring to freedom, not\line +price. Our General Public Licenses are designed to make sure that you\line +have the freedom to distribute copies of free software (and charge for\line +this service if you wish), that you receive source code or can get it\line +if you want it, that you can change the software or use pieces of it\line +in new free programs; and that you know you can do these things.\line +\line + To protect your rights, we need to make restrictions that forbid\line +anyone to deny you these rights or to ask you to surrender the rights.\line +These restrictions translate to certain responsibilities for you if you\line +distribute copies of the software, or if you modify it.\line +\line + For example, if you distribute copies of such a program, whether\line +gratis or for a fee, you must give the recipients all the rights that\line +you have. You must make sure that they, too, receive or can get the\line +source code. And you must show them these terms so they know their\line +rights.\line +\line + We protect your rights with two steps: (1) copyright the software, and\line +(2) offer you this license which gives you legal permission to copy,\line +distribute and/or modify the software.\line +\line + Also, for each author's protection and ours, we want to make certain\line +that everyone understands that there is no warranty for this free\line +software. If the software is modified by someone else and passed on, we\line +want its recipients to know that what they have is not the original, so\line +that any problems introduced by others will not reflect on the original\line +authors' reputations.\line +\line + Finally, any free program is threatened constantly by software\line +patents. We wish to avoid the danger that redistributors of a free\line +program will individually obtain patent licenses, in effect making the\line +program proprietary. To prevent this, we have made it clear that any\line +patent must be licensed for everyone's free use or not licensed at all.\line +\line + The precise terms and conditions for copying, distribution and\line +modification follow.\line +\line + GNU GENERAL PUBLIC LICENSE\line + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\line +\line + 0. This License applies to any program or other work which contains\line +a notice placed by the copyright holder saying it may be distributed\line +under the terms of this General Public License. The "Program", below,\line +refers to any such program or work, and a "work based on the Program"\line +means either the Program or any derivative work under copyright law:\line +that is to say, a work containing the Program or a portion of it,\line +either verbatim or with modifications and/or translated into another\line +language. (Hereinafter, translation is included without limitation in\line +the term "modification".) Each licensee is addressed as "you".\line +\line +Activities other than copying, distribution and modification are not\line +covered by this License; they are outside its scope. The act of\line +running the Program is not restricted, and the output from the Program\line +is covered only if its contents constitute a work based on the\line +Program (independent of having been made by running the Program).\line +Whether that is true depends on what the Program does.\line +\line + 1. You may copy and distribute verbatim copies of the Program's\line +source code as you receive it, in any medium, provided that you\line +conspicuously and appropriately publish on each copy an appropriate\line +copyright notice and disclaimer of warranty; keep intact all the\line +notices that refer to this License and to the absence of any warranty;\line +and give any other recipients of the Program a copy of this License\line +along with the Program.\line +\line +You may charge a fee for the physical act of transferring a copy, and\line +you may at your option offer warranty protection in exchange for a fee.\line +\line + 2. You may modify your copy or copies of the Program or any portion\line +of it, thus forming a work based on the Program, and copy and\line +distribute such modifications or work under the terms of Section 1\line +above, provided that you also meet all of these conditions:\line +\line + a) You must cause the modified files to carry prominent notices\line + stating that you changed the files and the date of any change.\line +\line + b) You must cause any work that you distribute or publish, that in\line + whole or in part contains or is derived from the Program or any\line + part thereof, to be licensed as a whole at no charge to all third\line + parties under the terms of this License.\line +\line + c) If the modified program normally reads commands interactively\line + when run, you must cause it, when started running for such\line + interactive use in the most ordinary way, to print or display an\line + announcement including an appropriate copyright notice and a\line + notice that there is no warranty (or else, saying that you provide\line + a warranty) and that users may redistribute the program under\line + these conditions, and telling the user how to view a copy of this\line + License. (Exception: if the Program itself is interactive but\line + does not normally print such an announcement, your work based on\line + the Program is not required to print an announcement.)\line +\line +These requirements apply to the modified work as a whole. If\line +identifiable sections of that work are not derived from the Program,\line +and can be reasonably considered independent and separate works in\line +themselves, then this License, and its terms, do not apply to those\line +sections when you distribute them as separate works. But when you\line +distribute the same sections as part of a whole which is a work based\line +on the Program, the distribution of the whole must be on the terms of\line +this License, whose permissions for other licensees extend to the\line +entire whole, and thus to each and every part regardless of who wrote it.\line +\line +Thus, it is not the intent of this section to claim rights or contest\line +your rights to work written entirely by you; rather, the intent is to\line +exercise the right to control the distribution of derivative or\line +collective works based on the Program.\line +\line +In addition, mere aggregation of another work not based on the Program\line +with the Program (or with a work based on the Program) on a volume of\line +a storage or distribution medium does not bring the other work under\line +the scope of this License.\line +\line + 3. You may copy and distribute the Program (or a work based on it,\line +under Section 2) in object code or executable form under the terms of\line +Sections 1 and 2 above provided that you also do one of the following:\line +\line + a) Accompany it with the complete corresponding machine-readable\line + source code, which must be distributed under the terms of Sections\line + 1 and 2 above on a medium customarily used for software interchange; or,\line +\line + b) Accompany it with a written offer, valid for at least three\line + years, to give any third party, for a charge no more than your\line + cost of physically performing source distribution, a complete\line + machine-readable copy of the corresponding source code, to be\line + distributed under the terms of Sections 1 and 2 above on a medium\line + customarily used for software interchange; or,\line +\line + c) Accompany it with the information you received as to the offer\line + to distribute corresponding source code. (This alternative is\line + allowed only for noncommercial distribution and only if you\line + received the program in object code or executable form with such\line + an offer, in accord with Subsection b above.)\line +\line +The source code for a work means the preferred form of the work for\line +making modifications to it. For an executable work, complete source\line +code means all the source code for all modules it contains, plus any\line +associated interface definition files, plus the scripts used to\line +control compilation and installation of the executable. However, as a\line +special exception, the source code distributed need not include\line +anything that is normally distributed (in either source or binary\line +form) with the major components (compiler, kernel, and so on) of the\line +operating system on which the executable runs, unless that component\line +itself accompanies the executable.\line +\line +If distribution of executable or object code is made by offering\line +access to copy from a designated place, then offering equivalent\line +access to copy the source code from the same place counts as\line +distribution of the source code, even though third parties are not\line +compelled to copy the source along with the object code.\line +\line + 4. You may not copy, modify, sublicense, or distribute the Program\line +except as expressly provided under this License. Any attempt\line +otherwise to copy, modify, sublicense or distribute the Program is\line +void, and will automatically terminate your rights under this License.\line +However, parties who have received copies, or rights, from you under\line +this License will not have their licenses terminated so long as such\line +parties remain in full compliance.\line +\line + 5. You are not required to accept this License, since you have not\line +signed it. However, nothing else grants you permission to modify or\line +distribute the Program or its derivative works. These actions are\line +prohibited by law if you do not accept this License. Therefore, by\line +modifying or distributing the Program (or any work based on the\line +Program), you indicate your acceptance of this License to do so, and\line +all its terms and conditions for copying, distributing or modifying\line +the Program or works based on it.\line +\line + 6. Each time you redistribute the Program (or any work based on the\line +Program), the recipient automatically receives a license from the\line +original licensor to copy, distribute or modify the Program subject to\line +these terms and conditions. You may not impose any further\line +restrictions on the recipients' exercise of the rights granted herein.\line +You are not responsible for enforcing compliance by third parties to\line +this License.\line +\line + 7. If, as a consequence of a court judgment or allegation of patent\line +infringement or for any other reason (not limited to patent issues),\line +conditions are imposed on you (whether by court order, agreement or\line +otherwise) that contradict the conditions of this License, they do not\line +excuse you from the conditions of this License. If you cannot\line +distribute so as to satisfy simultaneously your obligations under this\line +License and any other pertinent obligations, then as a consequence you\line +may not distribute the Program at all. For example, if a patent\line +license would not permit royalty-free redistribution of the Program by\line +all those who receive copies directly or indirectly through you, then\line +the only way you could satisfy both it and this License would be to\line +refrain entirely from distribution of the Program.\line +\line +If any portion of this section is held invalid or unenforceable under\line +any particular circumstance, the balance of the section is intended to\line +apply and the section as a whole is intended to apply in other\line +circumstances.\line +\line +It is not the purpose of this section to induce you to infringe any\line +patents or other property right claims or to contest validity of any\line +such claims; this section has the sole purpose of protecting the\line +integrity of the free software distribution system, which is\line +implemented by public license practices. Many people have made\line +generous contributions to the wide range of software distributed\line +through that system in reliance on consistent application of that\line +system; it is up to the author/donor to decide if he or she is willing\line +to distribute software through any other system and a licensee cannot\line +impose that choice.\line +\line +This section is intended to make thoroughly clear what is believed to\line +be a consequence of the rest of this License.\line +\line + 8. If the distribution and/or use of the Program is restricted in\line +certain countries either by patents or by copyrighted interfaces, the\line +original copyright holder who places the Program under this License\line +may add an explicit geographical distribution limitation excluding\line +those countries, so that distribution is permitted only in or among\line +countries not thus excluded. In such case, this License incorporates\line +the limitation as if written in the body of this License.\line +\line + 9. The Free Software Foundation may publish revised and/or new versions\line +of the General Public License from time to time. Such new versions will\line +be similar in spirit to the present version, but may differ in detail to\line +address new problems or concerns.\line +\line +Each version is given a distinguishing version number. If the Program\line +specifies a version number of this License which applies to it and "any\line +later version", you have the option of following the terms and conditions\line +either of that version or of any later version published by the Free\line +Software Foundation. If the Program does not specify a version number of\line +this License, you may choose any version ever published by the Free Software\line +Foundation.\line +\line + 10. If you wish to incorporate parts of the Program into other free\line +programs whose distribution conditions are different, write to the author\line +to ask for permission. For software which is copyrighted by the Free\line +Software Foundation, write to the Free Software Foundation; we sometimes\line +make exceptions for this. Our decision will be guided by the two goals\line +of preserving the free status of all derivatives of our free software and\line +of promoting the sharing and reuse of software generally.\line +\line + NO WARRANTY\line +\line + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\line +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN\line +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\line +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\line +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\line +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS\line +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE\line +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\line +REPAIR OR CORRECTION.\line +\line + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\line +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\line +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\line +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\line +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\line +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\line +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\line +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\line +POSSIBILITY OF SUCH DAMAGES.\line +\line + END OF TERMS AND CONDITIONS\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 GNU LGPL Version 2.1 License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 GNU LESSER GENERAL PUBLIC LICENSE\line + Version 2.1, February 1999\line +\line + Copyright (C) 1991, 1999 Free Software Foundation, Inc.\line + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\line + Everyone is permitted to copy and distribute verbatim copies\line + of this license document, but changing it is not allowed.\line +\line +[This is the first released version of the Lesser GPL. It also counts\line + as the successor of the GNU Library Public License, version 2, hence\line + the version number 2.1.]\line +\line + Preamble\line +\line + The licenses for most software are designed to take away your\line +freedom to share and change it. By contrast, the GNU General Public\line +Licenses are intended to guarantee your freedom to share and change\line +free software--to make sure the software is free for all its users.\line +\line + This license, the Lesser General Public License, applies to some\line +specially designated software packages--typically libraries--of the\line +Free Software Foundation and other authors who decide to use it. You\line +can use it too, but we suggest you first think carefully about whether\line +this license or the ordinary General Public License is the better\line +strategy to use in any particular case, based on the explanations below.\line +\line + When we speak of free software, we are referring to freedom of use,\line +not price. Our General Public Licenses are designed to make sure that\line +you have the freedom to distribute copies of free software (and charge\line +for this service if you wish); that you receive source code or can get\line +it if you want it; that you can change the software and use pieces of\line +it in new free programs; and that you are informed that you can do\line +these things.\line +\line + To protect your rights, we need to make restrictions that forbid\line +distributors to deny you these rights or to ask you to surrender these\line +rights. These restrictions translate to certain responsibilities for\line +you if you distribute copies of the library or if you modify it.\line +\line + For example, if you distribute copies of the library, whether gratis\line +or for a fee, you must give the recipients all the rights that we gave\line +you. You must make sure that they, too, receive or can get the source\line +code. If you link other code with the library, you must provide\line +complete object files to the recipients, so that they can relink them\line +with the library after making changes to the library and recompiling\line +it. And you must show them these terms so they know their rights.\line +\line + We protect your rights with a two-step method: (1) we copyright the\line +library, and (2) we offer you this license, which gives you legal\line +permission to copy, distribute and/or modify the library.\line +\line + To protect each distributor, we want to make it very clear that\line +there is no warranty for the free library. Also, if the library is\line +modified by someone else and passed on, the recipients should know\line +that what they have is not the original version, so that the original\line +author's reputation will not be affected by problems that might be\line +introduced by others.\line +\line + Finally, software patents pose a constant threat to the existence of\line +any free program. We wish to make sure that a company cannot\line +effectively restrict the users of a free program by obtaining a\line +restrictive license from a patent holder. Therefore, we insist that\line +any patent license obtained for a version of the library must be\line +consistent with the full freedom of use specified in this license.\line +\line + Most GNU software, including some libraries, is covered by the\line +ordinary GNU General Public License. This license, the GNU Lesser\line +General Public License, applies to certain designated libraries, and\line +is quite different from the ordinary General Public License. We use\line +this license for certain libraries in order to permit linking those\line +libraries into non-free programs.\line +\line + When a program is linked with a library, whether statically or using\line +a shared library, the combination of the two is legally speaking a\line +combined work, a derivative of the original library. The ordinary\line +General Public License therefore permits such linking only if the\line +entire combination fits its criteria of freedom. The Lesser General\line +Public License permits more lax criteria for linking other code with\line +the library.\line +\line + We call this license the "Lesser" General Public License because it\line +does Less to protect the user's freedom than the ordinary General\line +Public License. It also provides other free software developers Less\line +of an advantage over competing non-free programs. These disadvantages\line +are the reason we use the ordinary General Public License for many\line +libraries. However, the Lesser license provides advantages in certain\line +special circumstances.\line +\line + For example, on rare occasions, there may be a special need to\line +encourage the widest possible use of a certain library, so that it becomes\line +a de-facto standard. To achieve this, non-free programs must be\line +allowed to use the library. A more frequent case is that a free\line +library does the same job as widely used non-free libraries. In this\line +case, there is little to gain by limiting the free library to free\line +software only, so we use the Lesser General Public License.\line +\line + In other cases, permission to use a particular library in non-free\line +programs enables a greater number of people to use a large body of\line +free software. For example, permission to use the GNU C Library in\line +non-free programs enables many more people to use the whole GNU\line +operating system, as well as its variant, the GNU/Linux operating\line +system.\line +\line + Although the Lesser General Public License is Less protective of the\line +users' freedom, it does ensure that the user of a program that is\line +linked with the Library has the freedom and the wherewithal to run\line +that program using a modified version of the Library.\line +\line + The precise terms and conditions for copying, distribution and\line +modification follow. Pay close attention to the difference between a\line +"work based on the library" and a "work that uses the library". The\line +former contains code derived from the library, whereas the latter must\line +be combined with the library in order to run.\line +\line + GNU LESSER GENERAL PUBLIC LICENSE\line + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\line +\line + 0. This License Agreement applies to any software library or other\line +program which contains a notice placed by the copyright holder or\line +other authorized party saying it may be distributed under the terms of\line +this Lesser General Public License (also called "this License").\line +Each licensee is addressed as "you".\line +\line + A "library" means a collection of software functions and/or data\line +prepared so as to be conveniently linked with application programs\line +(which use some of those functions and data) to form executables.\line +\line + The "Library", below, refers to any such software library or work\line +which has been distributed under these terms. A "work based on the\line +Library" means either the Library or any derivative work under\line +copyright law: that is to say, a work containing the Library or a\line +portion of it, either verbatim or with modifications and/or translated\line +straightforwardly into another language. (Hereinafter, translation is\line +included without limitation in the term "modification".)\line +\line + "Source code" for a work means the preferred form of the work for\line +making modifications to it. For a library, complete source code means\line +all the source code for all modules it contains, plus any associated\line +interface definition files, plus the scripts used to control compilation\line +and installation of the library.\line +\line + Activities other than copying, distribution and modification are not\line +covered by this License; they are outside its scope. The act of\line +running a program using the Library is not restricted, and output from\line +such a program is covered only if its contents constitute a work based\line +on the Library (independent of the use of the Library in a tool for\line +writing it). Whether that is true depends on what the Library does\line +and what the program that uses the Library does.\line +\line + 1. You may copy and distribute verbatim copies of the Library's\line +complete source code as you receive it, in any medium, provided that\line +you conspicuously and appropriately publish on each copy an\line +appropriate copyright notice and disclaimer of warranty; keep intact\line +all the notices that refer to this License and to the absence of any\line +warranty; and distribute a copy of this License along with the\line +Library.\line +\line + You may charge a fee for the physical act of transferring a copy,\line +and you may at your option offer warranty protection in exchange for a\line +fee.\line +\line + 2. You may modify your copy or copies of the Library or any portion\line +of it, thus forming a work based on the Library, and copy and\line +distribute such modifications or work under the terms of Section 1\line +above, provided that you also meet all of these conditions:\line +\line + a) The modified work must itself be a software library.\line +\line + b) You must cause the files modified to carry prominent notices\line + stating that you changed the files and the date of any change.\line +\line + c) You must cause the whole of the work to be licensed at no\line + charge to all third parties under the terms of this License.\line +\line + d) If a facility in the modified Library refers to a function or a\line + table of data to be supplied by an application program that uses\line + the facility, other than as an argument passed when the facility\line + is invoked, then you must make a good faith effort to ensure that,\line + in the event an application does not supply such function or\line + table, the facility still operates, and performs whatever part of\line + its purpose remains meaningful.\line +\line + (For example, a function in a library to compute square roots has\line + a purpose that is entirely well-defined independent of the\line + application. Therefore, Subsection 2d requires that any\line + application-supplied function or table used by this function must\line + be optional: if the application does not supply it, the square\line + root function must still compute square roots.)\line +\line +These requirements apply to the modified work as a whole. If\line +identifiable sections of that work are not derived from the Library,\line +and can be reasonably considered independent and separate works in\line +themselves, then this License, and its terms, do not apply to those\line +sections when you distribute them as separate works. But when you\line +distribute the same sections as part of a whole which is a work based\line +on the Library, the distribution of the whole must be on the terms of\line +this License, whose permissions for other licensees extend to the\line +entire whole, and thus to each and every part regardless of who wrote\line +it.\line +\line +Thus, it is not the intent of this section to claim rights or contest\line +your rights to work written entirely by you; rather, the intent is to\line +exercise the right to control the distribution of derivative or\line +collective works based on the Library.\line +\line +In addition, mere aggregation of another work not based on the Library\line +with the Library (or with a work based on the Library) on a volume of\line +a storage or distribution medium does not bring the other work under\line +the scope of this License.\line +\line + 3. You may opt to apply the terms of the ordinary GNU General Public\line +License instead of this License to a given copy of the Library. To do\line +this, you must alter all the notices that refer to this License, so\line +that they refer to the ordinary GNU General Public License, version 2,\line +instead of to this License. (If a newer version than version 2 of the\line +ordinary GNU General Public License has appeared, then you can specify\line +that version instead if you wish.) Do not make any other change in\line +these notices.\line +\line + Once this change is made in a given copy, it is irreversible for\line +that copy, so the ordinary GNU General Public License applies to all\line +subsequent copies and derivative works made from that copy.\line +\line + This option is useful when you wish to copy part of the code of\line +the Library into a program that is not a library.\line +\line + 4. You may copy and distribute the Library (or a portion or\line +derivative of it, under Section 2) in object code or executable form\line +under the terms of Sections 1 and 2 above provided that you accompany\line +it with the complete corresponding machine-readable source code, which\line +must be distributed under the terms of Sections 1 and 2 above on a\line +medium customarily used for software interchange.\line +\line + If distribution of object code is made by offering access to copy\line +from a designated place, then offering equivalent access to copy the\line +source code from the same place satisfies the requirement to\line +distribute the source code, even though third parties are not\line +compelled to copy the source along with the object code.\line +\line + 5. A program that contains no derivative of any portion of the\line +Library, but is designed to work with the Library by being compiled or\line +linked with it, is called a "work that uses the Library". Such a\line +work, in isolation, is not a derivative work of the Library, and\line +therefore falls outside the scope of this License.\line +\line + However, linking a "work that uses the Library" with the Library\line +creates an executable that is a derivative of the Library (because it\line +contains portions of the Library), rather than a "work that uses the\line +library". The executable is therefore covered by this License.\line +Section 6 states terms for distribution of such executables.\line +\line + When a "work that uses the Library" uses material from a header file\line +that is part of the Library, the object code for the work may be a\line +derivative work of the Library even though the source code is not.\line +Whether this is true is especially significant if the work can be\line +linked without the Library, or if the work is itself a library. The\line +threshold for this to be true is not precisely defined by law.\line +\line + If such an object file uses only numerical parameters, data\line +structure layouts and accessors, and small macros and small inline\line +functions (ten lines or less in length), then the use of the object\line +file is unrestricted, regardless of whether it is legally a derivative\line +work. (Executables containing this object code plus portions of the\line +Library will still fall under Section 6.)\line +\line + Otherwise, if the work is a derivative of the Library, you may\line +distribute the object code for the work under the terms of Section 6.\line +Any executables containing that work also fall under Section 6,\line +whether or not they are linked directly with the Library itself.\line +\line + 6. As an exception to the Sections above, you may also combine or\line +link a "work that uses the Library" with the Library to produce a\line +work containing portions of the Library, and distribute that work\line +under terms of your choice, provided that the terms permit\line +modification of the work for the customer's own use and reverse\line +engineering for debugging such modifications.\line +\line + You must give prominent notice with each copy of the work that the\line +Library is used in it and that the Library and its use are covered by\line +this License. You must supply a copy of this License. If the work\line +during execution displays copyright notices, you must include the\line +copyright notice for the Library among them, as well as a reference\line +directing the user to the copy of this License. Also, you must do one\line +of these things:\line +\line + a) Accompany the work with the complete corresponding\line + machine-readable source code for the Library including whatever\line + changes were used in the work (which must be distributed under\line + Sections 1 and 2 above); and, if the work is an executable linked\line + with the Library, with the complete machine-readable "work that\line + uses the Library", as object code and/or source code, so that the\line + user can modify the Library and then relink to produce a modified\line + executable containing the modified Library. (It is understood\line + that the user who changes the contents of definitions files in the\line + Library will not necessarily be able to recompile the application\line + to use the modified definitions.)\line +\line + b) Use a suitable shared library mechanism for linking with the\line + Library. A suitable mechanism is one that (1) uses at run time a\line + copy of the library already present on the user's computer system,\line + rather than copying library functions into the executable, and (2)\line + will operate properly with a modified version of the library, if\line + the user installs one, as long as the modified version is\line + interface-compatible with the version that the work was made with.\line +\line + c) Accompany the work with a written offer, valid for at\line + least three years, to give the same user the materials\line + specified in Subsection 6a, above, for a charge no more\line + than the cost of performing this distribution.\line +\line + d) If distribution of the work is made by offering access to copy\line + from a designated place, offer equivalent access to copy the above\line + specified materials from the same place.\line +\line + e) Verify that the user has already received a copy of these\line + materials or that you have already sent this user a copy.\line +\line + For an executable, the required form of the "work that uses the\line +Library" must include any data and utility programs needed for\line +reproducing the executable from it. However, as a special exception,\line +the materials to be distributed need not include anything that is\line +normally distributed (in either source or binary form) with the major\line +components (compiler, kernel, and so on) of the operating system on\line +which the executable runs, unless that component itself accompanies\line +the executable.\line +\line + It may happen that this requirement contradicts the license\line +restrictions of other proprietary libraries that do not normally\line +accompany the operating system. Such a contradiction means you cannot\line +use both them and the Library together in an executable that you\line +distribute.\line +\line + 7. You may place library facilities that are a work based on the\line +Library side-by-side in a single library together with other library\line +facilities not covered by this License, and distribute such a combined\line +library, provided that the separate distribution of the work based on\line +the Library and of the other library facilities is otherwise\line +permitted, and provided that you do these two things:\line +\line + a) Accompany the combined library with a copy of the same work\line + based on the Library, uncombined with any other library\line + facilities. This must be distributed under the terms of the\line + Sections above.\line +\line + b) Give prominent notice with the combined library of the fact\line + that part of it is a work based on the Library, and explaining\line + where to find the accompanying uncombined form of the same work.\line +\line + 8. You may not copy, modify, sublicense, link with, or distribute\line +the Library except as expressly provided under this License. Any\line +attempt otherwise to copy, modify, sublicense, link with, or\line +distribute the Library is void, and will automatically terminate your\line +rights under this License. However, parties who have received copies,\line +or rights, from you under this License will not have their licenses\line +terminated so long as such parties remain in full compliance.\line +\line + 9. You are not required to accept this License, since you have not\line +signed it. However, nothing else grants you permission to modify or\line +distribute the Library or its derivative works. These actions are\line +prohibited by law if you do not accept this License. Therefore, by\line +modifying or distributing the Library (or any work based on the\line +Library), you indicate your acceptance of this License to do so, and\line +all its terms and conditions for copying, distributing or modifying\line +the Library or works based on it.\line +\line + 10. Each time you redistribute the Library (or any work based on the\line +Library), the recipient automatically receives a license from the\line +original licensor to copy, distribute, link with or modify the Library\line +subject to these terms and conditions. You may not impose any further\line +restrictions on the recipients' exercise of the rights granted herein.\line +You are not responsible for enforcing compliance by third parties with\line +this License.\line +\line + 11. If, as a consequence of a court judgment or allegation of patent\line +infringement or for any other reason (not limited to patent issues),\line +conditions are imposed on you (whether by court order, agreement or\line +otherwise) that contradict the conditions of this License, they do not\line +excuse you from the conditions of this License. If you cannot\line +distribute so as to satisfy simultaneously your obligations under this\line +License and any other pertinent obligations, then as a consequence you\line +may not distribute the Library at all. For example, if a patent\line +license would not permit royalty-free redistribution of the Library by\line +all those who receive copies directly or indirectly through you, then\line +the only way you could satisfy both it and this License would be to\line +refrain entirely from distribution of the Library.\line +\line +If any portion of this section is held invalid or unenforceable under any\line +particular circumstance, the balance of the section is intended to apply,\line +and the section as a whole is intended to apply in other circumstances.\line +\line +It is not the purpose of this section to induce you to infringe any\line +patents or other property right claims or to contest validity of any\line +such claims; this section has the sole purpose of protecting the\line +integrity of the free software distribution system which is\line +implemented by public license practices. Many people have made\line +generous contributions to the wide range of software distributed\line +through that system in reliance on consistent application of that\line +system; it is up to the author/donor to decide if he or she is willing\line +to distribute software through any other system and a licensee cannot\line +impose that choice.\line +\line +This section is intended to make thoroughly clear what is believed to\line +be a consequence of the rest of this License.\line +\line + 12. If the distribution and/or use of the Library is restricted in\line +certain countries either by patents or by copyrighted interfaces, the\line +original copyright holder who places the Library under this License may add\line +an explicit geographical distribution limitation excluding those countries,\line +so that distribution is permitted only in or among countries not thus\line +excluded. In such case, this License incorporates the limitation as if\line +written in the body of this License.\line +\line + 13. The Free Software Foundation may publish revised and/or new\line +versions of the Lesser General Public License from time to time.\line +Such new versions will be similar in spirit to the present version,\line +but may differ in detail to address new problems or concerns.\line +\line +Each version is given a distinguishing version number. If the Library\line +specifies a version number of this License which applies to it and\line +"any later version", you have the option of following the terms and\line +conditions either of that version or of any later version published by\line +the Free Software Foundation. If the Library does not specify a\line +license version number, you may choose any version ever published by\line +the Free Software Foundation.\line +\line + 14. If you wish to incorporate parts of the Library into other free\line +programs whose distribution conditions are incompatible with these,\line +write to the author to ask for permission. For software which is\line +copyrighted by the Free Software Foundation, write to the Free\line +Software Foundation; we sometimes make exceptions for this. Our\line +decision will be guided by the two goals of preserving the free status\line +of all derivatives of our free software and of promoting the sharing\line +and reuse of software generally.\line +\line + NO WARRANTY\line +\line + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\line +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\line +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\line +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY\line +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\line +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\line +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\line +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\line +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\line +\line + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\line +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\line +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\line +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\line +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\line +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\line +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\line +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\line +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\line +DAMAGES.\line + END OF TERMS AND CONDITIONS\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 GNU LGPL Version 3 License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 GNU LESSER GENERAL PUBLIC LICENSE\line + Version 3, 29 June 2007\line +\line + Copyright (C) 2007 Free Software Foundation, Inc. \line + Everyone is permitted to copy and distribute verbatim copies\line + of this license document, but changing it is not allowed.\line +\line +\line + This version of the GNU Lesser General Public License incorporates\line +the terms and conditions of version 3 of the GNU General Public\line +License, supplemented by the additional permissions listed below.\line +\line + 0. Additional Definitions.\line +\line + As used herein, "this License" refers to version 3 of the GNU Lesser\line +General Public License, and the "GNU GPL" refers to version 3 of the GNU\line +General Public License.\line +\line + "The Library" refers to a covered work governed by this License,\line +other than an Application or a Combined Work as defined below.\line +\line + An "Application" is any work that makes use of an interface provided\line +by the Library, but which is not otherwise based on the Library.\line +Defining a subclass of a class defined by the Library is deemed a mode\line +of using an interface provided by the Library.\line +\line + A "Combined Work" is a work produced by combining or linking an\line +Application with the Library. The particular version of the Library\line +with which the Combined Work was made is also called the "Linked\line +Version".\line +\line + The "Minimal Corresponding Source" for a Combined Work means the\line +Corresponding Source for the Combined Work, excluding any source code\line +for portions of the Combined Work that, considered in isolation, are\line +based on the Application, and not on the Linked Version.\line +\line + The "Corresponding Application Code" for a Combined Work means the\line +object code and/or source code for the Application, including any data\line +and utility programs needed for reproducing the Combined Work from the\line +Application, but excluding the System Libraries of the Combined Work.\line +\line + 1. Exception to Section 3 of the GNU GPL.\line +\line + You may convey a covered work under sections 3 and 4 of this License\line +without being bound by section 3 of the GNU GPL.\line +\line + 2. Conveying Modified Versions.\line +\line + If you modify a copy of the Library, and, in your modifications, a\line +facility refers to a function or data to be supplied by an Application\line +that uses the facility (other than as an argument passed when the\line +facility is invoked), then you may convey a copy of the modified\line +version:\line +\line + a) under this License, provided that you make a good faith effort to\line + ensure that, in the event an Application does not supply the\line + function or data, the facility still operates, and performs\line + whatever part of its purpose remains meaningful, or\line +\line + b) under the GNU GPL, with none of the additional permissions of\line + this License applicable to that copy.\line +\line + 3. Object Code Incorporating Material from Library Header Files.\line +\line + The object code form of an Application may incorporate material from\line +a header file that is part of the Library. You may convey such object\line +code under terms of your choice, provided that, if the incorporated\line +material is not limited to numerical parameters, data structure\line +layouts and accessors, or small macros, inline functions and templates\line +(ten or fewer lines in length), you do both of the following:\line +\line + a) Give prominent notice with each copy of the object code that the\line + Library is used in it and that the Library and its use are\line + covered by this License.\line +\line + b) Accompany the object code with a copy of the GNU GPL and this license\line + document.\line +\line + 4. Combined Works.\line +\line + You may convey a Combined Work under terms of your choice that,\line +taken together, effectively do not restrict modification of the\line +portions of the Library contained in the Combined Work and reverse\line +engineering for debugging such modifications, if you also do each of\line +the following:\line +\line + a) Give prominent notice with each copy of the Combined Work that\line + the Library is used in it and that the Library and its use are\line + covered by this License.\line +\line + b) Accompany the Combined Work with a copy of the GNU GPL and this license\line + document.\line +\line + c) For a Combined Work that displays copyright notices during\line + execution, include the copyright notice for the Library among\line + these notices, as well as a reference directing the user to the\line + copies of the GNU GPL and this license document.\line +\line + d) Do one of the following:\line +\line + 0) Convey the Minimal Corresponding Source under the terms of this\line + License, and the Corresponding Application Code in a form\line + suitable for, and under terms that permit, the user to\line + recombine or relink the Application with a modified version of\line + the Linked Version to produce a modified Combined Work, in the\line + manner specified by section 6 of the GNU GPL for conveying\line + Corresponding Source.\line +\line + 1) Use a suitable shared library mechanism for linking with the\line + Library. A suitable mechanism is one that (a) uses at run time\line + a copy of the Library already present on the user's computer\line + system, and (b) will operate properly with a modified version\line + of the Library that is interface-compatible with the Linked\line + Version.\line +\line + e) Provide Installation Information, but only if you would otherwise\line + be required to provide such information under section 6 of the\line + GNU GPL, and only to the extent that such information is\line + necessary to install and execute a modified version of the\line + Combined Work produced by recombining or relinking the\line + Application with a modified version of the Linked Version. (If\line + you use option 4d0, the Installation Information must accompany\line + the Minimal Corresponding Source and Corresponding Application\line + Code. If you use option 4d1, you must provide the Installation\line + Information in the manner specified by section 6 of the GNU GPL\line + for conveying Corresponding Source.)\line +\line + 5. Combined Libraries.\line +\line + You may place library facilities that are a work based on the\line +Library side by side in a single library together with other library\line +facilities that are not Applications and are not covered by this\line +License, and convey such a combined library under terms of your\line +choice, if you do both of the following:\line +\line + a) Accompany the combined library with a copy of the same work based\line + on the Library, uncombined with any other library facilities,\line + conveyed under the terms of this License.\line +\line + b) Give prominent notice with the combined library that part of it\line + is a work based on the Library, and explaining where to find the\line + accompanying uncombined form of the same work.\line +\line + 6. Revised Versions of the GNU Lesser General Public License.\line +\line + The Free Software Foundation may publish revised and/or new versions\line +of the GNU Lesser General Public License from time to time. Such new\line +versions will be similar in spirit to the present version, but may\line +differ in detail to address new problems or concerns.\line +\line + Each version is given a distinguishing version number. If the\line +Library as you received it specifies that a certain numbered version\line +of the GNU Lesser General Public License "or any later version"\line +applies to it, you have the option of following the terms and\line +conditions either of that published version or of any later version\line +published by the Free Software Foundation. If the Library as you\line +received it does not specify a version number of the GNU Lesser\line +General Public License, you may choose any version of the GNU Lesser\line +General Public License ever published by the Free Software Foundation.\line +\line + If the Library as you received it specifies that a proxy can decide\line +whether future versions of the GNU Lesser General Public License shall\line +apply, that proxy's public statement of acceptance of any version is\line +permanent authorization for you to choose that version for the\line +Library.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 ISC License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 /* Copyright (c) 2015, Google Inc.\line + *\line + * Permission to use, copy, modify, and/or distribute this software for any\line + * purpose with or without fee is hereby granted, provided that the above\line + * copyright notice and this permission notice appear in all copies.\line + *\line + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\line + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\line + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\line + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\line + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\line + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\line + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 MIT License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Permission to use, copy, modify, and distribute this software and its documentation\line +for any purpose and without fee is hereby granted, provided that the above copyright\line +notice appear in all copies and that both that copyright notice and this permission\line +notice appear in supporting documentation, and that the name of M.I.T. not be used\line +in advertising or publicity pertaining to distribution of the software without\line +specific, written prior permission. M.I.T. makes no representations about the\line +suitability of this software for any purpose. It is provided "as is" without express\line +or implied warranty.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 OpenSSL License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 /* ====================================================================\line + * Copyright (c) 1998-2019 The OpenSSL Project. All rights reserved.\line + *\line + * Redistribution and use in source and binary forms, with or without\line + * modification, are permitted provided that the following conditions\line + * are met:\line + *\line + * 1. Redistributions of source code must retain the above copyright\line + * notice, this list of conditions and the following disclaimer.\line + *\line + * 2. Redistributions in binary form must reproduce the above copyright\line + * notice, this list of conditions and the following disclaimer in\line + * the documentation and/or other materials provided with the\line + * distribution.\line + *\line + * 3. All advertising materials mentioning features or use of this\line + * software must display the following acknowledgment:\line + * "This product includes software developed by the OpenSSL Project\line + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"\line + *\line + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to\line + * endorse or promote products derived from this software without\line + * prior written permission. For written permission, please contact\line + * openssl-core@openssl.org.\line + *\line + * 5. Products derived from this software may not be called "OpenSSL"\line + * nor may "OpenSSL" appear in their names without prior written\line + * permission of the OpenSSL Project.\line + *\line + * 6. Redistributions of any form whatsoever must retain the following\line + * acknowledgment:\line + * "This product includes software developed by the OpenSSL Project\line + * for use in the OpenSSL Toolkit (http://www.openssl.org/)"\line + *\line + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\line + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\line + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\line + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\line + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\line + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\line + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\line + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\line + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\line + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\line + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\line + * OF THE POSSIBILITY OF SUCH DAMAGE.\line + * ====================================================================\line + *\line + * This product includes cryptographic software written by Eric Young\line + * (eay@cryptsoft.com). This product includes software written by Tim\line + * Hudson (tjh@cryptsoft.com).\line + *\line + */\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 SSLeay License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)\line + * All rights reserved.\line + *\line + * This package is an SSL implementation written\line + * by Eric Young (eay@cryptsoft.com).\line + * The implementation was written so as to conform with Netscapes SSL.\line + *\line + * This library is free for commercial and non-commercial use as long as\line + * the following conditions are aheared to. The following conditions\line + * apply to all code found in this distribution, be it the RC4, RSA,\line + * lhash, DES, etc., code; not just the SSL code. The SSL documentation\line + * included with this distribution is covered by the same copyright terms\line + * except that the holder is Tim Hudson (tjh@cryptsoft.com).\line + *\line + * Copyright remains Eric Young's, and as such any Copyright notices in\line + * the code are not to be removed.\line + * If this package is used in a product, Eric Young should be given attribution\line + * as the author of the parts of the library used.\line + * This can be in the form of a textual message at program startup or\line + * in documentation (online or textual) provided with the package.\line + *\line + * Redistribution and use in source and binary forms, with or without\line + * modification, are permitted provided that the following conditions\line + * are met:\line + * 1. Redistributions of source code must retain the copyright\line + * notice, this list of conditions and the following disclaimer.\line + * 2. Redistributions in binary form must reproduce the above copyright\line + * notice, this list of conditions and the following disclaimer in the\line + * documentation and/or other materials provided with the distribution.\line + * 3. All advertising materials mentioning features or use of this software\line + * must display the following acknowledgement:\line + * "This product includes cryptographic software written by\line + * Eric Young (eay@cryptsoft.com)"\line + * The word 'cryptographic' can be left out if the rouines from the library\line + * being used are not cryptographic related :-).\line + * 4. If you include any Windows specific code (or a derivative thereof) from\line + * the apps directory (application code) you must include an acknowledgement:\line + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"\line + *\line + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\line + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\line + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\line + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\line + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\line + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\line + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\line + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\line + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\line + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\line + * SUCH DAMAGE.\line + *\line + * The licence and distribution terms for any publically available version or\line + * derivative of this code cannot be changed. i.e. this code cannot simply be\line + * copied and put under another distribution licence\line + * [including the GNU Public Licence.]\line + */\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 libssh OpenSSL Exception\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Linking with OpenSSL\line + 17. In addition, as a special exception, we give permission to link the code of\line +its release of libssh with the OpenSSL project's "OpenSSL" library (or with modified\line +versions of it that use the same license as the "OpenSSL" library), and distribute\line +the linked executables. You must obey the GNU Lesser General Public License in all\line +respects for all of the code used other than "OpenSSL". If you modify this file, you\line +may extend this exception to your version of the file, but you are not obligated to\line +do so. If you do not wish to do so, delete this exception statement from your\line +version.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 libffi License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Permission is hereby granted, free of charge, to any person obtaining\line +a copy of this software and associated documentation files (the\line +``Software''), to deal in the Software without restriction, including\line +without limitation the rights to use, copy, modify, merge, publish,\line +distribute, sublicense, and/or sell copies of the Software, and to\line +permit persons to whom the Software is furnished to do so, subject to\line +the following conditions:\line +\line +The above copyright notice and this permission notice shall be\line +included in all copies or substantial portions of the Software.\line +\line +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,\line +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\line +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\line +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\line +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\line +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\line +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 p11-kit License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Redistribution and use in source and binary forms, with or without\line +modification, are permitted provided that the following conditions\line +are met:\line +\line + * Redistributions of source code must retain the above\line + copyright notice, this list of conditions and the\line + following disclaimer.\line + * Redistributions in binary form must reproduce the\line + above copyright notice, this list of conditions and\line + the following disclaimer in the documentation and/or\line + other materials provided with the distribution.\line + * The names of contributors to this software may not be\line + used to endorse or promote products derived from this\line + software without specific prior written permission.\line +\line +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\line +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\line +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\line +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\line +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\line +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\line +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\line +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\line +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\line +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\line +THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\line +DAMAGE.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 xz-embedded License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 All the files in this package have been written by Lasse Collin\line +and/or Igor Pavlov. All these files have been put into the\line +public domain. You can do whatever you want with these files.\line +\line +As usual, this software is provided "as is", without any warranty.\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \outlinelevel3 \b \fs24 zlib License\par} +{\pard \ql \f0 \sa180 \li0 \fi0 \f1 This software is provided 'as-is', without any express or implied\line +warranty. In no event will the authors be held liable for any damages\line +arising from the use of this software.\line +\line +Permission is granted to anyone to use this software for any purpose,\line +including commercial applications, and to alter it and redistribute it\line +freely, subject to the following restrictions:\line +\line +1. The origin of this software must not be misrepresented; you must not\line + claim that you wrote the original software. If you use this software\line + in a product, an acknowledgment in the product documentation would be\line + appreciated but is not required.\line +2. Altered source versions must be plainly marked as such, and must not be\line + misrepresented as being the original software.\line +3. This notice may not be removed or altered from any source distribution.\line +\line + Jean-loup Gailly Mark Adler\line + jloup@gzip.org madler@alumni.caltech.edu\line +\line +If you use the zlib library in a product, we would appreciate *not* receiving\line +lengthy legal documents to sign. The sources are provided for free but without\line +warranty of any kind. The library has been entirely written by Jean-loup\line +Gailly and Mark Adler; it does not include third-party code.\line +\line +If you redistribute modified sources, we would appreciate that you include in\line +the file ChangeLog history information documenting your changes. Please read\line +the FAQ for more information on the distribution of modified source versions.\par} +} diff --git a/packaging/windows/LICENCE.txt b/packaging/windows/LICENCE.txt new file mode 100644 index 0000000000..5621961199 --- /dev/null +++ b/packaging/windows/LICENCE.txt @@ -0,0 +1,2112 @@ +#### Multipass +Copyright © Canonical Ltd. +GPL-3.0 + +https://github.com/canonical/multipass/ + +#### Open source projects used directly: +- fmt: https://github.com/fmtlib/fmt +- grpc: https://github.com/grpc/grpc + - abseil-cpp: https://github.com/abseil/abseil-cpp + - c-ares: https://github.com/c-ares/c-ares + - gflags: https://github.com/gflags/gflags + - protobuf: https://github.com/google/protobuf + - zlib: https://github.com/madler/zlib +- libssh: https://git.libssh.org/projects/libssh.git/ +- poco: https://github.com/pocoproject/poco +- qt: https://www.qt.io/ +- semver: https://github.com/zmarko/semver +- xz-embedded: https://git.tukaani.org/?p=xz-embedded.git +- yaml-cpp: https://github.com/jbeder/yaml-cpp + +#### Additional binaries used: +- qemu (qemu-img): https://chocolatey.org/packages/qemu-img +- OpenSSL (libssl-1_1-x64.dll & libcrypto-1_1-x64.dll): https://chocolatey.org/packages/openssl + +#### Licensing: +Below is a summary of the licensing used in the respective projects. See their source repositories, linked above, for details. + +- fmt: BSD 2-Clause "Simplified" License; Copyright (c) 2012 - 2016, Victor Zverovich +- grpc: Apache License 2.0 +- abseil-cpp: Apache License 2.0 +- c-ares: MIT License; Copyright (c) 2007 - 2018, Daniel Stenberg with many contributors, see AUTHORS file. +- gflags: BSD 3-Clause "New" or "Revised" License; Copyright (c) 2006, Google Inc. +- protobuf: BSD 3-Clause "New" or "Revised" License; Copyright 2008 Google Inc. +- zlib: zlib License; (C) 1995-2017 Jean-loup Gailly and Mark Adler +- libssh: + - GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information + - OpenSSL Exception +- poco: Boost Software License - Version 1.0 - August 17th, 2003 +- qt: GNU LGPL Version 3; Copyright (c) 2016 The Qt Company +- semver: MIT License; Copyright (c) 2015 Marko Živanović +- xz-embedded: zx-embedded License; +- yaml-cpp: MIT License; Copyright (c) 2008-2015 Jesse Beder. +- gettext (libintl): GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information +- glib: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information +- gmp: GNU LGPL Version 3 License; See AUTHORS file for Copyright information +- gnutls: GNU LGPL Version 2.1 and 3 Licenses; See AUTHORS file for Copyright information +- libffi: libffi License; Copyright (c) 1996-2014 Anthony Green, Red Hat, Inc and others. +- libtasn1: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information +- libunistring: GNU LGPL Version 3 License; See AUTHORS file for Copyright information +- nettle: GNU LGPL Version 3 License; See AUTHORS file for Copyright information +- p11-kit: p11-kit License; +- pcre: GNU LGPL Version 2.1 License; See AUTHORS file for Copyright information +- qemu (qemu-img): GNU GPL Version 2 License; See AUTHORS file for Copyright information +- OpenSSL (libssl-1_1-x64.dll & libcrypto-1_1-x64.dll): + - OpenSSL; Copyright (c) 1998-2020 The OpenSSL Project. + - SSLeay; Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + +#### Licenses: +Below are the contents of all the licenses used across all the projects distributed along with Multipass. + +#### Apache License 2.0 +``` + 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 + ``` + +#### Boost Software License - Version 1.0 - August 17th, 2003 +``` +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +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, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +``` + +#### BSD 2-Clause "Simplified" License +``` +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. + +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. +``` + +#### BSD 3-Clause "New" or "Revised" License +``` +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 Google Inc. 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 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. +``` + +#### GNU GPL Version 3 License +``` + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The 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 +``` + +#### GNU GPL Version 2 License +``` + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS +``` + +#### GNU LGPL Version 2.1 License +``` + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + END OF TERMS AND CONDITIONS +``` + +#### GNU LGPL Version 3 License +``` + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. +``` + +#### ISC License +``` +/* Copyright (c) 2015, Google Inc. + * + * Permission to use, copy, modify, and/or 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. */ +``` + +#### MIT License +``` +Permission to use, copy, modify, and distribute this software and its documentation +for any purpose and without fee is hereby granted, provided that the above copyright +notice appear in all copies and that both that copyright notice and this permission +notice appear in supporting documentation, and that the name of M.I.T. not be used +in advertising or publicity pertaining to distribution of the software without +specific, written prior permission. M.I.T. makes no representations about the +suitability of this software for any purpose. It is provided "as is" without express +or implied warranty. +``` + +#### OpenSSL License +``` +/* ==================================================================== + * Copyright (c) 1998-2019 The OpenSSL 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. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED 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 OpenSSL PROJECT OR + * ITS 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. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +``` + +#### SSLeay License +``` +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + ``` + +#### libssh OpenSSL Exception +``` +Linking with OpenSSL + 17. In addition, as a special exception, we give permission to link the code of +its release of libssh with the OpenSSL project's "OpenSSL" library (or with modified +versions of it that use the same license as the "OpenSSL" library), and distribute +the linked executables. You must obey the GNU Lesser General Public License in all +respects for all of the code used other than "OpenSSL". If you modify this file, you +may extend this exception to your version of the file, but you are not obligated to +do so. If you do not wish to do so, delete this exception statement from your +version. +``` + +#### libffi License +``` +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. +``` + +#### p11-kit License +``` +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. + * The names of contributors to this software may not 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. +``` + +#### xz-embedded License +``` +All the files in this package have been written by Lasse Collin +and/or Igor Pavlov. All these files have been put into the +public domain. You can do whatever you want with these files. + +As usual, this software is provided "as is", without any warranty. +``` + +#### zlib License +``` +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. +``` diff --git a/packaging/windows/custom-actions/custom-actions.vcxproj b/packaging/windows/custom-actions/custom-actions.vcxproj new file mode 100644 index 0000000000..ac169a4d2a --- /dev/null +++ b/packaging/windows/custom-actions/custom-actions.vcxproj @@ -0,0 +1,115 @@ + + + + + + + Debug + x64 + + + Release + x64 + + + + Win32Proj + {33d9cfb8-6c19-4a45-a950-0f3fb1d9017a} + custom_actions + v142 + 10.0 + + + + DynamicLibrary + true + Unicode + + + DynamicLibrary + false + true + Unicode + + + + + + + + + + + + + + + + C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\SDKs\DismApi\Include;%(AdditionalIncludeDirectories) + Level3 + true + _DEBUG;EXAMPLECADLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + MultiThreadedDebug + + + msi.lib;version.lib;%(AdditionalDependencies) + C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\SDKs\DismApi\Lib\amd64\ + Windows + true + false + custom_actions.def + + + + + C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\SDKs\DismApi\Include;%(AdditionalIncludeDirectories) + Level3 + true + true + true + NDEBUG;EXAMPLECADLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + MultiThreaded + + + msi.lib;version.lib;%(AdditionalDependencies) + C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\SDKs\DismApi\Lib\amd64\ + Windows + true + true + true + false + custom_actions.def + + + + + + + + + + + Create + Create + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + diff --git a/packaging/windows/custom-actions/custom-actions.vcxproj.user b/packaging/windows/custom-actions/custom-actions.vcxproj.user new file mode 100644 index 0000000000..98dadff166 --- /dev/null +++ b/packaging/windows/custom-actions/custom-actions.vcxproj.user @@ -0,0 +1,4 @@ + + + + diff --git a/packaging/windows/custom-actions/custom_actions.cpp b/packaging/windows/custom-actions/custom_actions.cpp new file mode 100644 index 0000000000..1e6f04a73f --- /dev/null +++ b/packaging/windows/custom-actions/custom_actions.cpp @@ -0,0 +1,148 @@ +// CustomAction.cpp : Defines the entry point for the custom action. +#include "pch.h" +#include +#include +#include +#include +#include +#pragma comment(lib, "dismapi.lib") + +UINT __stdcall AskRemoveData(__in MSIHANDLE hInstall) +{ + HRESULT hr = S_OK; + DWORD er = ERROR_SUCCESS; + WCHAR szBuf[1024]; + DWORD cchBuf = _countof(szBuf); + PMSIHANDLE hRec; + UINT removeData; + + hr = WcaInitialize(hInstall, __FUNCTION__); + ExitOnFailure(hr, "Failed to initialize"); + + WcaLog(LOGMSG_STANDARD, "Begin AskRemoveData."); + + hr = MsiGetProperty(hInstall, L"RemoveDataText", szBuf, &cchBuf); + ExitOnFailure(hr, "Failed getting RemoveDataText"); + + hRec = MsiCreateRecord(1); + ExitOnNullWithLastError(hRec, hr, "Failed to create record"); + + MsiRecordSetString(hRec, 0, szBuf); + removeData = MsiProcessMessage(hInstall, INSTALLMESSAGE(MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2), hRec); + + if (removeData == IDYES) + hr = MsiSetProperty(hInstall, L"REMOVE_DATA", L"yes"); + else if (removeData == IDNO) + hr = MsiSetProperty(hInstall, L"REMOVE_DATA", L"no"); + ExitOnFailure(hr, "Failed setting property '%hs'", L"REMOVE_DATA") + + // clang-format off +LExit: + er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_UNKNOWN_PROPERTY; + return WcaFinalize(er); + // clang-format on +} + +UINT __stdcall EnableHyperV(__in MSIHANDLE hInstall) +{ + HRESULT hr = S_OK; + DWORD er = ERROR_SUCCESS; + HANDLE hCancel_ = NULL; + WCHAR szBuf[1024]; + DWORD cchBuf = _countof(szBuf); + DismSession hSession = DISM_SESSION_DEFAULT; + DismString* pErrorString = nullptr; + BOOL bDismInit = FALSE; + PMSIHANDLE hActionData; + UINT uiLevel; + DWORD exitCode = 0; + + hr = WcaInitialize(hInstall, __FUNCTION__); + ExitOnFailure(hr, "Failed to initialize"); + WcaLog(LOGMSG_STANDARD, "Begin EnableHyperV."); + + hr = MsiGetProperty(hInstall, TEXT("CustomActionData"), szBuf, &cchBuf); + ExitOnFailure(hr, "Failed getting CustomActionData"); + + uiLevel = _ttoi(szBuf); + WcaLog(LOGMSG_STANDARD, std::to_string(uiLevel).c_str()); + + hCancel_ = CreateEvent(nullptr, TRUE, FALSE, nullptr); + ExitOnNullWithLastError(hCancel_, hr, "Failed creating event"); + + hr = DismInitialize(DismLogErrorsWarningsInfo, NULL, NULL); + if (FAILED(hr)) + { + DismGetLastErrorMessage(&pErrorString); + ExitOnFailure(hr, + "Failed initializing DISM. %ls", + (pErrorString && pErrorString->Value) ? pErrorString->Value : L""); + } + bDismInit = TRUE; + + hr = DismOpenSession(DISM_ONLINE_IMAGE, nullptr, nullptr, &hSession); + if (FAILED(hr)) + { + DismGetLastErrorMessage(&pErrorString); + ExitOnFailure(hr, + "Failed opening DISM online session. %ls", + (pErrorString && pErrorString->Value) ? pErrorString->Value : L""); + } + + WcaLog(LOGMSG_STANDARD, "Enabling feature Microsoft-Hyper-V"); + + hActionData = MsiCreateRecord(1); + if (hActionData && SUCCEEDED(WcaSetRecordString(hActionData, 1, L"Microsoft-Hyper-V"))) + WcaProcessMessage(INSTALLMESSAGE::INSTALLMESSAGE_ACTIONDATA, hActionData); + + hr = DismEnableFeature(hSession, + L"Microsoft-Hyper-V", + nullptr, + DismPackageNone, + FALSE, + nullptr, + 0, + TRUE, + hCancel_, + nullptr, + nullptr); + if (HRESULT_CODE(hr) == ERROR_SUCCESS_REBOOT_REQUIRED) + { + hr = S_OK; + WcaLog(LOGMSG_STANDARD, "Enabled feature Microsoft-Hyper-V. However, it requires reboot to complete"); + if (uiLevel > 3) + WcaDeferredActionRequiresReboot(); + else + WcaLog(LOGMSG_STANDARD, "Silent install. Skipping reboot"); + } + + if (FAILED(hr)) + { + DismGetLastErrorMessage(&pErrorString); + WcaLogError(hr, + "Failed enabling feature Microsoft-Hyper-V. %ls", + (pErrorString && pErrorString->Value) ? pErrorString->Value : L""); + ExitOnFailure(hr, "Failed enabling feature"); + } + + // Cancelled? + if (WaitForSingleObject(hCancel_, 0) == WAIT_OBJECT_0) + { + WcaLog(LOGMSG_STANDARD, "Seems like DISM was canceled."); + hr = S_FALSE; + ExitFunction(); + } + +LExit: + if (hCancel_) + CloseHandle(hCancel_); + if (pErrorString) + DismDelete(pErrorString); + if (hSession != DISM_SESSION_DEFAULT) + DismCloseSession(hSession); + if (bDismInit) + DismShutdown(); + + er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_UNKNOWN_PROPERTY; + return WcaFinalize(er); +} diff --git a/packaging/windows/custom-actions/custom_actions.def b/packaging/windows/custom-actions/custom_actions.def new file mode 100644 index 0000000000..f3522c2dc7 --- /dev/null +++ b/packaging/windows/custom-actions/custom_actions.def @@ -0,0 +1,5 @@ +LIBRARY "custom-actions" + +EXPORTS + AskRemoveData + EnableHyperV diff --git a/packaging/windows/custom-actions/custom_actions.vcxproj.filters b/packaging/windows/custom-actions/custom_actions.vcxproj.filters new file mode 100644 index 0000000000..47f93de025 --- /dev/null +++ b/packaging/windows/custom-actions/custom_actions.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + + + + Source Files + + + diff --git a/packaging/windows/custom-actions/dllmain.cpp b/packaging/windows/custom-actions/dllmain.cpp new file mode 100644 index 0000000000..e37256c959 --- /dev/null +++ b/packaging/windows/custom-actions/dllmain.cpp @@ -0,0 +1,22 @@ +// dllmain.cpp : Defines the entry point for the DLL application. +#include "pch.h" + +BOOL APIENTRY DllMain(__in HMODULE hModule, __in DWORD ulReasonForCall, __in LPVOID) +{ + switch (ulReasonForCall) + { + case DLL_PROCESS_ATTACH: + WcaGlobalInitialize(hModule); + break; + + case DLL_PROCESS_DETACH: + WcaGlobalFinalize(); + break; + + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + break; + } + + return TRUE; +} diff --git a/packaging/windows/custom-actions/framework.h b/packaging/windows/custom-actions/framework.h new file mode 100644 index 0000000000..a78e2457ac --- /dev/null +++ b/packaging/windows/custom-actions/framework.h @@ -0,0 +1,11 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +// Windows Header Files +// clang-format off +#include +#include +#include // clang-format on + +// WiX Header Files: +#include diff --git a/packaging/windows/custom-actions/packages.config b/packaging/windows/custom-actions/packages.config new file mode 100644 index 0000000000..45c708ac4b --- /dev/null +++ b/packaging/windows/custom-actions/packages.config @@ -0,0 +1,5 @@ + + + + + diff --git a/packaging/windows/custom-actions/pch.cpp b/packaging/windows/custom-actions/pch.cpp new file mode 100644 index 0000000000..64b7eef6d6 --- /dev/null +++ b/packaging/windows/custom-actions/pch.cpp @@ -0,0 +1,5 @@ +// pch.cpp: source file corresponding to the pre-compiled header + +#include "pch.h" + +// When you are using pre-compiled headers, this source file is necessary for compilation to succeed. diff --git a/packaging/windows/custom-actions/pch.h b/packaging/windows/custom-actions/pch.h new file mode 100644 index 0000000000..cc757129ac --- /dev/null +++ b/packaging/windows/custom-actions/pch.h @@ -0,0 +1,13 @@ +// pch.h: This is a precompiled header file. +// Files listed below are compiled only once, improving build performance for future builds. +// This also affects IntelliSense performance, including code completion and many code browsing features. +// However, files listed here are ALL re-compiled if any one of them is updated between builds. +// Do not add files here that you will be updating frequently as this negates the performance advantage. + +#ifndef PCH_H +#define PCH_H + +// add headers that you want to pre-compile here +#include "framework.h" + +#endif // PCH_H diff --git a/packaging/windows/fonts/UBUNTU-LICENCE.txt b/packaging/windows/fonts/UBUNTU-LICENCE.txt new file mode 100644 index 0000000000..b1a7649cd2 --- /dev/null +++ b/packaging/windows/fonts/UBUNTU-LICENCE.txt @@ -0,0 +1,98 @@ +------------------------------- +UBUNTU FONT LICENCE Version 1.0 +------------------------------- + +PREAMBLE +This licence allows the licensed fonts to be used, studied, modified and +redistributed freely. The fonts, including any derivative works, can be +bundled, embedded, and redistributed provided the terms of this licence +are met. The fonts and derivatives, however, cannot be released under +any other licence. The requirement for fonts to remain under this +licence does not require any document created using the fonts or their +derivatives to be published under this licence, as long as the primary +purpose of the document is not to be a vehicle for the distribution of +the fonts. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this licence and clearly marked as such. This may +include source files, build scripts and documentation. + +"Original Version" refers to the collection of Font Software components +as received under this licence. + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to +a new environment. + +"Copyright Holder(s)" refers to all individuals and companies who have a +copyright ownership of the Font Software. + +"Substantially Changed" refers to Modified Versions which can be easily +identified as dissimilar to the Font Software by users of the Font +Software comparing the Original Version with the Modified Version. + +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 and with or without charging +a redistribution fee), making available to the public, and in some +countries other activities as well. + +PERMISSION & CONDITIONS +This licence does not grant any rights under trademark law and all such +rights are reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of the Font Software, to propagate the Font Software, subject to +the below conditions: + +1) Each copy of the Font Software must contain the above copyright +notice and this licence. These can be included either as stand-alone +text files, human-readable headers or in the appropriate machine- +readable metadata fields within text or binary files as long as those +fields can be easily viewed by the user. + +2) The font name complies with the following: +(a) The Original Version must retain its name, unmodified. +(b) Modified Versions which are Substantially Changed must be renamed to +avoid use of the name of the Original Version or similar names entirely. +(c) Modified Versions which are not Substantially Changed must be +renamed to both (i) retain the name of the Original Version and (ii) add +additional naming elements to distinguish the Modified Version from the +Original Version. The name of such Modified Versions must be the name of +the Original Version, with "derivative X" where X represents the name of +the new work, appended to that name. + +3) The name(s) of the Copyright Holder(s) and any contributor to the +Font Software shall not be used to promote, endorse or advertise any +Modified Version, except (i) as required by this licence, (ii) to +acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with +their explicit written permission. + +4) The Font Software, modified or unmodified, in part or in whole, must +be distributed entirely under this licence, and must not be distributed +under any other licence. The requirement for fonts to remain under this +licence does not affect any document created using the Font Software, +except any version of the Font Software extracted from a document +created using the Font Software may only be distributed under this +licence. + +TERMINATION +This licence becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER +DEALINGS IN THE FONT SOFTWARE. + +https://font.ubuntu.com/ diff --git a/packaging/windows/fonts/UbuntuMono-R.ttf b/packaging/windows/fonts/UbuntuMono-R.ttf new file mode 100644 index 0000000000..0ba266a77c Binary files /dev/null and b/packaging/windows/fonts/UbuntuMono-R.ttf differ diff --git a/packaging/windows/icon.ico b/packaging/windows/icon.ico new file mode 120000 index 0000000000..16d66dfd30 --- /dev/null +++ b/packaging/windows/icon.ico @@ -0,0 +1 @@ +../../data/icon.ico \ No newline at end of file diff --git a/packaging/windows/icon_wt.ico b/packaging/windows/icon_wt.ico new file mode 100755 index 0000000000..a1af703737 Binary files /dev/null and b/packaging/windows/icon_wt.ico differ diff --git a/packaging/windows/multipass.bmp b/packaging/windows/multipass.bmp new file mode 100644 index 0000000000..ddfa5af9c7 Binary files /dev/null and b/packaging/windows/multipass.bmp differ diff --git a/packaging/windows/template.rtf b/packaging/windows/template.rtf new file mode 100644 index 0000000000..6f203c7edf --- /dev/null +++ b/packaging/windows/template.rtf @@ -0,0 +1,30 @@ +{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Segoe UI;}{\f1 Courier;}}\fs16 +{\colortbl;\red255\green0\blue0;\red0\green0\blue255;} +\widowctrl\hyphauto +$for(header-includes)$ +$header-includes$ +$endfor$ + +$if(title)$ +{\pard \qc \f0 \sa180 \li0 \fi0 \b \fs36 $title$\par} +$endif$ +$for(author)$ +{\pard \qc \f0 \sa180 \li0 \fi0 $author$\par} +$endfor$ +$if(date)$ +{\pard \qc \f0 \sa180 \li0 \fi0 $date$\par} +$endif$ +$if(spacer)$ +{\pard \ql \f0 \sa180 \li0 \fi0 \par} +$endif$ +$if(toc)$ +$table-of-contents$ +$endif$ +$for(include-before)$ +$include-before$ +$endfor$ +$body$ +$for(include-after)$ +$include-after$ +$endfor$ +} diff --git a/packaging/windows/wix/CLIClientComponents.wxs b/packaging/windows/wix/CLIClientComponents.wxs new file mode 100644 index 0000000000..ad6c67bcbd --- /dev/null +++ b/packaging/windows/wix/CLIClientComponents.wxs @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/DaemonComponents.wxs b/packaging/windows/wix/DaemonComponents.wxs new file mode 100644 index 0000000000..377666d533 --- /dev/null +++ b/packaging/windows/wix/DaemonComponents.wxs @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/GUIComponents.wxs b/packaging/windows/wix/GUIComponents.wxs new file mode 100644 index 0000000000..0c11c1a389 --- /dev/null +++ b/packaging/windows/wix/GUIComponents.wxs @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/Package.en-us.wxl b/packaging/windows/wix/Package.en-us.wxl new file mode 100644 index 0000000000..e3e0e860c2 --- /dev/null +++ b/packaging/windows/wix/Package.en-us.wxl @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/Package.wxs b/packaging/windows/wix/Package.wxs new file mode 100644 index 0000000000..4732c762cd --- /dev/null +++ b/packaging/windows/wix/Package.wxs @@ -0,0 +1,230 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/filter.xsl b/packaging/windows/wix/filter.xsl new file mode 100644 index 0000000000..a3402f02cf --- /dev/null +++ b/packaging/windows/wix/filter.xsl @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/multipass.wixproj b/packaging/windows/wix/multipass.wixproj new file mode 100644 index 0000000000..2e8294b070 --- /dev/null +++ b/packaging/windows/wix/multipass.wixproj @@ -0,0 +1,41 @@ + + + + 0.0 + Version=$(BuildVersion) + x64 + ICE69;ICE61;ICE03 + bin\$(Configuration)\ + + + + + + + + + + + + + + + + + + + + + + MultipassSupportComponents + INSTALLFOLDER + true + true + filter.xsl + + + + + + + diff --git a/packaging/windows/wix/ui/CustomInstallDirDlg.wxs b/packaging/windows/wix/ui/CustomInstallDirDlg.wxs new file mode 100644 index 0000000000..92c522f983 --- /dev/null +++ b/packaging/windows/wix/ui/CustomInstallDirDlg.wxs @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/ui/CustomWelcomeDlg.wxs b/packaging/windows/wix/ui/CustomWelcomeDlg.wxs new file mode 100644 index 0000000000..b68e39f21c --- /dev/null +++ b/packaging/windows/wix/ui/CustomWelcomeDlg.wxs @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/ui/CustomWixUI_InstallDir.wxs b/packaging/windows/wix/ui/CustomWixUI_InstallDir.wxs new file mode 100644 index 0000000000..c8e5339174 --- /dev/null +++ b/packaging/windows/wix/ui/CustomWixUI_InstallDir.wxs @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/ui/UninstallExeMPDlg.wxs b/packaging/windows/wix/ui/UninstallExeMPDlg.wxs new file mode 100644 index 0000000000..fa20614f9e --- /dev/null +++ b/packaging/windows/wix/ui/UninstallExeMPDlg.wxs @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/ui/WixUI_ChooseHypervisor.wxs b/packaging/windows/wix/ui/WixUI_ChooseHypervisor.wxs new file mode 100644 index 0000000000..143050db83 --- /dev/null +++ b/packaging/windows/wix/ui/WixUI_ChooseHypervisor.wxs @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/wix/ui/WixUI_ChoosePathInstall.wxs b/packaging/windows/wix/ui/WixUI_ChoosePathInstall.wxs new file mode 100644 index 0000000000..d4e2db7e77 --- /dev/null +++ b/packaging/windows/wix/ui/WixUI_ChoosePathInstall.wxs @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/blueprint_provider/default_vm_blueprint_provider.cpp b/src/blueprint_provider/default_vm_blueprint_provider.cpp index 1828d94b89..d176c9d2c1 100644 --- a/src/blueprint_provider/default_vm_blueprint_provider.cpp +++ b/src/blueprint_provider/default_vm_blueprint_provider.cpp @@ -433,9 +433,6 @@ mp::Query mp::DefaultVMBlueprintProvider::blueprint_from_file(const std::string& VirtualMachineDescription& vm_desc, ClientLaunchData& client_launch_data) { - if (!MP_PLATFORM.is_image_url_supported()) - throw std::runtime_error(fmt::format("Launching a Blueprint from a file is not supported")); - mpl::log(mpl::Level::debug, category, fmt::format("Reading Blueprint '{}' from file {}", blueprint_name, path)); QFileInfo file_info{QString::fromStdString(path)}; diff --git a/src/client/cli/CMakeLists.txt b/src/client/cli/CMakeLists.txt index b8aa3ba804..c208632bf4 100644 --- a/src/client/cli/CMakeLists.txt +++ b/src/client/cli/CMakeLists.txt @@ -23,6 +23,7 @@ target_link_libraries(client formatter rpc scope_guard + shared Qt6::Core) add_executable(multipass @@ -35,5 +36,22 @@ install(TARGETS multipass DESTINATION bin COMPONENT multipass) +if(APPLE) + set_target_properties( multipass PROPERTIES INSTALL_RPATH "@executable_path/../lib" ) + + # Copy any framework depenencies into the install directory for packaging + install(CODE " + include(${CMAKE_SOURCE_DIR}/packaging/FrameworkUtilities.cmake) + install_frameworks(\"${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/multipass\" \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/lib\") + " COMPONENT multipass) +endif(APPLE) + +if(MSVC) + install(CODE " + include(BundleUtilities) + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/bin/multipass.exe\" \"\" \"${CMAKE_RUNTIME_OUTPUT_DIRECTORY}\") + " COMPONENT multipass) +endif() + add_subdirectory(cmd) add_subdirectory(formatter) diff --git a/src/client/gui/.metadata b/src/client/gui/.metadata index d9ca52af72..0a3b89faa7 100644 --- a/src/client/gui/.metadata +++ b/src/client/gui/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled. version: - revision: 4b12645012342076800eb701bcdfe18f87da21cf + revision: 796c8ef79279f9c774545b3771238c3098dbefab channel: stable project_type: app @@ -13,14 +13,14 @@ project_type: app migration: platforms: - platform: root - create_revision: 4b12645012342076800eb701bcdfe18f87da21cf - base_revision: 4b12645012342076800eb701bcdfe18f87da21cf + create_revision: 796c8ef79279f9c774545b3771238c3098dbefab + base_revision: 796c8ef79279f9c774545b3771238c3098dbefab - platform: linux create_revision: 4b12645012342076800eb701bcdfe18f87da21cf base_revision: 4b12645012342076800eb701bcdfe18f87da21cf - platform: macos - create_revision: 4b12645012342076800eb701bcdfe18f87da21cf - base_revision: 4b12645012342076800eb701bcdfe18f87da21cf + create_revision: 796c8ef79279f9c774545b3771238c3098dbefab + base_revision: 796c8ef79279f9c774545b3771238c3098dbefab - platform: windows create_revision: 4b12645012342076800eb701bcdfe18f87da21cf base_revision: 4b12645012342076800eb701bcdfe18f87da21cf diff --git a/src/client/gui/CMakeLists.txt b/src/client/gui/CMakeLists.txt index 37168169a6..d32aaecf76 100644 --- a/src/client/gui/CMakeLists.txt +++ b/src/client/gui/CMakeLists.txt @@ -33,5 +33,13 @@ if(MULTIPASS_ENABLE_FLUTTER_GUI) set(MULTIPASS_GUI_ARCH arm64) endif() - include("CMakeLists.txt.linux") + if(UNIX) + if(APPLE) + include("CMakeLists.txt.macos") + else() # Linux + include("CMakeLists.txt.linux") + endif() + else() # Windows + include("CMakeLists.txt.windows") + endif() endif() diff --git a/src/client/gui/CMakeLists.txt.macos b/src/client/gui/CMakeLists.txt.macos new file mode 100644 index 0000000000..10feadaaf1 --- /dev/null +++ b/src/client/gui/CMakeLists.txt.macos @@ -0,0 +1,64 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +set(MULTIPASS_GUI_TARGET macos) +set(MULTIPASS_GUI_PREFIX macos/Build/Products/Release) +set(MULTIPASS_GUI_BUNDLE_RELATIVE "Multipass.app") +set(MULTIPASS_GUI_EXEC_PATH_RELATIVE_TO_BUNDLE Contents/MacOS) +set(MULTIPASS_GUI_EXECUTABLE multipass_gui) + +set(MULTIPASS_GUI_BUILD_DIR ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +cmake_path(RELATIVE_PATH MULTIPASS_GUI_BUILD_DIR) + +set(MULTIPASS_GUI_PATH ${MULTIPASS_GUI_BUILD_DIR}/${MULTIPASS_GUI_PREFIX}) +set(MULTIPASS_GUI_BUNDLE ${MULTIPASS_GUI_PATH}/${MULTIPASS_GUI_BUNDLE_RELATIVE}) +set(MULTIPASS_GUI_SOURCE_DIR ${CMAKE_SOURCE_DIR}/src/client/gui) +set(MULTIPASS_GUI_LINK_NAME multipass.gui) +set(MULTIPASS_GUI_EXECUTABLE_FULL_PATH ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${MULTIPASS_GUI_PREFIX}/${MULTIPASS_GUI_BUNDLE_RELATIVE}/${MULTIPASS_GUI_EXEC_PATH_RELATIVE_TO_BUNDLE}/${MULTIPASS_GUI_EXECUTABLE}) + +file(GLOB_RECURSE MULTIPASS_GUI_SOURCE_FILES ${MULTIPASS_GUI_SOURCE_DIR}/lib/*.dart) + +set(FLUTTER_BUILD_ARGS --release --suppress-analytics --verbose --no-tree-shake-icons --build-name=${MULTIPASS_SEMANTIC_VERSION} --build-number=${MULTIPASS_BUILD_NUMBER}) + +add_custom_command(OUTPUT ${MULTIPASS_GUI_EXECUTABLE_FULL_PATH} + DEPENDS ${MULTIPASS_GUI_SOURCE_FILES} + WORKING_DIRECTORY ${MULTIPASS_GUI_SOURCE_DIR} + COMMAND ${CMAKE_COMMAND} -E make_directory lib/generated + COMMAND $ --plugin=protoc-gen-dart=${DART_PROTOC_PLUGIN} --dart_out=grpc:lib/generated -I ../../rpc ../../rpc/multipass.proto google/protobuf/timestamp.proto + COMMAND ${FLUTTER_EXECUTABLE} config --build-dir=${MULTIPASS_GUI_BUILD_DIR} + COMMAND ${FLUTTER_EXECUTABLE} build ${MULTIPASS_GUI_TARGET} ${FLUTTER_BUILD_ARGS} + COMMAND ${FLUTTER_EXECUTABLE} config --build-dir= +) + +add_custom_target(${MULTIPASS_GUI_EXECUTABLE} ALL + DEPENDS ${MULTIPASS_GUI_EXECUTABLE_FULL_PATH} +) + +install(DIRECTORY ${MULTIPASS_GUI_BUNDLE}/Contents + DESTINATION "bin/Multipass.app/" + USE_SOURCE_PERMISSIONS + COMPONENT multipass_gui + PATTERN "*/PkgInfo" EXCLUDE + PATTERN "*/_CodeSignature*" EXCLUDE +) + +set_target_properties( ${MULTIPASS_GUI_EXECUTABLE} PROPERTIES + MACOSX_BUNDLE TRUE + INSTALL_RPATH "@executable_path/../Frameworks" +) + +add_custom_target(bundle_symlink ALL + WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} + COMMAND ${CMAKE_COMMAND} -E create_symlink ${MULTIPASS_GUI_PREFIX}/${MULTIPASS_GUI_BUNDLE_RELATIVE} "Multipass.app" +) diff --git a/src/client/gui/CMakeLists.txt.windows b/src/client/gui/CMakeLists.txt.windows new file mode 100644 index 0000000000..e359c0913c --- /dev/null +++ b/src/client/gui/CMakeLists.txt.windows @@ -0,0 +1,62 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +set_target_properties(dart_ffi PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON) +install(TARGETS dart_ffi DESTINATION bin/ COMPONENT multipass_gui) + +set(MULTIPASS_GUI_EXECUTABLE multipass.gui.exe) +set(MULTIPASS_GUI_TARGET windows) +set(MULTIPASS_GUI_PREFIX ${MULTIPASS_GUI_TARGET}/${MULTIPASS_GUI_ARCH}/runner/Release) +set(MULTIPASS_GUI_BUNDLE_RELATIVE "") +set(MULTIPASS_GUI_EXEC_PATH_RELATIVE_TO_BUNDLE "") + +set(MULTIPASS_GUI_BUILD_DIR ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +cmake_path(RELATIVE_PATH MULTIPASS_GUI_BUILD_DIR) + +if (MULTIPASS_GUI_BUILD_DIR STREQUAL "") + message(FATAL_ERROR "Build and source folders should be in the same drive") +endif() + +set(MULTIPASS_GUI_PATH ${MULTIPASS_GUI_BUILD_DIR}/${MULTIPASS_GUI_PREFIX}) +set(MULTIPASS_GUI_BUNDLE ${MULTIPASS_GUI_PATH}/${MULTIPASS_GUI_BUNDLE_RELATIVE}) +set(MULTIPASS_GUI_SOURCE_DIR ${CMAKE_SOURCE_DIR}/src/client/gui) +set(MULTIPASS_GUI_LINK_NAME multipass.gui) +set(MULTIPASS_GUI_EXECUTABLE_FULL_PATH ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${MULTIPASS_GUI_PREFIX}/${MULTIPASS_GUI_BUNDLE_RELATIVE}/${MULTIPASS_GUI_EXEC_PATH_RELATIVE_TO_BUNDLE}/${MULTIPASS_GUI_EXECUTABLE}) + +file(GLOB_RECURSE MULTIPASS_GUI_SOURCE_FILES ${MULTIPASS_GUI_SOURCE_DIR}/lib/*.dart) + +set(FLUTTER_BUILD_ARGS --release --suppress-analytics --verbose --build-name=${MULTIPASS_SEMANTIC_VERSION} --build-number=${MULTIPASS_BUILD_NUMBER}) + +add_custom_command(OUTPUT ${MULTIPASS_GUI_EXECUTABLE_FULL_PATH} + DEPENDS ${MULTIPASS_GUI_SOURCE_FILES} + WORKING_DIRECTORY ${MULTIPASS_GUI_SOURCE_DIR} + COMMAND ${CMAKE_COMMAND} -E make_directory lib/generated + COMMAND $ --plugin=protoc-gen-dart=${DART_PROTOC_PLUGIN} --dart_out=grpc:lib/generated -I ../../rpc ../../rpc/multipass.proto google/protobuf/timestamp.proto + COMMAND ${FLUTTER_EXECUTABLE} config --build-dir=${MULTIPASS_GUI_BUILD_DIR} + COMMAND ${FLUTTER_EXECUTABLE} build ${MULTIPASS_GUI_TARGET} ${FLUTTER_BUILD_ARGS} + COMMAND ${FLUTTER_EXECUTABLE} config --build-dir= +) + + +add_custom_target(${MULTIPASS_GUI_EXECUTABLE} ALL + DEPENDS ${MULTIPASS_GUI_EXECUTABLE_FULL_PATH} +) + +set(FLUTTER_INSTALL_BUNDLE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${MULTIPASS_GUI_PREFIX}/${MULTIPASS_GUI_BUNDLE_RELATIVE}/${MULTIPASS_GUI_EXEC_PATH_RELATIVE_TO_BUNDLE}/") + +install(DIRECTORY + ${FLUTTER_INSTALL_BUNDLE} + DESTINATION bin/ + COMPONENT multipass_gui +) diff --git a/src/client/gui/macos/Flutter/Flutter-Debug.xcconfig b/src/client/gui/macos/Flutter/Flutter-Debug.xcconfig index c2efd0b608..4b81f9b2d2 100644 --- a/src/client/gui/macos/Flutter/Flutter-Debug.xcconfig +++ b/src/client/gui/macos/Flutter/Flutter-Debug.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/src/client/gui/macos/Flutter/Flutter-Release.xcconfig b/src/client/gui/macos/Flutter/Flutter-Release.xcconfig index c2efd0b608..5caa9d1579 100644 --- a/src/client/gui/macos/Flutter/Flutter-Release.xcconfig +++ b/src/client/gui/macos/Flutter/Flutter-Release.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/src/client/gui/macos/Podfile b/src/client/gui/macos/Podfile new file mode 100644 index 0000000000..c795730db8 --- /dev/null +++ b/src/client/gui/macos/Podfile @@ -0,0 +1,43 @@ +platform :osx, '10.14' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/src/client/gui/macos/Podfile.lock b/src/client/gui/macos/Podfile.lock new file mode 100644 index 0000000000..881a7f805e --- /dev/null +++ b/src/client/gui/macos/Podfile.lock @@ -0,0 +1,41 @@ +PODS: + - FlutterMacOS (1.0.0) + - path_provider_foundation (0.0.1): + - Flutter + - FlutterMacOS + - screen_retriever (0.0.1): + - FlutterMacOS + - tray_menu (0.0.1): + - FlutterMacOS + - window_manager (0.2.0): + - FlutterMacOS + +DEPENDENCIES: + - FlutterMacOS (from `Flutter/ephemeral`) + - path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin`) + - screen_retriever (from `Flutter/ephemeral/.symlinks/plugins/screen_retriever/macos`) + - tray_menu (from `Flutter/ephemeral/.symlinks/plugins/tray_menu/macos`) + - window_manager (from `Flutter/ephemeral/.symlinks/plugins/window_manager/macos`) + +EXTERNAL SOURCES: + FlutterMacOS: + :path: Flutter/ephemeral + path_provider_foundation: + :path: Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin + screen_retriever: + :path: Flutter/ephemeral/.symlinks/plugins/screen_retriever/macos + tray_menu: + :path: Flutter/ephemeral/.symlinks/plugins/tray_menu/macos + window_manager: + :path: Flutter/ephemeral/.symlinks/plugins/window_manager/macos + +SPEC CHECKSUMS: + FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24 + path_provider_foundation: 29f094ae23ebbca9d3d0cec13889cd9060c0e943 + screen_retriever: 59634572a57080243dd1bf715e55b6c54f241a38 + tray_menu: 388c475404aa4fc1563a6ed002bef6677d467905 + window_manager: 3a1844359a6295ab1e47659b1a777e36773cd6e8 + +PODFILE CHECKSUM: 236401fc2c932af29a9fcf0e97baeeb2d750d367 + +COCOAPODS: 1.12.1 diff --git a/src/client/gui/macos/Runner.xcodeproj/project.pbxproj b/src/client/gui/macos/Runner.xcodeproj/project.pbxproj index 4a93ea0f2f..4ef5c31290 100644 --- a/src/client/gui/macos/Runner.xcodeproj/project.pbxproj +++ b/src/client/gui/macos/Runner.xcodeproj/project.pbxproj @@ -21,14 +21,24 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 6A0877FE1BA617DA77792597 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E83D45693C567AE838AE72DC /* Pods_RunnerTests.framework */; }; + D4C1D42C4D6EC1C408C90EA0 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9EE07778F0EABA0076B64FED /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 33CC10E52044A3C60003C045 /* Project object */; @@ -52,6 +62,9 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 308B3CEF5FE9598FFF3EED0E /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 33CC10ED2044A3C60003C045 /* Multipass.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Multipass.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -66,21 +79,59 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 5F3991AD67F1FB47DEAEA18A /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 8508A2C669BAF03F30193E2F /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 8A844B79F7E216878B8851B9 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; + 9EE07778F0EABA0076B64FED /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + CD39D165DC88BD3C86813530 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + E83ABCA4F66A63D043806FE7 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + E83D45693C567AE838AE72DC /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6A0877FE1BA617DA77792597 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 33CC10EA2044A3C60003C045 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + D4C1D42C4D6EC1C408C90EA0 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 0CFBBA13A1F423169E5F06BD /* Pods */ = { + isa = PBXGroup; + children = ( + 5F3991AD67F1FB47DEAEA18A /* Pods-Runner.debug.xcconfig */, + 308B3CEF5FE9598FFF3EED0E /* Pods-Runner.release.xcconfig */, + 8508A2C669BAF03F30193E2F /* Pods-Runner.profile.xcconfig */, + CD39D165DC88BD3C86813530 /* Pods-RunnerTests.debug.xcconfig */, + 8A844B79F7E216878B8851B9 /* Pods-RunnerTests.release.xcconfig */, + E83ABCA4F66A63D043806FE7 /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; 33BA886A226E78AF003329D5 /* Configs */ = { isa = PBXGroup; children = ( @@ -97,8 +148,10 @@ children = ( 33FAB671232836740065AC1E /* Runner */, 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, D73912EC22F37F3D000D13A0 /* Frameworks */, + 0CFBBA13A1F423169E5F06BD /* Pods */, ); sourceTree = ""; }; @@ -148,6 +201,8 @@ D73912EC22F37F3D000D13A0 /* Frameworks */ = { isa = PBXGroup; children = ( + 9EE07778F0EABA0076B64FED /* Pods_Runner.framework */, + E83D45693C567AE838AE72DC /* Pods_RunnerTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -155,15 +210,36 @@ /* End PBXGroup section */ /* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 8884889C1B3D0B986C964EAD /* [CP] Check Pods Manifest.lock */, + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; 33CC10EC2044A3C60003C045 /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( + A86C8DEDA8C985A6BE57FF66 /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, 33CC110E2044A8840003C045 /* Bundle Framework */, 3399D490228B24CF009A79C7 /* ShellScript */, + EA70CB5C0682FD9C53421EFF /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -185,6 +261,10 @@ LastUpgradeCheck = 1300; ORGANIZATIONNAME = ""; TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; 33CC10EC2044A3C60003C045 = { CreatedOnToolsVersion = 9.2; LastSwiftMigration = 1100; @@ -215,12 +295,20 @@ projectRoot = ""; targets = ( 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, 33CC111A2044C6BA0003C045 /* Flutter Assemble */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 33CC10EB2044A3C60003C045 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -271,9 +359,78 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; + 8884889C1B3D0B986C964EAD /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + A86C8DEDA8C985A6BE57FF66 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + EA70CB5C0682FD9C53421EFF /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 33CC10E92044A3C60003C045 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -287,6 +444,11 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; @@ -307,6 +469,51 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = CD39D165DC88BD3C86813530 /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.canonical.multipassGui.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Multipass.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/multipass_gui"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 8A844B79F7E216878B8851B9 /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.canonical.multipassGui.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Multipass.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/multipass_gui"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E83ABCA4F66A63D043806FE7 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.canonical.multipassGui.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Multipass.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/multipass_gui"; + }; + name = Profile; + }; 338D0CE9231458BD00FA5F75 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; @@ -540,6 +747,16 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/src/client/gui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/src/client/gui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 3feedfd02e..4e77505829 100644 --- a/src/client/gui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/src/client/gui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -37,6 +37,17 @@ + + + + + + diff --git a/src/client/gui/macos/Runner/MainFlutterWindow.swift b/src/client/gui/macos/Runner/MainFlutterWindow.swift index 2722837ec9..3cc05eb234 100644 --- a/src/client/gui/macos/Runner/MainFlutterWindow.swift +++ b/src/client/gui/macos/Runner/MainFlutterWindow.swift @@ -3,7 +3,7 @@ import FlutterMacOS class MainFlutterWindow: NSWindow { override func awakeFromNib() { - let flutterViewController = FlutterViewController.init() + let flutterViewController = FlutterViewController() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) diff --git a/src/client/gui/macos/RunnerTests/RunnerTests.swift b/src/client/gui/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000000..5418c9f539 --- /dev/null +++ b/src/client/gui/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import FlutterMacOS +import Cocoa +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/src/client/gui/resources/gui.rc.in b/src/client/gui/resources/gui.rc.in new file mode 100644 index 0000000000..f9bf09816f --- /dev/null +++ b/src/client/gui/resources/gui.rc.in @@ -0,0 +1,25 @@ +icon ICON "../data/icon.ico" + +1 VERSIONINFO +// TODO: Fill in FILEVERSION with a real version +FILEVERSION 0,0,0,0 +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "CompanyName", "Canonical Ltd." + VALUE "FileDescription", "Multipass" + VALUE "FileVersion", "@MULTIPASS_VERSION@" + VALUE "InternalName", "" + VALUE "OriginalFilename", "" + VALUE "ProductName", "Multipass" + VALUE "ProductVersion", "@MULTIPASS_VERSION@" + END + END + + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 0x04B0 + END +END diff --git a/src/daemon/CMakeLists.txt b/src/daemon/CMakeLists.txt index 38cb4f1791..463fe2732e 100644 --- a/src/daemon/CMakeLists.txt +++ b/src/daemon/CMakeLists.txt @@ -61,12 +61,67 @@ target_link_libraries(delayed_shutdown Qt6::Core ) -add_executable(multipassd daemon_main.cpp) +if(MSVC) + add_executable(multipassd daemon_main_win.cpp) + qt6_disable_unicode_defines(multipassd) +else() + add_executable(multipassd daemon_main.cpp) +endif() target_link_libraries(multipassd fmt::fmt-header-only daemon) +# this TLS plugin is common to all platforms, so we can retrieve it +find_package(Qt6QTlsBackendCertOnlyPlugin PATHS ${Qt6Network_DIR}) +# the IMPORTED_LOCATION is defined for RELEASE on all platforms, so we use that to get the path of the shared lib itself +get_target_property(QT_TLS_PLUGIN_PATH Qt6::QTlsBackendCertOnlyPlugin IMPORTED_LOCATION_RELEASE) +# the path of the root plugins dir is two dirs up from the path of the shared lib we just retrieved +cmake_path(GET QT_TLS_PLUGIN_PATH PARENT_PATH QT_TLS_PLUGIN_DIR) +cmake_path(GET QT_TLS_PLUGIN_DIR PARENT_PATH QT_PLUGINS_DIR) +# this way of retrieving the Qt plugins directory is kind of a hack +# this information was extracted from Qt's cmake files, but it has no stability guarantee + +if (NOT IS_DIRECTORY ${QT_PLUGINS_DIR}/tls) + message(FATAL_ERROR "Failed to retrieve Qt 'tls' plugin directory") +endif() + +if (NOT IS_DIRECTORY ${QT_PLUGINS_DIR}/networkinformation) + message(FATAL_ERROR "Failed to retrieve Qt 'networkinformation' plugin directory") +endif() + +if(APPLE) + set_target_properties( multipassd PROPERTIES INSTALL_RPATH "@executable_path/../lib" ) + + # Copy any framework depenencies into the install directory for packaging + install(CODE " + include(${CMAKE_SOURCE_DIR}/packaging/FrameworkUtilities.cmake) + install_frameworks(\"${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/multipassd\" \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/lib\") + " COMPONENT multipassd) + + file(GLOB QT_TLS_PLUGIN_FILES "${QT_PLUGINS_DIR}/tls/*.dylib") + install(FILES ${QT_TLS_PLUGIN_FILES} DESTINATION plugins/tls COMPONENT multipassd) + + file(GLOB QT_NETWORKINFORMATION_PLUGIN_FILES "${QT_PLUGINS_DIR}/networkinformation/*.dylib") + install(FILES ${QT_NETWORKINFORMATION_PLUGIN_FILES} DESTINATION plugins/networkinformation COMPONENT multipassd) +endif(APPLE) + install(TARGETS multipassd DESTINATION bin COMPONENT multipassd) + +if(MSVC) + install(CODE " + include(BundleUtilities) + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/bin/multipassd.exe\" \"\" \"${CMAKE_RUNTIME_OUTPUT_DIRECTORY}\") + " COMPONENT multipassd) + + file(GLOB SSL_DLLS "${OPENSSL_INCLUDE_DIR}/../*.dll") + install(FILES ${SSL_DLLS} DESTINATION bin COMPONENT multipassd) + + file(GLOB QT_TLS_PLUGIN_FILES "${QT_PLUGINS_DIR}/tls/*.dll") + install(FILES ${QT_TLS_PLUGIN_FILES} DESTINATION bin/tls COMPONENT multipassd) + + file(GLOB QT_NETWORKINFORMATION_PLUGIN_FILES "${QT_PLUGINS_DIR}/networkinformation/*.dll") + install(FILES ${QT_NETWORKINFORMATION_PLUGIN_FILES} DESTINATION bin/networkinformation COMPONENT multipassd) +endif() diff --git a/src/daemon/common_image_host.cpp b/src/daemon/common_image_host.cpp index 630116265f..e00ffbb5e0 100644 --- a/src/daemon/common_image_host.cpp +++ b/src/daemon/common_image_host.cpp @@ -22,9 +22,6 @@ #include #include -#include -#include - namespace mp = multipass; namespace mpl = multipass::logging; @@ -58,27 +55,3 @@ void mp::CommonVMImageHost::on_manifest_update_failure(const std::string& detail { mpl::log(mpl::Level::warning, category, fmt::format("Could not update manifest: {}", details)); } - -void mp::CommonVMImageHost::check_remote_is_supported(const std::string& remote_name) const -{ - if (!MP_PLATFORM.is_remote_supported(remote_name)) - throw mp::UnsupportedRemoteException( - fmt::format("Remote \'{}\' is not a supported remote for this platform. Please use " - "`multipass find` for supported remotes and images.", - remote_name)); -} - -void mp::CommonVMImageHost::check_alias_is_supported(const std::string& alias, const std::string& remote_name) const -{ - if (!MP_PLATFORM.is_alias_supported(alias, remote_name)) - throw mp::UnsupportedAliasException(fmt::format( - "\'{}\' is not a supported alias. Please use `multipass find` for supported image aliases.", alias)); -} - -bool mp::CommonVMImageHost::alias_verifies_image_is_supported(const QStringList& aliases, - const std::string& remote_name) const -{ - return aliases.empty() || std::any_of(aliases.cbegin(), aliases.cend(), [&remote_name](const auto& alias) { - return MP_PLATFORM.is_alias_supported(alias.toStdString(), remote_name); - }); -} diff --git a/src/daemon/common_image_host.h b/src/daemon/common_image_host.h index 8bd088319f..174aa88d1d 100644 --- a/src/daemon/common_image_host.h +++ b/src/daemon/common_image_host.h @@ -38,9 +38,6 @@ class CommonVMImageHost : public VMImageHost protected: void on_manifest_update_failure(const std::string& details); void on_manifest_empty(const std::string& details); - void check_remote_is_supported(const std::string& remote_name) const; - void check_alias_is_supported(const std::string& alias, const std::string& remote_name) const; - bool alias_verifies_image_is_supported(const QStringList& aliases, const std::string& remote_name) const; virtual void for_each_entry_do_impl(const Action& action) = 0; virtual VMImageInfo info_for_full_hash_impl(const std::string& full_hash) = 0; diff --git a/src/daemon/custom_image_host.cpp b/src/daemon/custom_image_host.cpp index 844fd9e1d6..5b4c8c7f37 100644 --- a/src/daemon/custom_image_host.cpp +++ b/src/daemon/custom_image_host.cpp @@ -17,16 +17,13 @@ #include "custom_image_host.h" +#include +#include #include #include #include #include -#include -#include - -#include - #include #include @@ -171,8 +168,6 @@ mp::CustomVMImageHost::CustomVMImageHost(const QString& arch, URLDownloader* dow std::optional mp::CustomVMImageHost::info_for(const Query& query) { - check_alias_is_supported(query.release, query.remote_name); - auto custom_manifest = manifest_from(query.remote_name); auto it = custom_manifest->image_records.find(query.release); @@ -204,12 +199,7 @@ std::vector mp::CustomVMImageHost::all_images_for(const std::st { std::vector images; auto custom_manifest = manifest_from(remote_name); - - auto pred = [this, &remote_name](const auto& product) { - return alias_verifies_image_is_supported(product.aliases, remote_name); - }; - - std::copy_if(custom_manifest->products.begin(), custom_manifest->products.end(), std::back_inserter(images), pred); + std::copy(custom_manifest->products.begin(), custom_manifest->products.end(), std::back_inserter(images)); return images; } @@ -220,8 +210,7 @@ void mp::CustomVMImageHost::for_each_entry_do_impl(const Action& action) { for (const auto& info : manifest.second->products) { - if (alias_verifies_image_is_supported(info.aliases, manifest.first)) - action(manifest.first, info); + action(manifest.first, info); } } } @@ -237,7 +226,6 @@ void mp::CustomVMImageHost::fetch_manifests(const bool is_force_update_from_netw { try { - check_remote_is_supported(spec.first); std::unique_ptr custom_manifest = full_image_info_for(spec.second, url_downloader, is_force_update_from_network); custom_image_info.emplace(spec.first, std::move(custom_manifest)); @@ -246,10 +234,6 @@ void mp::CustomVMImageHost::fetch_manifests(const bool is_force_update_from_netw { throw e; } - catch (const mp::UnsupportedRemoteException&) - { - continue; - } } } @@ -260,8 +244,6 @@ void mp::CustomVMImageHost::clear() mp::CustomManifest* mp::CustomVMImageHost::manifest_from(const std::string& remote_name) { - check_remote_is_supported(remote_name); - auto it = custom_image_info.find(remote_name); if (it == custom_image_info.end()) throw std::runtime_error(fmt::format("Remote \"{}\" is unknown or unreachable.", remote_name)); diff --git a/src/daemon/daemon.cpp b/src/daemon/daemon.cpp index caae590a20..16183fd200 100644 --- a/src/daemon/daemon.cpp +++ b/src/daemon/daemon.cpp @@ -343,7 +343,6 @@ auto fetch_image_for(const std::string& name, mp::VirtualMachineFactory& factory query, stub_prepare, stub_progress, - false, std::nullopt, factory.get_instance_directory(name)); } @@ -3132,7 +3131,6 @@ void mp::Daemon::create_vm(const CreateRequest* request, ClientLaunchData client_launch_data; - bool launch_from_blueprint{true}; try { auto image = request->image(); @@ -3184,7 +3182,6 @@ void mp::Daemon::create_vm(const CreateRequest* request, catch (const std::out_of_range&) { // Blueprint not found, move on - launch_from_blueprint = false; query = query_from(request, name); vm_desc.mem_size = checked_args.mem_size; } @@ -3214,7 +3211,6 @@ void mp::Daemon::create_vm(const CreateRequest* request, query, prepare_action, progress_monitor, - launch_from_blueprint, checksum, config->factory->get_instance_directory(name)); diff --git a/src/daemon/daemon_config.cpp b/src/daemon/daemon_config.cpp index 79e06f0b7d..164b74bdbc 100644 --- a/src/daemon/daemon_config.cpp +++ b/src/daemon/daemon_config.cpp @@ -90,6 +90,26 @@ std::unique_ptr discover_http_proxy() return proxy_ptr; } + +bool admits_snapcraft_image(const mp::VMImageInfo& info) +{ + static constexpr auto supported_snapcraft_aliases = { + "core18", + "18.04", + "core20", + "20.04", + "core22", + "22.04", + "core24", + "24.04", + "devel", + }; + + const auto& aliases = info.aliases; + return aliases.empty() || std::any_of(supported_snapcraft_aliases.begin(), + supported_snapcraft_aliases.end(), + [&aliases](const auto& alias) { return aliases.contains(alias); }); +} } // namespace mp::DaemonConfig::~DaemonConfig() @@ -142,12 +162,19 @@ std::unique_ptr mp::DaemonConfigBuilder::build() std::make_unique(QSysInfo::currentCpuArchitecture(), url_downloader.get())); image_hosts.push_back(std::make_unique( std::vector>{ - {mp::release_remote, UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", "releases/", - std::make_optional(mp::mirror_key)}}, - {mp::daily_remote, UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", "daily/", - std::make_optional(mp::mirror_key)}}, - {mp::snapcraft_remote, UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", "buildd/daily/", - std::make_optional(mp::mirror_key)}}, + {mp::release_remote, + UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", + "releases/", + std::make_optional(mp::mirror_key)}}, + {mp::daily_remote, + UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", + "daily/", + std::make_optional(mp::mirror_key)}}, + {mp::snapcraft_remote, + UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", + "buildd/daily/", + &admits_snapcraft_image, + std::make_optional(mp::mirror_key)}}, {mp::appliance_remote, UbuntuVMImageRemote{"https://cdimage.ubuntu.com/", "ubuntu-core/appliances/"}}}, url_downloader.get())); } @@ -179,8 +206,7 @@ std::unique_ptr mp::DaemonConfigBuilder::build() if (blueprint_provider == nullptr) { - auto blueprint_provider_url = MP_PLATFORM.get_blueprints_url_override(); - + auto blueprint_provider_url = qEnvironmentVariable(blueprints_url_env_var); if (!blueprint_provider_url.isEmpty()) blueprint_provider = std::make_unique( QUrl(blueprint_provider_url), url_downloader.get(), cache_directory, manifest_ttl); diff --git a/src/daemon/daemon_main_win.cpp b/src/daemon/daemon_main_win.cpp new file mode 100644 index 0000000000..cbc1e8ad82 --- /dev/null +++ b/src/daemon/daemon_main_win.cpp @@ -0,0 +1,235 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "cli.h" +#include "daemon.h" +#include "daemon_config.h" +#include "daemon_init_settings.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; + +#define BUFF_SZ 32767 + +namespace +{ +constexpr auto service_name = "Multipass"; +std::vector service_argv; + +BOOL windows_console_ctrl_handler(DWORD dwCtrlType) +{ + switch (dwCtrlType) + { + case CTRL_C_EVENT: + case CTRL_CLOSE_EVENT: + { + QCoreApplication::quit(); + return TRUE; + } + default: + return FALSE; + } +} + +enum class RegisterConsoleHandler +{ + no, + yes +}; + +auto make_status() +{ + SERVICE_STATUS status{}; + status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + status.dwCurrentState = SERVICE_START_PENDING; + status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP; + status.dwWin32ExitCode = NO_ERROR; + status.dwServiceSpecificExitCode = 0; + status.dwWaitHint = 0; + return status; +} + +SERVICE_STATUS_HANDLE service_handle{nullptr}; +void control_handler(DWORD control) +{ + switch (control) + { + case SERVICE_CONTROL_STOP: + case SERVICE_CONTROL_SHUTDOWN: + { + if (service_handle != nullptr) + { + auto status = make_status(); + status.dwCurrentState = SERVICE_STOP_PENDING; + SetServiceStatus(service_handle, &status); + } + QCoreApplication::quit(); + } + } +} + +void create_client_cert_if_necessary() +{ + TCHAR infoBuf[BUFF_SZ]; + GetSystemDirectory(infoBuf, BUFF_SZ); + auto storage_path = MP_PLATFORM.multipass_storage_location(); + + const QString multipassd_data_dir_path{ + storage_path.isEmpty() ? QString("%1\\config\\systemprofile\\AppData\\Roaming\\multipassd\\").arg(infoBuf) + : QString("%1\\data").arg(storage_path)}; + + mp::ClientCertStore cert_store{multipassd_data_dir_path}; + + if (cert_store.empty()) + { + auto data_location{MP_STDPATHS.writableLocation(mp::StandardPaths::GenericDataLocation)}; + auto client_cert_dir_path{MP_UTILS.make_dir(data_location + mp::common_client_cert_dir)}; + mp::SSLCertProvider cert_provider{client_cert_dir_path}; + + cert_store.add_cert(cert_provider.PEM_certificate()); + } +} + +int daemon_main(int argc, char* argv[], RegisterConsoleHandler register_console) +{ + QCoreApplication app(argc, argv); + QCoreApplication::setApplicationName(mp::daemon_name); + QCoreApplication::setApplicationVersion(mp::version_string); + + if (register_console == RegisterConsoleHandler::yes) + SetConsoleCtrlHandler(windows_console_ctrl_handler, TRUE); + + mp::daemon::register_global_settings_handlers(); + + auto builder = mp::cli::parse(app); + auto config = builder.build(); + + mp::daemon::monitor_and_quit_on_settings_change(); + mp::Daemon daemon(std::move(config)); + QObject::connect(&app, + &QCoreApplication::aboutToQuit, + &daemon, + &mp::Daemon::shutdown_grpc_server, + Qt::DirectConnection); + + mpl::log(mpl::Level::info, "daemon", fmt::format("Daemon arguments: {}", app.arguments().join(" "))); + auto ret = QCoreApplication::exec(); + mpl::log(mpl::Level::info, "daemon", "Goodbye!"); + return ret; +} + +void service_main(DWORD argc, char* argv[]) // clang-format off +try // clang-format on +{ + auto logger = mp::platform::make_logger(mpl::Level::info); + auto daemon_argv(service_argv); + daemon_argv.insert(daemon_argv.end(), argv + 1, argv + argc); + + logger->log(mpl::Level::info, "service_main", "registering control handler"); + + service_handle = RegisterServiceCtrlHandler(service_name, control_handler); + if (service_handle == nullptr) + { + logger->log(mpl::Level::info, "service_main", "failed to register control handler"); + return; + } + + auto status = make_status(); + SetServiceStatus(service_handle, &status); + status.dwCurrentState = SERVICE_RUNNING; + SetServiceStatus(service_handle, &status); + + logger->log(mpl::Level::info, "service_main", "service is running"); + + auto exit_code = daemon_main(daemon_argv.size(), daemon_argv.data(), RegisterConsoleHandler::no); + + status.dwCurrentState = SERVICE_STOPPED; + status.dwWin32ExitCode = exit_code; + SetServiceStatus(service_handle, &status); + + logger->log(mpl::Level::info, "service_main", "service stopped"); +} +catch (...) +{ + if (service_handle != nullptr) + { + auto status = make_status(); + status.dwCurrentState = SERVICE_STOPPED; + SetServiceStatus(service_handle, &status); + } +} +} // namespace + +int main(int argc, char* argv[]) // clang-format off +try // clang-format on +{ + service_argv.assign(argv, argv + argc); + + auto logger = mp::platform::make_logger(mpl::Level::info); + std::ostringstream arguments; + std::copy(service_argv.begin(), service_argv.end(), std::ostream_iterator(arguments, " ")); + logger->log(mpl::Level::info, "main", fmt::format("Starting Multipass {}", mp::version_string)); + logger->log(mpl::Level::info, "main", fmt::format("Service arguments: {}", arguments.str())); + + if (argc > 1) + { + std::string cmd{argv[1]}; + if (cmd == "/install") + { + QCoreApplication app(argc, argv); + QCoreApplication::setApplicationName(mp::daemon_name); + QCoreApplication::setApplicationVersion(mp::version_string); + create_client_cert_if_necessary(); + return EXIT_SUCCESS; + } + + if (cmd == "/svc") + { + logger->log(mpl::Level::info, "main", "calling service ctrl dispatcher"); + std::array table{{{const_cast(""), service_main}, {nullptr, nullptr}}}; + // remove "/svc" from the list of arguments + service_argv.erase(service_argv.begin() + 1); + return StartServiceCtrlDispatcher(table.data()); + } + } + return daemon_main(argc, argv, RegisterConsoleHandler::yes); +} +catch (const std::exception& e) +{ + fmt::print(stderr, "error: {}\n", e.what()); + return EXIT_FAILURE; +} diff --git a/src/daemon/default_vm_image_vault.cpp b/src/daemon/default_vm_image_vault.cpp index fbec7a9e8f..9e72db9ba3 100644 --- a/src/daemon/default_vm_image_vault.cpp +++ b/src/daemon/default_vm_image_vault.cpp @@ -260,7 +260,6 @@ mp::VMImage mp::DefaultVMImageVault::fetch_image(const FetchType& fetch_type, const Query& query, const PrepareAction& prepare, const ProgressMonitor& monitor, - const bool unlock, const std::optional& checksum, const mp::Path& save_dir) { @@ -275,9 +274,6 @@ mp::VMImage mp::DefaultVMImageVault::fetch_image(const FetchType& fetch_type, } } - if (!unlock && query.query_type != Query::Type::Alias && !MP_PLATFORM.is_image_url_supported()) - throw std::runtime_error(fmt::format("http and file based images are not supported")); - if (query.query_type == Query::Type::LocalFile) { QUrl image_url(QString::fromStdString(query.release)); @@ -546,7 +542,6 @@ void mp::DefaultVMImageVault::update_images(const FetchType& fetch_type, const P record.query, prepare, monitor, - false, std::nullopt, QFileInfo{record.image.image_path}.absolutePath()); diff --git a/src/daemon/default_vm_image_vault.h b/src/daemon/default_vm_image_vault.h index 37db7c653d..abd4e6d58d 100644 --- a/src/daemon/default_vm_image_vault.h +++ b/src/daemon/default_vm_image_vault.h @@ -56,7 +56,6 @@ class DefaultVMImageVault final : public BaseVMImageVault const Query& query, const PrepareAction& prepare, const ProgressMonitor& monitor, - const bool unlock, const std::optional& checksum, const Path& save_dir) override; void remove(const std::string& name) override; diff --git a/src/daemon/ubuntu_image_host.cpp b/src/daemon/ubuntu_image_host.cpp index 276a8fa244..f6a379f566 100644 --- a/src/daemon/ubuntu_image_host.cpp +++ b/src/daemon/ubuntu_image_host.cpp @@ -18,6 +18,9 @@ #include "ubuntu_image_host.h" #include +#include +#include +#include #include #include #include @@ -25,11 +28,6 @@ #include #include -#include -#include -#include -#include - #include #include #include @@ -105,7 +103,6 @@ std::optional mp::UbuntuVMImageHost::info_for(const Query& quer std::vector> mp::UbuntuVMImageHost::all_info_for(const Query& query) { auto key = key_from(query.release); - check_alias_is_supported(key.toStdString(), query.remote_name); std::vector remotes_to_search; @@ -120,26 +117,16 @@ std::vector> mp::UbuntuVMImageHost::all_ std::vector> images; - mp::SimpleStreamsManifest* manifest; - for (const auto& remote_name : remotes_to_search) { - try - { - manifest = manifest_from(remote_name); - } - catch (const mp::UnsupportedRemoteException&) + auto* manifest = manifest_from(remote_name); + const auto& remote = get_remote(remote_name); + + if (const auto* info = match_alias(key, *manifest); info) { - if (query.remote_name.empty()) + if (!remote.admits_image(*info)) continue; - throw; - } - - const auto* info = match_alias(key, *manifest); - - if (info) - { if (!info->supported && !query.allow_unsupported) throw mp::UnsupportedImageException(query.release); @@ -153,7 +140,8 @@ std::vector> mp::UbuntuVMImageHost::all_ for (const auto& entry : manifest->products) { - if (entry.id.startsWith(key) && (entry.supported || query.allow_unsupported) && + if (entry.id.startsWith(key) && remote.admits_image(entry) && + (entry.supported || query.allow_unsupported) && found_hashes.find(entry.id.toStdString()) == found_hashes.end()) { images.push_back(std::make_pair( @@ -194,7 +182,7 @@ std::vector mp::UbuntuVMImageHost::all_images_for(const std::st for (const auto& entry : manifest->products) { - if ((entry.supported || allow_unsupported) && alias_verifies_image_is_supported(entry.aliases, remote_name)) + if ((entry.supported || allow_unsupported) && get_remote(remote_name).admits_image(entry)) { images.push_back(with_location_fully_resolved(QString::fromStdString(remote_url_from(remote_name)), entry)); } @@ -208,14 +196,14 @@ std::vector mp::UbuntuVMImageHost::all_images_for(const std::st void mp::UbuntuVMImageHost::for_each_entry_do_impl(const Action& action) { - for (const auto& manifest : manifests) + for (const auto& [remote_name, manifest] : manifests) { - for (const auto& product : manifest.second->products) + for (const auto& product : manifest->products) { - if (alias_verifies_image_is_supported(product.aliases, manifest.first)) + if (get_remote(remote_name).admits_image(product)) { - action(manifest.first, - with_location_fully_resolved(QString::fromStdString(remote_url_from(manifest.first)), product)); + action(remote_name, + with_location_fully_resolved(QString::fromStdString(remote_url_from(remote_name)), product)); } } } @@ -241,7 +229,6 @@ void mp::UbuntuVMImageHost::fetch_manifests(const bool is_force_update_from_netw const auto& [remote_name, remote_info] = remote_pair; try { - check_remote_is_supported(remote_name); auto official_site = remote_info.get_official_url(); auto manifest_bytes_from_official = download_manifest(official_site, url_downloader, is_force_update_from_network); @@ -271,9 +258,6 @@ void mp::UbuntuVMImageHost::fetch_manifests(const bool is_force_update_from_netw { throw e; } - catch (const mp::UnsupportedRemoteException&) - { - } return {}; }; @@ -290,8 +274,6 @@ void mp::UbuntuVMImageHost::clear() mp::SimpleStreamsManifest* mp::UbuntuVMImageHost::manifest_from(const std::string& remote) { - check_remote_is_supported(remote); - const auto it = std::find_if(manifests.cbegin(), manifests.cend(), [&remote](const std::pair>& element) { @@ -317,27 +299,46 @@ const mp::VMImageInfo* mp::UbuntuVMImageHost::match_alias(const QString& key, return nullptr; } - -std::string mp::UbuntuVMImageHost::remote_url_from(const std::string& remote_name) +const mp::UbuntuVMImageRemote& mp::UbuntuVMImageHost::get_remote(const std::string& remote_name) const { - std::string url; - auto it = std::find_if(remotes.cbegin(), remotes.cend(), [&remote_name](const std::pair& element) { return element.first == remote_name; }); - if (it != remotes.cend()) + if (it == remotes.cend()) + throw std::out_of_range{fmt::format("Unknown remote \"{}\"", remote_name)}; + + return it->second; +} + +std::string mp::UbuntuVMImageHost::remote_url_from(const std::string& remote_name) +{ + try { - url = it->second.get_url().toStdString(); + return get_remote(remote_name).get_url().toStdString(); + } + catch (std::out_of_range&) + { + return {}; } - - return url; } -mp::UbuntuVMImageRemote::UbuntuVMImageRemote(std::string official_host, std::string uri, +mp::UbuntuVMImageRemote::UbuntuVMImageRemote(std::string official_host, + std::string uri, std::optional mirror_key) - : official_host(std::move(official_host)), uri(std::move(uri)), mirror_key(std::move(mirror_key)) + : UbuntuVMImageRemote(std::move(official_host), std::move(uri), &default_image_admitter, std::move(mirror_key)) +{ +} + +multipass::UbuntuVMImageRemote::UbuntuVMImageRemote(std::string official_host, + std::string uri, + std::function custom_image_admitter, + std::optional mirror_key) + : official_host(std::move(official_host)), + uri(std::move(uri)), + image_admitter{custom_image_admitter}, + mirror_key(std::move(mirror_key)) { } @@ -368,3 +369,13 @@ const std::optional mp::UbuntuVMImageRemote::get_mirror_url() const return std::nullopt; } + +bool multipass::UbuntuVMImageRemote::admits_image(const VMImageInfo& info) const +{ + return image_admitter(info); +} + +bool multipass::UbuntuVMImageRemote::default_image_admitter(const VMImageInfo&) +{ + return true; +} diff --git a/src/daemon/ubuntu_image_host.h b/src/daemon/ubuntu_image_host.h index d021dc9735..3377eeb8f3 100644 --- a/src/daemon/ubuntu_image_host.h +++ b/src/daemon/ubuntu_image_host.h @@ -54,24 +54,33 @@ class UbuntuVMImageHost final : public CommonVMImageHost void clear() override; SimpleStreamsManifest* manifest_from(const std::string& remote); const VMImageInfo* match_alias(const QString& key, const SimpleStreamsManifest& manifest) const; + const UbuntuVMImageRemote& get_remote(const std::string& remote_name) const; + std::string remote_url_from(const std::string& remote_name); std::vector>> manifests; URLDownloader* const url_downloader; std::vector> remotes; - std::string remote_url_from(const std::string& remote_name); QString index_path; }; class UbuntuVMImageRemote { public: UbuntuVMImageRemote(std::string official_host, std::string uri, std::optional mirror_key = std::nullopt); + UbuntuVMImageRemote(std::string official_host, + std::string uri, + std::function custom_image_admitter, + std::optional mirror_key = std::nullopt); const QString get_url() const; const QString get_official_url() const; const std::optional get_mirror_url() const; + bool admits_image(const VMImageInfo& info) const; private: + static bool default_image_admitter(const VMImageInfo&); + const std::string official_host; const std::string uri; + const std::function image_admitter; const std::optional mirror_key; }; } // namespace multipass diff --git a/src/iso/cloud_init_iso.cpp b/src/iso/cloud_init_iso.cpp index 69eb7aaf62..3d40431a3d 100644 --- a/src/iso/cloud_init_iso.cpp +++ b/src/iso/cloud_init_iso.cpp @@ -26,6 +26,7 @@ #include #include +#include namespace mp = multipass; namespace mpu = multipass::utils; diff --git a/src/platform/CMakeLists.txt b/src/platform/CMakeLists.txt index 0cbfa979a3..445f933fa7 100644 --- a/src/platform/CMakeLists.txt +++ b/src/platform/CMakeLists.txt @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . - function(add_target TARGET_NAME) if(LINUX) add_library(${TARGET_NAME} STATIC @@ -21,6 +20,23 @@ function(add_target TARGET_NAME) target_link_libraries(${TARGET_NAME} logger_linux) + elseif(MSVC) + add_library(${TARGET_NAME} STATIC + platform_proprietary.cpp + platform_win.cpp) + qt6_disable_unicode_defines(${TARGET_NAME}) + target_link_libraries(${TARGET_NAME} + jsoncpp_static + shared_win + scope_guard + wineventlogger) + elseif(APPLE) + add_library(${TARGET_NAME} STATIC + platform_osx.cpp + platform_proprietary.cpp + platform_unix.cpp) + target_link_libraries(${TARGET_NAME} + shared_macos) endif() foreach(BACKEND IN LISTS MULTIPASS_BACKENDS) diff --git a/src/platform/backends/hyperv/CMakeLists.txt b/src/platform/backends/hyperv/CMakeLists.txt new file mode 100644 index 0000000000..c28ff71685 --- /dev/null +++ b/src/platform/backends/hyperv/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . +# + +add_library(hyperv_backend STATIC + hyperv_snapshot.cpp + hyperv_virtual_machine.cpp + hyperv_virtual_machine_factory.cpp + ${CMAKE_SOURCE_DIR}/include/multipass/process/basic_process.h + ${CMAKE_SOURCE_DIR}/include/multipass/process/process.h) + +target_link_libraries(hyperv_backend + Qt6::Core + fmt::fmt-header-only + ip_address + logger + process + ssh + utils + yaml) diff --git a/src/platform/backends/hyperv/hyperv_snapshot.cpp b/src/platform/backends/hyperv/hyperv_snapshot.cpp new file mode 100644 index 0000000000..68edbd6c72 --- /dev/null +++ b/src/platform/backends/hyperv/hyperv_snapshot.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "hyperv_snapshot.h" +#include "hyperv_virtual_machine.h" + +#include + +#include // TODO@snapshots drop +#include +#include + +#include + +namespace mp = multipass; +namespace mpl = mp::logging; + +namespace +{ +QString quoted(const QString& s) +{ + return '"' + s + '"'; +} + +bool snapshot_exists(mp::PowerShell& ps, const QString& vm_name, const QString& id) +{ + static const auto expected_error = QStringLiteral("ObjectNotFound"); + + QString output_err; + if (ps.run({"Get-VMCheckpoint", "-VMName", vm_name, "-Name", id}, nullptr, &output_err)) + return true; + + if (!output_err.contains(expected_error)) + { + mpl::log(mpl::Level::warning, + vm_name.toStdString(), + fmt::format("Get-VMCheckpoint failed with unexpected output: {}", output_err)); + throw std::runtime_error{"Failure while looking for snapshot name"}; + } + + return false; // we're good: the command failed with the expected error +} + +void require_unique_id(mp::PowerShell& ps, const QString& vm_name, const QString& id) +{ + if (snapshot_exists(ps, vm_name, id)) + throw std::runtime_error{fmt::format("A snapshot with ID {} already exists for {} in Hyper-V", id, vm_name)}; +} +} // namespace + +mp::HyperVSnapshot::HyperVSnapshot(const std::string& name, + const std::string& comment, + const std::string& cloud_init_instance_id, + const VMSpecs& specs, + std::shared_ptr parent, + const QString& vm_name, + HyperVVirtualMachine& vm, + PowerShell& power_shell) + : BaseSnapshot{name, comment, cloud_init_instance_id, std::move(parent), specs, vm}, + quoted_id{quoted(get_id())}, + vm_name{vm_name}, + power_shell{power_shell} +{ +} + +mp::HyperVSnapshot::HyperVSnapshot(const QString& filename, + HyperVVirtualMachine& vm, + const VirtualMachineDescription& desc, + PowerShell& power_shell) + : BaseSnapshot{filename, vm, desc}, + quoted_id{quoted(get_id())}, + vm_name{QString::fromStdString(desc.vm_name)}, + power_shell{power_shell} +{ +} + +void mp::HyperVSnapshot::capture_impl() +{ + require_unique_id(power_shell, vm_name, quoted_id); + power_shell.easy_run({"Checkpoint-VM", "-Name", vm_name, "-SnapshotName", quoted_id}, "Could not create snapshot"); +} + +void mp::HyperVSnapshot::erase_impl() +{ + if (snapshot_exists(power_shell, vm_name, quoted_id)) + power_shell.easy_run({"Remove-VMCheckpoint", "-VMName", vm_name, "-Name", quoted_id, "-Confirm:$false"}, + "Could not delete snapshot"); + else + mpl::log(mpl::Level::warning, + vm_name.toStdString(), + fmt::format("Could not find underlying Hyper-V snapshot for \"{}\". Ignoring...", get_name())); +} + +void mp::HyperVSnapshot::apply_impl() +{ + power_shell.easy_run({"Restore-VMCheckpoint", "-VMName", vm_name, "-Name", quoted_id, "-Confirm:$false"}, + "Could not apply snapshot"); +} diff --git a/src/platform/backends/hyperv/hyperv_snapshot.h b/src/platform/backends/hyperv/hyperv_snapshot.h new file mode 100644 index 0000000000..6172f0315e --- /dev/null +++ b/src/platform/backends/hyperv/hyperv_snapshot.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_HYPERVSNAPSHOT_H +#define MULTIPASS_HYPERVSNAPSHOT_H + +#include + +#include + +namespace multipass +{ +class HyperVVirtualMachine; +class PowerShell; + +class HyperVSnapshot : public BaseSnapshot +{ +public: + HyperVSnapshot(const std::string& name, + const std::string& comment, + const std::string& cloud_init_instance_id, + const VMSpecs& specs, + std::shared_ptr parent, + const QString& vm_name, + HyperVVirtualMachine& vm, + PowerShell& power_shell); + HyperVSnapshot(const QString& filename, + HyperVVirtualMachine& vm, + const VirtualMachineDescription& desc, + PowerShell& power_shell); + +protected: + void capture_impl() override; + void erase_impl() override; + void apply_impl() override; + +private: + const QString quoted_id; + const QString vm_name; + PowerShell& power_shell; +}; + +} // namespace multipass + +#endif // MULTIPASS_HYPERVSNAPSHOT_H diff --git a/src/platform/backends/hyperv/hyperv_virtual_machine.cpp b/src/platform/backends/hyperv/hyperv_virtual_machine.cpp new file mode 100644 index 0000000000..0ab44d659c --- /dev/null +++ b/src/platform/backends/hyperv/hyperv_virtual_machine.cpp @@ -0,0 +1,535 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "hyperv_virtual_machine.h" +#include "hyperv_snapshot.h" + +#include +#include // TODO@snapshots drop +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; + +namespace +{ +const QString default_switch_guid{"C08CB7B8-9B3C-408E-8E30-5E16A3AEB444"}; +const QString snapshot_name{"suspend"}; + +namespace fs = std::filesystem; + +QString quoted(const QString& str) +{ + return '"' + str + '"'; +} + +std::optional remote_ip(const std::string& host, + int port, + const std::string& username, + const mp::SSHKeyProvider& key_provider) // clang-format off +try // clang-format on +{ + mp::SSHSession session{host, port, username, key_provider}; + + sockaddr_in addr{}; + int size = sizeof(addr); + auto socket = ssh_get_fd(session); + const auto failed = getpeername(socket, reinterpret_cast(&addr), &size); + + if (failed) + return std::nullopt; + + return std::optional{ntohl(addr.sin_addr.s_addr)}; +} +catch (...) +{ + return std::nullopt; +} + +auto instance_state_for(mp::PowerShell* power_shell, const QString& name) +{ + QString state; + + if (power_shell->run({"Get-VM", "-Name", name, "|", "Select-Object", "-ExpandProperty", "State"}, + &state, + nullptr, + /* whisper = */ true)) // avoid GUI polling spamming the logs + { + if (state == "Running") + { + return mp::VirtualMachine::State::running; + } + else if (state == "Starting") + { + return mp::VirtualMachine::State::starting; + } + else if (state == "Saved") + { + return mp::VirtualMachine::State::suspended; + } + else if (state == "Off") + { + return mp::VirtualMachine::State::stopped; + } + } + + return mp::VirtualMachine::State::unknown; +} + +void delete_automatic_snapshots(mp::PowerShell* power_shell, const QString& name) +{ + power_shell->easy_run({"Get-VMCheckpoint -VMName", + name, + "| Where-Object { $_.IsAutomaticCheckpoint } | Remove-VMCheckpoint -Confirm:$false"}, + "Could not delete existing automatic checkpoints"); +} + +void add_extra_net(mp::PowerShell& ps, const QString& vm_name, const mp::NetworkInterface& extra_interface) +{ + const auto switch_name = quoted(QString::fromStdString(extra_interface.id)); + ps.easy_run({"Get-VMSwitch", "-Name", switch_name}, + fmt::format("Could not find the device to connect to: no switch named \"{}\"", extra_interface.id)); + ps.easy_run({"Add-VMNetworkAdapter", + "-VMName", + vm_name, + "-SwitchName", + switch_name, + "-StaticMacAddress", + quoted(QString::fromStdString(extra_interface.mac_address))}, + fmt::format("Could not setup adapter for {}", extra_interface.id)); +} + +fs::path locate_vmcx_file(const fs::path& exported_vm_dir_path) +{ + if (fs::exists(exported_vm_dir_path) && fs::is_directory(exported_vm_dir_path)) + { + const fs::path vm_state_dir = exported_vm_dir_path / "Virtual Machines"; + + if (auto iter = std::find_if( + fs::directory_iterator{vm_state_dir}, + fs::directory_iterator{}, + [](const fs::directory_entry& entry) -> bool { return entry.path().extension() == ".vmcx"; }); + iter != fs::directory_iterator{}) + { + return iter->path(); + } + } + + return {}; +} +} // namespace + +mp::HyperVVirtualMachine::HyperVVirtualMachine(const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const mp::Path& instance_dir) + : HyperVVirtualMachine{desc, monitor, key_provider, instance_dir, true} +{ + if (!power_shell->run({"Get-VM", "-Name", name})) + { + auto mem_size = QString::number(desc.mem_size.in_bytes()); /* format documented in `Help(New-VM)`, under + `-MemoryStartupBytes` option; */ + + power_shell->easy_run({QString("$switch = Get-VMSwitch -Id %1").arg(default_switch_guid)}, + "Could not find the default switch"); + + power_shell->easy_run({"New-VM", + "-Name", + name, + "-Generation", + "2", + "-VHDPath", + '"' + desc.image.image_path + '"', + "-BootDevice", + "VHD", + "-SwitchName", + "$switch.Name", + "-MemoryStartupBytes", + mem_size}, + "Could not create VM"); + power_shell->easy_run({"Set-VMFirmware", "-VMName", name, "-EnableSecureBoot", "Off"}, + "Could not disable secure boot"); + power_shell->easy_run({"Set-VMProcessor", "-VMName", name, "-Count", QString::number(desc.num_cores)}, + "Could not configure VM processor"); + power_shell->easy_run({"Add-VMDvdDrive", "-VMName", name, "-Path", '"' + desc.cloud_init_iso + '"'}, + "Could not setup cloud-init drive"); + power_shell->easy_run({"Set-VMMemory", "-VMName", name, "-DynamicMemoryEnabled", "$false"}, + "Could not disable dynamic memory"); + + setup_network_interfaces(); + + state = State::off; + } + else + { + state = instance_state_for(power_shell.get(), name); + } + + power_shell->easy_run({"Set-VM", "-Name", name, "-AutomaticCheckpointsEnabled", "$false"}, + "Could not disable automatic snapshots"); // TODO move to new VMs only in a couple of releases + delete_automatic_snapshots(power_shell.get(), name); // TODO drop in a couple of releases (going in on v1.13) +} + +mp::HyperVVirtualMachine::HyperVVirtualMachine(const std::string& source_vm_name, + const VMSpecs& src_vm_specs, + const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& dest_instance_dir) + : HyperVVirtualMachine{desc, monitor, key_provider, dest_instance_dir, true} +{ + // 1. Export-VM -Name vm1 -Path C:\ProgramData\Multipass\data\vault\instances\vm1-clone1 + power_shell->easy_run( + {"Export-VM", "-Name", QString::fromStdString(source_vm_name), "-Path", quoted(dest_instance_dir)}, + "Could not export the source vm"); + + // 2. $imported_vm=Import-VM -Path 'C:\ProgramData\Multipass\data\vault\instances\vm1-clone1\vm1\Virtual + // Machines\7735327A-A22F-4926-95A1-51757D650BB7.vmcx' -Copy -GenerateNewId -VhdDestinationPath + // "C:\ProgramData\Multipass\data\vault\instances\vm1-clone1\" + const fs::path exported_vm_path = fs::path{dest_instance_dir.toStdString()} / fs::path{source_vm_name}; + const fs::path vmcx_file_path = locate_vmcx_file(exported_vm_path); + // The next step needs to rename the instance, so we need to store the instance variable $imported_vm from the + // Import-VM step. Because we can not use vm name to uniquely identify the vm due to the imported vm has the same + // name. + power_shell->easy_run({"$imported_vm=Import-VM", + "-Path", + quoted(QString::fromStdString(vmcx_file_path.string())), + "-Copy", + "-GenerateNewId", + "-VhdDestinationPath", + quoted(dest_instance_dir)}, + "Could not import from the exported instance directory"); + // 3. Rename-vm $imported_vm -NewName vm1-clone1 + power_shell->easy_run({"Rename-vm", "$imported_vm", "-NewName", name}, "Could not rename the imported vm"); + // 4. Remove-VMDvdDrive -VMName vm1-clone1 -ControllerNumber 0 -ControllerLocation 1 + power_shell->easy_run({"Remove-VMDvdDrive", + "-VMName", + name, + "-ControllerNumber", + QString::number(0), + "-ControllerLocation", + QString::number(1)}, + "Could not remove the cloud-init-config.iso file from the virtual machine"); + // 5. Add-VMDvdDrive -VMName vm1-clone1 -Path + // 'C:\ProgramData\Multipass\data\vault\instances\vm1-clone1\cloud-init-config.iso' + const fs::path dest_cloud_init_path = fs::path{dest_instance_dir.toStdString()} / cloud_init_file_name; + power_shell->easy_run( + {"Add-VMDvdDrive", "-VMName", name, "-Path", quoted(QString::fromStdString(dest_cloud_init_path.string()))}, + "Could not add the cloud-init-config.iso to the virtual machine"); + // 6. Reset the default address, and extra interface addresses + update_network_interfaces(src_vm_specs); + + state = State::off; + + remove_snapshots_from_backend(); + fs::remove_all(exported_vm_path); +} + +mp::HyperVVirtualMachine::HyperVVirtualMachine(const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& instance_dir, + bool /*is_internal*/) + : BaseVirtualMachine{desc.vm_name, key_provider, instance_dir}, + desc{desc}, + name{QString::fromStdString(desc.vm_name)}, + power_shell{std::make_unique(vm_name)}, + monitor{&monitor} +{ +} + +void mp::HyperVVirtualMachine::setup_network_interfaces() +{ + power_shell->easy_run({"Set-VMNetworkAdapter", + "-VMName", + name, + "-StaticMacAddress", + quoted(QString::fromStdString(desc.default_mac_address))}, + "Could not setup default adapter"); + + for (const auto& net : desc.extra_interfaces) + { + add_extra_net(*power_shell, name, net); + } +} + +void mp::HyperVVirtualMachine::update_network_interfaces(const VMSpecs& src_specs) +{ + // We use mac address to identify the corresponding network adapter, it is a cumbersome implementation because the + // update requires the original default mac address and extra interface mac addresses. Meanwhile, there are other + // alternatives, 1. Make a proper name when we add a network interface by calling Add-VMNetworkAdapter and using the + // name as the unique identifier to remove it. However, this was not done from the beginning, so it will not be + // backward compatible. 2. Assume the network adapters are in the added order. However, hyper-v Get-VMNetworkAdapter + // does not guarantee that. 3. Use the switch name to query the network adapter. However, it might look like a + // unique identifier but actually it is not. + power_shell->easy_run( + {"Get-VMNetworkAdapter -VMName", + name, + "| Where-Object {$_.MacAddress -eq", + // "Where-Object {$_.MacAddress -eq }" clause requires the string quoted and no colon delimiter, + // for example "5254002CC58C"; whereas the "Set-VMNetworkAdapter -StaticMacAddress " can accept + // unquoted and with colon delimiter like 52:54:00:2C:C5:8B. + quoted(QString::fromStdString(src_specs.default_mac_address).remove(':')), + "} | Set-VMNetworkAdapter -StaticMacAddress", + QString::fromStdString(desc.default_mac_address)}, + "Could not setup the default network adapter"); + + assert(src_specs.extra_interfaces.size() == desc.extra_interfaces.size()); + for (size_t i = 0; i < src_specs.extra_interfaces.size(); ++i) + { + power_shell->easy_run({"Get-VMNetworkAdapter -VMName", + name, + "| Where-Object {$_.MacAddress -eq", + quoted(QString::fromStdString(src_specs.extra_interfaces[i].mac_address).remove(':')), + "} | Set-VMNetworkAdapter -StaticMacAddress", + QString::fromStdString(desc.extra_interfaces[i].mac_address)}, + "Could not setup the extra network adapter"); + } +} + +mp::HyperVVirtualMachine::~HyperVVirtualMachine() +{ + top_catch_all(vm_name, [this]() { + update_suspend_status = false; + + if (current_state() == State::running) + suspend(); + }); +} + +void mp::HyperVVirtualMachine::start() +{ + state = State::starting; + update_state(); + + QString output_err; + if (!power_shell->run({"Start-VM", "-Name", name}, nullptr, &output_err)) + { + state = instance_state_for(power_shell.get(), name); + update_state(); + throw StartException{vm_name, output_err.toStdString()}; + } +} + +void mp::HyperVVirtualMachine::shutdown(ShutdownPolicy shutdown_policy) +{ + std::unique_lock lock{state_mutex}; + const auto present_state = current_state(); + + try + { + check_state_for_shutdown(shutdown_policy); + } + catch (const VMStateIdempotentException& e) + { + mpl::log(mpl::Level::info, vm_name, e.what()); + return; + } + + drop_ssh_session(); + + if (shutdown_policy == ShutdownPolicy::Poweroff) + { + mpl::log(mpl::Level::info, vm_name, "Forcing shutdown"); + power_shell->run({"Stop-VM", "-Name", name, "-TurnOff"}); + } + else + { + power_shell->run({"Stop-VM", "-Name", name}); + } + + state = State::off; + + // If it wasn't force, we wouldn't be here + if (present_state == State::starting) + { + state_wait.wait(lock, [this] { return shutdown_while_starting; }); + } + + ip = std::nullopt; + update_state(); +} + +void mp::HyperVVirtualMachine::suspend() +{ + auto present_state = instance_state_for(power_shell.get(), name); + + if (present_state == State::running || present_state == State::delayed_shutdown) + { + power_shell->run({"Save-VM", "-Name", name}); + + drop_ssh_session(); + if (update_suspend_status) + { + state = State::suspended; + update_state(); + } + } + else if (present_state == State::stopped) + { + mpl::log(mpl::Level::info, vm_name, fmt::format("Ignoring suspend issued while stopped")); + } + + monitor->on_suspend(); +} + +mp::VirtualMachine::State mp::HyperVVirtualMachine::current_state() +{ + auto present_state = instance_state_for(power_shell.get(), name); + + if ((state == State::delayed_shutdown && present_state == State::running) || state == State::starting) + return state; + + state = present_state; + return state; +} + +int mp::HyperVVirtualMachine::ssh_port() +{ + return 22; +} + +void mp::HyperVVirtualMachine::ensure_vm_is_running() +{ + auto is_vm_running = [this] { return state != State::off; }; + + mp::backend::ensure_vm_is_running_for(this, is_vm_running, "Instance shutdown during start"); +} + +void mp::HyperVVirtualMachine::update_state() +{ + monitor->persist_state_for(vm_name, state); +} + +std::string mp::HyperVVirtualMachine::ssh_hostname(std::chrono::milliseconds /*timeout*/) +{ + return name.toStdString() + ".mshome.net"; +} + +std::string mp::HyperVVirtualMachine::ssh_username() +{ + return desc.ssh_username; +} + +std::string mp::HyperVVirtualMachine::management_ipv4() +{ + if (!ip) + { + // Not using cached SSH session for this because a) the underlying functions do not guarantee constness; + // b) we endure the penalty of creating a new session only when we don't have the IP yet. + auto result = remote_ip(VirtualMachine::ssh_hostname(), ssh_port(), ssh_username(), key_provider); + if (result) + ip.emplace(result.value()); + } + return ip ? ip.value().as_string() : "UNKNOWN"; +} + +std::string mp::HyperVVirtualMachine::ipv6() +{ + return {}; +} + +void mp::HyperVVirtualMachine::update_cpus(int num_cores) +{ + assert(num_cores > 0); + + power_shell->easy_run({"Set-VMProcessor", "-VMName", name, "-Count", QString::number(num_cores)}, + "Could not update CPUs"); +} + +void mp::HyperVVirtualMachine::resize_memory(const MemorySize& new_size) +{ + assert(new_size.in_bytes() > 0); + + QStringList resize_cmd = {"Set-VMMemory", "-VMName", name, "-StartupBytes", QString::number(new_size.in_bytes())}; + power_shell->easy_run(resize_cmd, "Could not resize memory"); +} + +void mp::HyperVVirtualMachine::resize_disk(const MemorySize& new_size) +{ + assert(new_size.in_bytes() > 0); + + // Resize the current disk layer, which will differ from the original image if there are snapshots + // clang-format off + QStringList resize_cmd = {"Get-VM", "-VMName", name, "|", "Select-Object", "VMId", "|", "Get-VHD", "|", + "Resize-VHD", "-SizeBytes", QString::number(new_size.in_bytes())}; // clang-format on + power_shell->easy_run(resize_cmd, "Could not resize disk"); +} + +void mp::HyperVVirtualMachine::add_network_interface(int /* not used on this backend */, + const std::string& default_mac_addr, + const NetworkInterface& extra_interface) +{ + desc.extra_interfaces.push_back(extra_interface); + add_extra_net(*power_shell, name, extra_interface); + add_extra_interface_to_instance_cloud_init(default_mac_addr, extra_interface); +} + +mp::MountHandler::UPtr mp::HyperVVirtualMachine::make_native_mount_handler(const std::string& target, + const mp::VMMount& mount) +{ + static const SmbManager smb_manager{}; + return std::make_unique(this, + &key_provider, + target, + mount, + instance_dir.absolutePath(), + smb_manager); +} + +void mp::HyperVVirtualMachine::remove_snapshots_from_backend() const +{ + // Get-VMSnapshot -VMName "YourVMName" | Remove-VMSnapshot + power_shell->easy_run({"Get-VMSnapshot -VMName", name, "| Remove-VMSnapshot"}, "Could not remove the snapshots"); +} + +auto mp::HyperVVirtualMachine::make_specific_snapshot(const std::string& snapshot_name, + const std::string& comment, + const std::string& instance_id, + const VMSpecs& specs, + std::shared_ptr parent) -> std::shared_ptr +{ + assert(power_shell); + return std::make_shared(snapshot_name, + comment, + instance_id, + specs, + std::move(parent), + name, + *this, + *power_shell); +} + +auto mp::HyperVVirtualMachine::make_specific_snapshot(const QString& filename) -> std::shared_ptr +{ + return std::make_shared(filename, *this, desc, *power_shell); +} diff --git a/src/platform/backends/hyperv/hyperv_virtual_machine.h b/src/platform/backends/hyperv/hyperv_virtual_machine.h new file mode 100644 index 0000000000..2012983773 --- /dev/null +++ b/src/platform/backends/hyperv/hyperv_virtual_machine.h @@ -0,0 +1,108 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_HYPERV_VIRTUAL_MACHINE_H +#define MULTIPASS_HYPERV_VIRTUAL_MACHINE_H + +#include + +#include +#include +#include + +#include + +#include +#include + +namespace multipass +{ +struct NetworkInterface; +struct VMSpecs; +class PowerShell; +class SSHKeyProvider; +class VirtualMachineDescription; +class VMStatusMonitor; + +class HyperVVirtualMachine final : public BaseVirtualMachine +{ +public: + HyperVVirtualMachine(const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& instance_dir); + // Contruct the vm based on the source virtual machine + HyperVVirtualMachine(const std::string& source_vm_name, + const multipass::VMSpecs& src_vm_specs, + const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& dest_instance_dir); + ~HyperVVirtualMachine(); + void start() override; + void shutdown(ShutdownPolicy shutdown_policy = ShutdownPolicy::Powerdown) override; + void suspend() override; + State current_state() override; + int ssh_port() override; + std::string ssh_hostname(std::chrono::milliseconds timeout) override; + std::string ssh_username() override; + std::string management_ipv4() override; + std::string ipv6() override; + void ensure_vm_is_running() override; + void update_state() override; + void update_cpus(int num_cores) override; + void resize_memory(const MemorySize& new_size) override; + void resize_disk(const MemorySize& new_size) override; + void add_network_interface(int index, + const std::string& default_mac_addr, + const NetworkInterface& extra_interface) override; + std::unique_ptr make_native_mount_handler(const std::string& target, const VMMount& mount) override; + +protected: + void require_snapshots_support() const override; + std::shared_ptr make_specific_snapshot(const QString& filename) override; + std::shared_ptr make_specific_snapshot(const std::string& snapshot_name, + const std::string& comment, + const std::string& instance_id, + const VMSpecs& specs, + std::shared_ptr parent) override; + +private: + HyperVVirtualMachine(const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& instance_dir, + bool is_internal); // is_internal is a dummy parameter to differentiate with other constructors + + void setup_network_interfaces(); + void update_network_interfaces(const VMSpecs& src_specs); + void remove_snapshots_from_backend() const; + + VirtualMachineDescription desc; // TODO we should probably keep the VMDescription in the base VM class instead + const QString name; + std::optional ip; + std::unique_ptr power_shell; + VMStatusMonitor* monitor; + bool update_suspend_status{true}; +}; +} // namespace multipass + +inline void multipass::HyperVVirtualMachine::require_snapshots_support() const +{ +} + +#endif // MULTIPASS_HYPERV_VIRTUAL_MACHINE_H diff --git a/src/platform/backends/hyperv/hyperv_virtual_machine_factory.cpp b/src/platform/backends/hyperv/hyperv_virtual_machine_factory.cpp new file mode 100644 index 0000000000..29a2b9fdfb --- /dev/null +++ b/src/platform/backends/hyperv/hyperv_virtual_machine_factory.cpp @@ -0,0 +1,437 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "hyperv_virtual_machine_factory.h" +#include "hyperv_virtual_machine.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include + +#include +#include + +namespace mp = multipass; + +namespace +{ +const QStringList& expand_property = mp::PowerShell::Snippets::expand_property; + +void ensure_hyperv_service_is_running(mp::PowerShell& power_shell) +{ + QString ps_output; + const QStringList get_vmms_service{"Get-Service", "-Name", "vmms"}; + + if (!power_shell.run(QStringList() << get_vmms_service << expand_property << "Status", &ps_output)) + { + throw std::runtime_error("The Hyper-V service does not exist. Ensure Hyper-V is installed correctly."); + } + + if (ps_output == "Stopped") + { + power_shell.run(QStringList() << get_vmms_service << expand_property << "StartType", &ps_output); + + if (ps_output == "Disabled") + { + throw std::runtime_error("The Hyper-V service is set to disabled. Please re-enable \"vmms\"."); + } + + if (!power_shell.run(QStringList() << "Start-Service" + << "-Name" + << "vmms", + &ps_output)) + { + throw std::runtime_error("Could not start the Hyper-V service"); + } + } +} + +void check_host_hyperv_support(mp::PowerShell& power_shell) +{ + QString ps_output; + + if (power_shell.run(QStringList() << "Get-CimInstance Win32_Processor" << expand_property + << "VirtualizationFirmwareEnabled", + &ps_output)) + { + if (ps_output == "False") + { + throw std::runtime_error("Virtualization support appears to be disabled in the BIOS.\n" + "Enter your BIOS setup and enable Virtualization Technology (VT)."); + } + } + + if (power_shell.run(QStringList() << "Get-CimInstance Win32_Processor" << expand_property + << "SecondLevelAddressTranslationExtensions", + &ps_output)) + { + if (ps_output == "False") + { + throw std::runtime_error("The CPU does not have proper virtualization extensions to support Hyper-V"); + } + } +} + +void check_hyperv_feature_enabled(mp::PowerShell& power_shell) +{ + QString ps_output; + const QStringList optional_feature{"Get-WindowsOptionalFeature", "-Online", "-FeatureName"}; + + // Check if Hyper-V is fully enabled + if (power_shell.run(QStringList() << optional_feature << "Microsoft-Hyper-V" << expand_property << "State", + &ps_output)) + { + if (ps_output.isEmpty()) + { + throw std::runtime_error( + "Hyper-V is not available on this edition of Windows 10. Please upgrade to one of Pro, Enterprise" + "or Education editions."); + } + else if (ps_output == "Enabled") + { + power_shell.run(QStringList() + << optional_feature << "Microsoft-Hyper-V-Hypervisor" << expand_property << "State", + &ps_output); + if (ps_output == "Enabled") + return; + + throw std::runtime_error("The Hyper-V Hypervisor is disabled. Please enable by using the following\n" + "command in an Administrator Powershell and reboot:\n" + "Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Hypervisor"); + } + + throw std::runtime_error("The Hyper-V Windows feature is disabled. Please enable by using the following\n" + "command in an Administrator Powershell and reboot:\n" + "Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All"); + } + else + { + throw std::runtime_error("Cannot determine if Hyper-V is available on this system."); + } +} + +void check_hyperv_support() +{ + mp::PowerShell power_shell("Hyper-V Health Check"); + QString ps_output; + QStringList get_reg_version_info{"Get-ItemProperty", + "-Path", + "'HKLM:\\Software\\Microsoft\\Windows NT\\CurrentVersion'"}; + + // Check for Windows 10 + power_shell.run(QStringList() << get_reg_version_info << expand_property << "CurrentMajorVersionNumber", + &ps_output); + if (ps_output.toInt() < 10) + throw std::runtime_error("Multipass support for Hyper-V requires Windows 10 or newer"); + else if (ps_output == "10") + { + // Check if it's a version less than 1803; NB: comparing strings, as new style ReleaseId is e.g. "21H2" + power_shell.run(QStringList() << get_reg_version_info << expand_property << "ReleaseId", &ps_output); + if (ps_output < "1803") + throw std::runtime_error("Multipass requires at least Windows 10 version 1803. Please update your system."); + } + + // Check if HypervisorPresent is true- implies either Hyper-V is running or running under a + // different virtualized environment like VirtualBox or QEMU. + // If it's running under a different virtualized environment, we can't check if nesting is + // available, so the user is on their own and we'll bubble up any failures at `launch`. + power_shell.run(QStringList() << "Get-CimInstance Win32_ComputerSystem" << expand_property << "HypervisorPresent", + &ps_output); + + QString hypervisor_present{ps_output}; + // Implies Hyper-V is not running (or any hypervisor for that matter). + // Determine why it is not running. + if (hypervisor_present == "False") + { + // First check if the CPU has the proper virtualization support. + // This is only accurate when "HypervisorPresent" returns false. + // This throws if the support is not found. + check_host_hyperv_support(power_shell); + } + + // Check if the Hyper-V feature is enabled. + // Throws if the Hyper-V feature is not enabled. + check_hyperv_feature_enabled(power_shell); + + // Check to make sure the service is running. + // Throws when it's not running. + ensure_hyperv_service_is_running(power_shell); + + // Lastly, if we make it this far, check hypervisor_present again. + // If it's false, then we know Hyper-V is enabled, but the host has + // not rebooted yet. + if (hypervisor_present == "False") + { + throw std::runtime_error("The computer needs to be rebooted in order for Hyper-V to be fully available"); + } +} + +std::vector switch_links(const std::vector& adapters, + const QString& adapter_description) +{ + std::vector ret; + if (!adapter_description.isEmpty()) + { + auto same = [&adapter_description](const auto& net) { return adapter_description == net.description.c_str(); }; + if (auto it = std::find_if(adapters.cbegin(), adapters.cend(), same); it != adapters.cend()) + ret.emplace_back(it->id); + } + + return ret; +} + +std::string switch_description(const QString& switch_type, const std::vector& links, const QString& notes) +{ + std::string ret; + if (switch_type.contains("external", Qt::CaseInsensitive)) + { + if (links.empty()) + ret = "Virtual Switch with external networking"; + else + ret = fmt::format("Virtual Switch with external networking via \"{}\"", fmt::join(links, ", ")); + } + else if (!links.empty()) + throw std::runtime_error{fmt::format("Unexpected link(s) for non-external switch: {}", fmt::join(links, ", "))}; + else if (switch_type.contains("private", Qt::CaseInsensitive)) + ret = "Private virtual switch"; + else if (switch_type.contains("internal", Qt::CaseInsensitive)) + ret = "Virtual Switch with internal networking"; + else + ret = fmt::format("Unknown Virtual Switch type: {}", switch_type); + + if (!notes.isEmpty()) + ret = fmt::format("{} ({})", ret, notes); + + return ret; +} + +void update_adapter_authorizations(std::vector& adapters, + const std::vector& switches) +{ + for (auto& adapter : adapters) + adapter.needs_authorization = std::none_of(switches.cbegin(), switches.cend(), [&adapter](const auto& switch_) { + return std::find(switch_.links.cbegin(), switch_.links.cend(), adapter.id) != switch_.links.cend(); + }); +} + +std::string error_msg_helper(const std::string& msg_core, const QString& ps_output) +{ + auto detail = ps_output.isEmpty() ? "" : fmt::format(" Detail: {}", ps_output); + return fmt::format("{} - error executing powershell command.{}", msg_core, detail); +} +} // namespace + +mp::HyperVVirtualMachineFactory::HyperVVirtualMachineFactory(const mp::Path& data_dir) + : BaseVirtualMachineFactory(MP_UTILS.derive_instances_dir(data_dir, get_backend_directory_name(), instances_subdir)) +{ +} + +mp::VirtualMachine::UPtr mp::HyperVVirtualMachineFactory::create_virtual_machine(const VirtualMachineDescription& desc, + const SSHKeyProvider& key_provider, + VMStatusMonitor& monitor) +{ + return std::make_unique(desc, + monitor, + key_provider, + get_instance_directory(desc.vm_name)); +} + +void mp::HyperVVirtualMachineFactory::remove_resources_for_impl(const std::string& name) +{ + PowerShell::exec({"Remove-VM", "-Name", QString::fromStdString(name), "-Force"}, name); +} + +mp::VMImage mp::HyperVVirtualMachineFactory::prepare_source_image(const mp::VMImage& source_image) +{ + QFileInfo source_file{source_image.image_path}; + auto vhdx_file = QString("%1/%2.vhdx").arg(source_file.path()).arg(source_file.completeBaseName()); + + QStringList convert_args( + {QStringLiteral("convert"), "-o", "subformat=dynamic", "-O", "vhdx", source_image.image_path, vhdx_file}); + + QProcess convert; + convert.setProgram("qemu-img.exe"); + convert.setArguments(convert_args); + convert.start(); + + if (!convert.waitForFinished(mp::image_resize_timeout)) + { + throw std::runtime_error(qPrintable("Conversion of image to vhdx timed out...")); + } + + if (convert.exitStatus() != QProcess::NormalExit || convert.exitCode() != 0) + { + throw std::runtime_error( + qPrintable("Conversion of image to vhdx failed with error: " + convert.readAllStandardError())); + } + if (!QFile::exists(vhdx_file)) + { + throw std::runtime_error("vhdx image file is missing"); + } + + auto prepared_image = source_image; + prepared_image.image_path = vhdx_file; + return prepared_image; +} + +void mp::HyperVVirtualMachineFactory::prepare_instance_image(const mp::VMImage& instance_image, + const VirtualMachineDescription& desc) +{ + const auto disk_size = QString::number(desc.disk_space.in_bytes()); // format documented in `Help(Resize-VHD)` + + // Resize-VHD can't operate on the sparse images that `qemu-img` produces. The `fsutil` cmd allocates them fully. + // Images copied from the cache aren't sparse, but they remain unaffected. + QStringList unsparse_cmd = {"fsutil", "sparse", "setFlag", instance_image.image_path, "0"}; + QStringList resize_cmd = {"Resize-VHD", "-Path", instance_image.image_path, "-SizeBytes", disk_size}; + PowerShell ps{desc.vm_name}; + + for (const auto& [cmd, op] : {std::pair(&unsparse_cmd, "unsparse"), std::pair(&resize_cmd, "resize")}) + ps.easy_run(*cmd, fmt::format("Failed to {} instance image", op)); +} + +void mp::HyperVVirtualMachineFactory::hypervisor_health_check() +{ + check_hyperv_support(); +} + +auto mp::HyperVVirtualMachineFactory::networks() const -> std::vector +{ + auto adapters = get_adapters(); + auto networks = get_switches(adapters); + update_adapter_authorizations(adapters, /* switches = */ networks); + + if (adapters.size() > networks.size()) + std::swap(adapters, networks); // we want to move the smallest one + networks.reserve(adapters.size() + networks.size()); // avoid growing more times than needed + + std::move(adapters.begin(), adapters.end(), std::back_inserter(networks)); + + return networks; +} + +std::string mp::HyperVVirtualMachineFactory::create_bridge_with(const NetworkInterfaceInfo& interface) +{ + assert(interface.type == "ethernet"); + + const auto switch_name = QStringLiteral("ExtSwitch (%1)").arg(interface.id.c_str()); + auto quote = [](const auto& str) { return QStringLiteral("'%1'").arg(str); }; + auto ps_args = QStringList{"New-VMSwitch", + "-NetAdapterName", + quote(interface.id.c_str()), + "-Name", + quote(switch_name), + "-AllowManagementOS", + "$true", + "-Notes", + "'Created by Multipass'", + "-ComputerName", + "localhost"}; // workaround for names with more than 15 chars + ps_args << expand_property << "Name"; + + QString ps_output; + QString ps_output_err; + if (!mp::PowerShell::exec(ps_args, + "Hyper-V Switch Creation", + &ps_output, + &ps_output_err)) // TODO should probably cache PS processes + throw std::runtime_error{error_msg_helper("Could not create external switch", ps_output_err)}; + + if (ps_output != switch_name) + throw std::runtime_error{error_msg_helper("Could not create external switch", ps_output)}; + + return ps_output.toStdString(); +} + +auto mp::HyperVVirtualMachineFactory::get_switches(const std::vector& adapters) + -> std::vector +{ + static const auto ps_args = QStringList{"Get-VMSwitch", + "-ComputerName", + "localhost", // workaround for names with more than 15 chars + "|", + "Select-Object", + "-Property", + "Name,SwitchType,NetAdapterInterfaceDescription,Notes"} + + mp::PowerShell::Snippets::to_bare_csv; + + QString ps_output; + QString ps_output_err; + if (mp::PowerShell::exec(ps_args, "Hyper-V Switch Listing", &ps_output, &ps_output_err)) + { + std::vector ret{}; + for (const auto& line : ps_output.split(QRegularExpression{"[\r\n]"}, Qt::SkipEmptyParts)) + { + auto terms = line.split(',', Qt::KeepEmptyParts); + if (terms.size() != 4) + { + throw std::runtime_error{ + fmt::format("Could not determine available networks - unexpected powershell output: {}", + ps_output)}; + } + + auto links = switch_links(adapters, terms.at(2)); + auto description = switch_description(terms.at(1), links, terms.at(3)); + ret.push_back({terms.at(0).toStdString(), "switch", description, links}); + } + + return ret; + } + + throw std::runtime_error{error_msg_helper("Could not determine available networks", ps_output_err)}; +} + +auto mp::HyperVVirtualMachineFactory::get_adapters() -> std::vector +{ + std::vector ret; + for (auto& item : MP_PLATFORM.get_network_interfaces_info()) + { + auto& net = item.second; + if (const auto& type = net.type; type == "ethernet") + { + net.needs_authorization = true; + ret.emplace_back(std::move(net)); + } + } + + return ret; +} + +mp::VirtualMachine::UPtr mp::HyperVVirtualMachineFactory::clone_vm_impl(const std::string& src_name, + const multipass::VMSpecs& src_spec, + const VirtualMachineDescription& dest_vm_desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider) +{ + return std::make_unique(src_name, + src_spec, + dest_vm_desc, + monitor, + key_provider, + get_instance_directory(dest_vm_desc.vm_name)); +} diff --git a/src/platform/backends/hyperv/hyperv_virtual_machine_factory.h b/src/platform/backends/hyperv/hyperv_virtual_machine_factory.h new file mode 100644 index 0000000000..a23f8ddcba --- /dev/null +++ b/src/platform/backends/hyperv/hyperv_virtual_machine_factory.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_HYPERV_VIRTUAL_MACHINE_FACTORY_H +#define MULTIPASS_HYPERV_VIRTUAL_MACHINE_FACTORY_H + +#include + +namespace multipass +{ +namespace test +{ +struct HyperVNetworkAccessor; // fwd declaration, to befriend below +} + +class HyperVVirtualMachineFactory final : public BaseVirtualMachineFactory +{ +public: + explicit HyperVVirtualMachineFactory(const Path& data_dir); + + VirtualMachine::UPtr create_virtual_machine(const VirtualMachineDescription& desc, + const SSHKeyProvider& key_provider, + VMStatusMonitor& monitor) override; + VMImage prepare_source_image(const VMImage& source_image) override; + void prepare_instance_image(const VMImage& instance_image, const VirtualMachineDescription& desc) override; + void hypervisor_health_check() override; + QString get_backend_version_string() const override + { + return "hyperv"; + }; + std::vector networks() const override; + void require_snapshots_support() const override; + void require_clone_support() const override + { + } + +protected: + std::string create_bridge_with(const NetworkInterfaceInfo& interface) override; + void remove_resources_for_impl(const std::string& name) override; + +private: + friend struct multipass::test::HyperVNetworkAccessor; + + VirtualMachine::UPtr clone_vm_impl(const std::string& source_vm_name, + const multipass::VMSpecs& src_vm_specs, + const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider) override; + static std::vector get_switches(const std::vector& adapters); + static std::vector get_adapters(); +}; +} // namespace multipass + +inline void multipass::HyperVVirtualMachineFactory::require_snapshots_support() const +{ +} + +#endif // MULTIPASS_HYPERV_VIRTUAL_MACHINE_FACTORY_H diff --git a/src/platform/backends/lxd/lxd_vm_image_vault.cpp b/src/platform/backends/lxd/lxd_vm_image_vault.cpp index 226df0cc44..37a40f4cd8 100644 --- a/src/platform/backends/lxd/lxd_vm_image_vault.cpp +++ b/src/platform/backends/lxd/lxd_vm_image_vault.cpp @@ -163,7 +163,6 @@ mp::VMImage mp::LXDVMImageVault::fetch_image(const FetchType& fetch_type, const Query& query, const PrepareAction& prepare, const ProgressMonitor& monitor, - const bool unlock, const std::optional& checksum, const mp::Path& /* save_dir */) { diff --git a/src/platform/backends/lxd/lxd_vm_image_vault.h b/src/platform/backends/lxd/lxd_vm_image_vault.h index 381280bc9c..98cab5664d 100644 --- a/src/platform/backends/lxd/lxd_vm_image_vault.h +++ b/src/platform/backends/lxd/lxd_vm_image_vault.h @@ -44,7 +44,6 @@ class LXDVMImageVault final : public BaseVMImageVault const Query& query, const PrepareAction& prepare, const ProgressMonitor& monitor, - const bool unlock, const std::optional& checksum, const Path& /* save_dir */) override; void remove(const std::string& name) override; diff --git a/src/platform/backends/qemu/CMakeLists.txt b/src/platform/backends/qemu/CMakeLists.txt index ffc18c737c..a144c5c15e 100644 --- a/src/platform/backends/qemu/CMakeLists.txt +++ b/src/platform/backends/qemu/CMakeLists.txt @@ -14,12 +14,6 @@ set (CMAKE_AUTOMOC ON) -set(HOST_ARCH ${CMAKE_HOST_SYSTEM_PROCESSOR}) - -if (${HOST_ARCH} STREQUAL "arm64") - set(HOST_ARCH "aarch64") -endif () - add_definitions(-DHOST_ARCH="${HOST_ARCH}") add_library(qemu_backend STATIC @@ -29,9 +23,7 @@ add_library(qemu_backend STATIC qemu_vm_process_spec.cpp qemu_vmstate_process_spec.cpp qemu_virtual_machine_factory.cpp - qemu_virtual_machine.cpp - ${CMAKE_SOURCE_DIR}/include/multipass/process/basic_process.h - ${CMAKE_SOURCE_DIR}/include/multipass/process/process.h) + qemu_virtual_machine.cpp) target_link_libraries(qemu_backend fmt::fmt-header-only diff --git a/src/platform/backends/qemu/macos/CMakeLists.txt b/src/platform/backends/qemu/macos/CMakeLists.txt new file mode 100644 index 0000000000..81b07aec5d --- /dev/null +++ b/src/platform/backends/qemu/macos/CMakeLists.txt @@ -0,0 +1,24 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +add_library(qemu_platform_detail + qemu_platform_detail_macos.cpp) + +target_include_directories(qemu_platform_detail PRIVATE ../) + +target_link_libraries(qemu_platform_detail + fmt::fmt-header-only + logger + utils + Qt6::Core) diff --git a/src/platform/backends/qemu/macos/qemu_platform_detail.h b/src/platform/backends/qemu/macos/qemu_platform_detail.h new file mode 100644 index 0000000000..75223ea067 --- /dev/null +++ b/src/platform/backends/qemu/macos/qemu_platform_detail.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_QEMU_PLATFORM_DETAIL_H +#define MULTIPASS_QEMU_PLATFORM_DETAIL_H + +#include + +#include + +namespace multipass +{ +// This class is the platform detail for QEMU on macOS +class QemuPlatformDetail : public QemuPlatform +{ +public: + explicit QemuPlatformDetail(); + + std::optional get_ip_for(const std::string& hw_addr) override; + void remove_resources_for(const std::string& name) override; + void platform_health_check() override; + QStringList vmstate_platform_args() override; + QStringList vm_platform_args(const VirtualMachineDescription& vm_desc) override; + QString get_directory_name() const override; + bool is_network_supported(const std::string& network_type) const override; + bool needs_network_prep() const override; + std::string create_bridge_with(const NetworkInterfaceInfo& interface) const override; + void set_authorization(std::vector& networks) override; + +private: + const QString host_arch{HOST_ARCH}; + const QStringList common_args; +}; +} // namespace multipass +#endif // MULTIPASS_QEMU_PLATFORM_DETAIL_H diff --git a/src/platform/backends/qemu/macos/qemu_platform_detail_macos.cpp b/src/platform/backends/qemu/macos/qemu_platform_detail_macos.cpp new file mode 100644 index 0000000000..ea79421438 --- /dev/null +++ b/src/platform/backends/qemu/macos/qemu_platform_detail_macos.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "qemu_platform_detail.h" + +#include +#include + +#include + +#include + +namespace mp = multipass; + +namespace +{ +auto get_common_args(const QString& host_arch) +{ + QStringList qemu_args; + + if (host_arch == "aarch64") + { + qemu_args << "-machine" + << "virt,gic-version=3"; + } + + return qemu_args; +} +} // namespace + +mp::QemuPlatformDetail::QemuPlatformDetail() : common_args{get_common_args(host_arch)} +{ +} + +std::optional mp::QemuPlatformDetail::get_ip_for(const std::string& hw_addr) +{ + return mp::backend::get_neighbour_ip(hw_addr); +} + +void mp::QemuPlatformDetail::remove_resources_for(const std::string& name) +{ +} + +void mp::QemuPlatformDetail::platform_health_check() +{ + // TODO: Add appropriate health checks to ensure the QEMU backend will work as expected +} + +QStringList mp::QemuPlatformDetail::vmstate_platform_args() +{ + return common_args; +} + +QStringList mp::QemuPlatformDetail::vm_platform_args(const VirtualMachineDescription& vm_desc) +{ + QStringList qemu_args; + + qemu_args << common_args << "-accel" + << "hvf" + << "-drive" + << QString("file=%1/../Resources/qemu/edk2-%2-code.fd,if=pflash,format=raw,readonly=on") + .arg(QCoreApplication::applicationDirPath()) + .arg(host_arch) + << "-cpu" + << "host" + // Set up the network related args + << "-nic" + << QString::fromStdString( + fmt::format("vmnet-shared,model=virtio-net-pci,mac={}", vm_desc.default_mac_address)); + + for (const auto& extra_interface : vm_desc.extra_interfaces) + { + qemu_args << "-nic" + << QString::fromStdString(fmt::format("vmnet-bridged,ifname={},model=virtio-net-pci,mac={}", + extra_interface.id, + extra_interface.mac_address)); + } + + return qemu_args; +} + +QString mp::QemuPlatformDetail::get_directory_name() const +{ + return "qemu"; +} + +bool mp::QemuPlatformDetail::is_network_supported(const std::string& network_type) const +{ + return network_type == "ethernet" || network_type == "wifi" || network_type == "usb"; +} + +bool mp::QemuPlatformDetail::needs_network_prep() const +{ + return false; +} + +void mp::QemuPlatformDetail::set_authorization(std::vector& networks) +{ + // nothing to do here +} + +mp::QemuPlatform::UPtr mp::QemuPlatformFactory::make_qemu_platform(const Path& data_dir) const +{ + return std::make_unique(); +} + +std::string mp::QemuPlatformDetail::create_bridge_with(const NetworkInterfaceInfo& interface) const +{ + return interface.id; +} diff --git a/src/platform/backends/shared/CMakeLists.txt b/src/platform/backends/shared/CMakeLists.txt index a9474b3fc0..8981b6c04f 100644 --- a/src/platform/backends/shared/CMakeLists.txt +++ b/src/platform/backends/shared/CMakeLists.txt @@ -17,6 +17,7 @@ add_library(shared STATIC base_virtual_machine.cpp base_virtual_machine_factory.cpp sshfs_server_process_spec.cpp + ${CMAKE_SOURCE_DIR}/include/multipass/process/process.h ${CMAKE_SOURCE_DIR}/include/multipass/process/basic_process.h) target_link_libraries(shared diff --git a/src/platform/backends/shared/macos/CMakeLists.txt b/src/platform/backends/shared/macos/CMakeLists.txt new file mode 100644 index 0000000000..0858f3b789 --- /dev/null +++ b/src/platform/backends/shared/macos/CMakeLists.txt @@ -0,0 +1,25 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +add_library(shared_macos STATIC + backend_utils.cpp + process_factory.cpp) + +include_directories(shared_macos + ..) + +target_link_libraries(shared_macos + fmt::fmt-header-only + ssh_common + Qt6::Core) diff --git a/src/platform/backends/shared/macos/backend_utils.cpp b/src/platform/backends/shared/macos/backend_utils.cpp new file mode 100644 index 0000000000..2633c3a010 --- /dev/null +++ b/src/platform/backends/shared/macos/backend_utils.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "backend_utils.h" + +#include +#include + +namespace mp = multipass; + +namespace +{ +QString simplify_mac_address(const QString& input_mac_address) +{ + // Trim the (first) leading 0 of each segment of the a MAC address. + // For example: "04:54:00:b9:69:b5" -> "4:54:0:b9:69:b5" + QString result_mac_address = input_mac_address; + + // Handle the middle segments: Replace ":0" with ":" + result_mac_address.replace(":0", ":"); + + // Handle the first segment: Remove leading zero if it exists + if (result_mac_address.startsWith('0')) + { + // 0 is the start index and 1 is the lengh of the sub-string to remove + result_mac_address.remove(0, 1); + } + + return result_mac_address; +} + +QString get_arp_output() +{ + // -a shows all Address Resolution Protocol(ARP) entries, -n shows numeric IP addresses instead of resolving to + // hostnames + const auto arp_process = mp::platform::make_process(mp::simple_process_spec("arp", {"-an"})); + const auto arp_exit_state = arp_process->execute(); + + if (!arp_exit_state.completed_successfully()) + { + throw std::runtime_error(fmt::format("arp failed ({}) with the following output:\n{}", + arp_exit_state.failure_message(), + arp_process->read_all_standard_error())); + } + + return QString{arp_process->read_all_standard_output()}; +} + +} // namespace + +std::optional mp::backend::get_neighbour_ip(const std::string& mac_address) +{ + // Example output: + // ? (192.168.1.1) at 3c:37:86:8a:e6:84 on en0 ifscope [ethernet] + // ? (192.168.1.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet] + // ? (192.168.64.2) at 52:54:0:2a:12:b6 on bridge100 ifscope [bridge] + // ? (192.168.64.3) at 52:54:0:85:72:55 on bridge100 ifscope [bridge] + // ? (192.168.64.4) at 52:54:0:e1:cd:ab on bridge100 ifscope [bridge] + // ? (192.168.64.255) at ff:ff:ff:ff:ff:ff on bridge100 ifscope [bridge] + // ? (224.0.0.251) at 1:0:5e:0:0:fb on en0 ifscope permanent [ethernet] + + const QString arp_ouput_stream = get_arp_output(); + const QRegularExpression ip_and_mac_address_pair_regex(R"(\(([^)\s]+)\) at ([^\s]+))"); + QRegularExpressionMatchIterator iter = ip_and_mac_address_pair_regex.globalMatch(arp_ouput_stream); + + const QString arp_format_mac_address = simplify_mac_address(QString::fromStdString(mac_address)); + while (iter.hasNext()) + { + QRegularExpressionMatch match = iter.next(); + // group 0 is the full match, 1 and 2 are the inner groups + if (match.captured(2) == arp_format_mac_address) + { + return {mp::IPAddress{match.captured(1).toStdString()}}; + } + } + + return std::nullopt; +} diff --git a/src/platform/platform_shared.h b/src/platform/backends/shared/macos/backend_utils.h similarity index 62% rename from src/platform/platform_shared.h rename to src/platform/backends/shared/macos/backend_utils.h index f592415ad9..f1f75c2d24 100644 --- a/src/platform/platform_shared.h +++ b/src/platform/backends/shared/macos/backend_utils.h @@ -15,25 +15,16 @@ * */ -#ifndef MULTIPASS_PLATFORM_SHARED_H -#define MULTIPASS_PLATFORM_SHARED_H +#ifndef MULTIPASS_BACKEND_UTILS_H +#define MULTIPASS_BACKEND_UTILS_H +#include + +#include #include -#include -namespace multipass::platform +namespace multipass::backend { -const std::unordered_set supported_snapcraft_aliases{ - "core18", - "18.04", - "core20", - "20.04", - "core22", - "22.04", - "core24", - "24.04", - "devel", -}; -} // namespace multipass::platform - -#endif // MULTIPASS_PLATFORM_SHARED_H +std::optional get_neighbour_ip(const std::string& mac_address); +} // namespace multipass::backend +#endif // MULTIPASS_BACKEND_UTILS_H diff --git a/src/platform/backends/shared/macos/process_factory.cpp b/src/platform/backends/shared/macos/process_factory.cpp new file mode 100644 index 0000000000..2eff8a960e --- /dev/null +++ b/src/platform/backends/shared/macos/process_factory.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "process_factory.h" +#include +#include +#include +#include +#include + +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; + +mp::ProcessFactory::ProcessFactory(const Singleton::PrivatePass& pass) + : Singleton::Singleton{pass} +{ + [[maybe_unused]] static bool run_once = []() { + ::setpgid(0, 0); // create own process group. On MacOS, children of the parent are reaped if it dies. + return true; + }(); +} + +// This is the default ProcessFactory that creates a Process with no security mechanisms enabled +std::unique_ptr mp::ProcessFactory::create_process(std::unique_ptr&& process_spec) const +{ + return std::make_unique(std::move(process_spec)); +} + +std::unique_ptr mp::ProcessFactory::create_process(const QString& command, + const QStringList& arguments) const +{ + return create_process(simple_process_spec(command, arguments)); +} diff --git a/src/platform/backends/shared/macos/process_factory.h b/src/platform/backends/shared/macos/process_factory.h new file mode 100644 index 0000000000..ad7e57d31e --- /dev/null +++ b/src/platform/backends/shared/macos/process_factory.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_PROCESS_FACTORY_H +#define MULTIPASS_PROCESS_FACTORY_H + +#include + +#include +#include + +#define MP_PROCFACTORY multipass::ProcessFactory::instance() + +namespace multipass +{ +class Process; + +class ProcessFactory : public Singleton +{ +public: + ProcessFactory(const Singleton::PrivatePass&); + + virtual std::unique_ptr create_process(std::unique_ptr&& process_spec) const; + std::unique_ptr create_process(const QString& command, const QStringList& = QStringList()) const; +}; + +} // namespace multipass + +#endif // MULTIPASS_PROCESS_FACTORY_H diff --git a/src/platform/backends/shared/windows/CMakeLists.txt b/src/platform/backends/shared/windows/CMakeLists.txt new file mode 100644 index 0000000000..ad480e8c9b --- /dev/null +++ b/src/platform/backends/shared/windows/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . + +set (CMAKE_AUTOMOC ON) +add_library(shared_win STATIC + aes.cpp + powershell.cpp + process_factory.cpp + smb_mount_handler.cpp) + +include_directories(shared_win + ..) + +target_link_libraries(shared_win + Qt6::Core + fmt::fmt-header-only + logger + OpenSSL::Crypto + sftp_client + utils) diff --git a/src/platform/backends/shared/windows/aes.cpp b/src/platform/backends/shared/windows/aes.cpp new file mode 100644 index 0000000000..1aa7a60805 --- /dev/null +++ b/src/platform/backends/shared/windows/aes.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "aes.h" + +#include + +#include + +namespace mp = multipass; + +using EVP_CIPHER_CTX_free_ptr = std::unique_ptr; + +namespace +{ +constexpr int key_size = 32; +constexpr int block_size = 16; +} // namespace + +mp::AES::AES(const Singleton::PrivatePass& pass) noexcept : Singleton::Singleton{pass} +{ +} + +int mp::AES::aes_256_key_size() const +{ + return key_size; +} + +int mp::AES::aes_256_block_size() const +{ + return block_size; +} + +std::string mp::AES::decrypt(const std::vector& key, + const std::vector& iv, + const std::string& encrypted_data) const +{ + EVP_CIPHER_CTX_free_ptr ctx(EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free); + if (!EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_cbc(), nullptr, key.data(), iv.data())) + throw std::runtime_error("EVP_DecryptInit_ex failed"); + + std::string decrypted_data; + decrypted_data.resize(encrypted_data.size()); + int out_len1 = (int)decrypted_data.size(); + + if (!EVP_DecryptUpdate(ctx.get(), + (uint8_t*)&decrypted_data[0], + &out_len1, + (const uint8_t*)&encrypted_data[0], + (int)encrypted_data.size())) + throw std::runtime_error("EVP_DecryptUpdate failed"); + + int out_len2 = (int)decrypted_data.size() - out_len1; + if (!EVP_DecryptFinal_ex(ctx.get(), (uint8_t*)&decrypted_data[0] + out_len1, &out_len2)) + throw std::runtime_error("EVP_DecryptFinal_ex failed"); + + decrypted_data.resize(out_len1 + out_len2); + return decrypted_data; +} + +std::string mp::AES::encrypt(const std::vector& key, + const std::vector& iv, + const std::string& data) const +{ + EVP_CIPHER_CTX_free_ptr ctx(EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free); + if (!EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_cbc(), nullptr, key.data(), iv.data())) + throw std::runtime_error("EVP_EncryptInit_ex failed"); + + std::string encrypted_data; + encrypted_data.resize(data.size() + iv.size()); + int out_len1 = (int)encrypted_data.size(); + + if (!EVP_EncryptUpdate(ctx.get(), + (uint8_t*)&encrypted_data[0], + &out_len1, + (const uint8_t*)&data[0], + (int)data.size())) + throw std::runtime_error("EVP_EncryptUpdate failed"); + + int out_len2 = (int)encrypted_data.size() - out_len1; + if (!EVP_EncryptFinal_ex(ctx.get(), (uint8_t*)&encrypted_data[0] + out_len1, &out_len2)) + throw std::runtime_error("EVP_EncryptFinal_ex failed"); + + encrypted_data.resize(out_len1 + out_len2); + return encrypted_data; +} diff --git a/src/platform/backends/shared/windows/aes.h b/src/platform/backends/shared/windows/aes.h new file mode 100644 index 0000000000..a41fba5df0 --- /dev/null +++ b/src/platform/backends/shared/windows/aes.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_AES_H +#define MULTIPASS_AES_H + +#include + +#include +#include + +#define MP_AES multipass::AES::instance() + +namespace multipass +{ +class AES : public Singleton +{ +public: + AES(const Singleton::PrivatePass&) noexcept; + + virtual int aes_256_key_size() const; + virtual int aes_256_block_size() const; + virtual std::string decrypt(const std::vector& key, + const std::vector& iv, + const std::string& encrypted_data) const; + virtual std::string encrypt(const std::vector& key, + const std::vector& iv, + const std::string& data) const; +}; +} // namespace multipass + +#endif // MULTIPASS_AES_H diff --git a/src/platform/backends/shared/windows/powershell.cpp b/src/platform/backends/shared/windows/powershell.cpp new file mode 100644 index 0000000000..22a281be55 --- /dev/null +++ b/src/platform/backends/shared/windows/powershell.cpp @@ -0,0 +1,233 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "powershell.h" + +#include +#include +#include +#include + +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; +namespace mpu = multipass::utils; + +namespace +{ +constexpr auto ps_cmd = "powershell.exe"; +const auto default_args = QStringList{"-NoProfile", "-NoExit", "-Command", "-"}; + +void setup_powershell(mp::Process* power_shell, const std::string& name) +{ + mpl::log(mpl::Level::trace, name, fmt::format("PowerShell arguments: {}", power_shell->arguments().join(", "))); + mpl::log(mpl::Level::trace, name, fmt::format("PowerShell working dir '{}'", power_shell->working_directory())); + mpl::log(mpl::Level::trace, name, fmt::format("PowerShell program '{}'", power_shell->program())); + + // handle stdout and stderr separately + power_shell->set_process_channel_mode(QProcess::SeparateChannels); + + QObject::connect(power_shell, &mp::Process::state_changed, [&name, power_shell](QProcess::ProcessState newState) { + mpl::log(mpl::Level::trace, + name, + fmt::format("[{}] PowerShell state changed to {}", + power_shell->process_id(), + mpu::qenum_to_qstring(newState))); + }); + + QObject::connect(power_shell, &mp::Process::error_occurred, [&name, power_shell](QProcess::ProcessError error) { + mpl::log( + mpl::Level::debug, + name, + fmt::format("[{}] PowerShell error occurred {}", power_shell->process_id(), mpu::qenum_to_qstring(error))); + }); + + QObject::connect(power_shell, &mp::Process::finished, [&name, power_shell](mp::ProcessState state) { + const auto pid = power_shell->process_id(); + if (state.completed_successfully()) + mpl::log(mpl::Level::debug, name, fmt::format("[{}] PowerShell finished successfully", pid)); + else + mpl::log(mpl::Level::warning, + name, + fmt::format("[{}] PowerShell finished abnormally: {}", pid, state.failure_message())); + }); +} + +const auto to_bare_csv_str = QStringLiteral("| ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 " + "| foreach { $_ -replace '^\"|\"$|\"(?=,)|(?<=,)\"','' }"); /* this last bit + removes surrounding quotes; may be replaced with "-UseQuotes Never" in + powershell 7 */ + +} // namespace + +const QStringList mp::PowerShell::Snippets::expand_property{"|", "Select-Object", "-ExpandProperty"}; +const QStringList mp::PowerShell::Snippets::to_bare_csv = to_bare_csv_str.split(' ', Qt::SkipEmptyParts); + +mp::PowerShell::PowerShell(const std::string& name) + : powershell_proc{MP_PROCFACTORY.create_process(ps_cmd, default_args)}, name(name) +{ + setup_powershell(powershell_proc.get(), this->name); + + powershell_proc->start(); +} + +mp::PowerShell::~PowerShell() +{ + if (!write("Exit\n") || !powershell_proc->wait_for_finished()) + { + auto error = powershell_proc->error_string(); + auto msg = fmt::format("[{}] Failed to exit PowerShell gracefully", powershell_proc->process_id()); + if (!error.isEmpty()) + msg = fmt::format("{}: {}", msg, error); + + mpl::log(mpl::Level::warning, name, msg); + powershell_proc->kill(); + } +} + +void mp::PowerShell::easy_run(const QStringList& args, std::string&& error_msg) +{ + if (!run(args)) + throw std::runtime_error{std::move(error_msg)}; +} + +bool mp::PowerShell::run(const QStringList& args, QString* output, QString* output_err, bool whisper) +{ + QString default_output, default_output_err; + output = output ? output : &default_output; + output_err = output_err ? output_err : &default_output_err; + + QString echo_cmdlet = QString("echo \"%1\" $?\n").arg(output_end_marker); + bool cmdlet_code{false}; + auto pid = powershell_proc->process_id(); + auto notice_level = whisper ? mpl::Level::trace : mpl::Level::debug; + const auto cmdlet = args.join(" "); + + mpl::log(notice_level, name, fmt::format("[{}] Cmdlet: '{}'", pid, cmdlet)); + + // Have Powershell echo a unique string to differentiate between the cmdlet + // output and the cmdlet exit status output + if (write((cmdlet + "\n").toUtf8()) && write(echo_cmdlet.toUtf8())) + { + QString powershell_stdout; + QString powershell_stderr; + auto cmdlet_exit_found{false}; + while (!cmdlet_exit_found) + { + powershell_proc->wait_for_ready_read(); // ignore timeouts - will just loop back if no output + + // Read stdout and stderr separately + powershell_stdout.append(powershell_proc->read_all_standard_output()); + powershell_stderr.append(powershell_proc->read_all_standard_error()); + + *output_err = powershell_stderr; + + if (powershell_stdout.contains(output_end_marker)) + { + auto parsed_output = powershell_stdout.split(output_end_marker); + if (parsed_output.size() == 2) + { + // Be sure the exit status is fully read from output + // Exit status can only be "True" or "False" + auto exit_value = parsed_output.at(1); + if (exit_value.contains("True")) + { + cmdlet_code = true; + cmdlet_exit_found = true; + } + else if (exit_value.contains("False")) + { + cmdlet_code = false; + cmdlet_exit_found = true; + } + + // Get the actual cmdlet's output + if (cmdlet_exit_found) + { + *output = parsed_output.at(0).trimmed(); + mpl::log(mpl::Level::trace, name, output->toStdString()); + } + } + } + } + + // Always log stderr, even if command succeeded + if (!powershell_stderr.isEmpty()) + mpl::log(mpl::Level::warning, name, fmt::format("[{}] stderr: {}", pid, powershell_stderr)); + } + + // Log final output and status + mpl::log(mpl::Level::trace, name, fmt::format("[{}] Output: {}", pid, *output)); + mpl::log(notice_level, name, fmt::format("[{}] Cmdlet exit status is '{}'", pid, cmdlet_code)); + + return cmdlet_code; +} + +bool mp::PowerShell::exec(const QStringList& args, const std::string& name, QString* output, QString* output_err) +{ + QString default_output{}, default_output_err{}; + output = output ? output : &default_output; + output_err = output_err ? output_err : &default_output_err; + + auto power_shell = MP_PROCFACTORY.create_process(ps_cmd, args); + setup_powershell(power_shell.get(), name); + + QObject::connect(power_shell.get(), &mp::Process::ready_read_standard_output, [output, &power_shell]() { + *output += power_shell->read_all_standard_output(); + }); + + QObject::connect(power_shell.get(), &mp::Process::ready_read_standard_error, [&output_err, &power_shell]() { + *output_err += power_shell->read_all_standard_error(); + }); + + power_shell->start(); + auto wait_result = power_shell->wait_for_finished(/* msecs = */ 60000); + auto pid = power_shell->process_id(); // This is 0 iff the process didn't even start + + if (!wait_result) + { + auto msg = pid ? fmt::format("[{}] Process failed; {}", pid, power_shell->error_string()) + : "Could not start PowerShell"; + mpl::log(mpl::Level::warning, name, msg); + } + + *output = output->trimmed(); + + // Log stderr if any + if (!output_err->isEmpty()) + mpl::log(mpl::Level::warning, name, fmt::format("[{}] stderr: {}", pid, *output_err)); + + mpl::log(mpl::Level::trace, name, fmt::format("[{}] Output:\n{}", pid, *output)); + + return wait_result && power_shell->process_state().completed_successfully(); +} + +bool mp::PowerShell::write(const QByteArray& data) +{ + if (auto written = powershell_proc->write(data); written < data.size()) + { + auto msg = fmt::format("[{}] Failed to send input data '{}'.", powershell_proc->process_id(), data); + if (written > 0) + msg = fmt::format("{}. Only the first {} bytes were written", msg, written); + + mpl::log(mpl::Level::warning, name, msg); + return false; + } + + return true; +} diff --git a/src/platform/backends/shared/windows/powershell.h b/src/platform/backends/shared/windows/powershell.h new file mode 100644 index 0000000000..9c87db3b1a --- /dev/null +++ b/src/platform/backends/shared/windows/powershell.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_POWERSHELL_H +#define MULTIPASS_POWERSHELL_H + +#include + +#include + +#include +#include + +namespace multipass +{ +namespace test +{ +class PowerShellTestHelper; // fwd declaration, to befriend below +} + +class PowerShell +{ +public: + explicit PowerShell(const std::string& name); + ~PowerShell(); + + // require rvalue ref for the error msg, to avoid confusion with output parameter in run + void easy_run(const QStringList& args, std::string&& error_msg); // signals failures with exception + bool run(const QStringList& args, QString* output = nullptr, QString* output_err = nullptr, bool whisper = false); + + static bool exec(const QStringList& args, + const std::string& name, + QString* output = nullptr, + QString* output_err = nullptr); + + struct Snippets + { + static const QStringList expand_property; + static const QStringList to_bare_csv; + }; + +private: + friend class multipass::test::PowerShellTestHelper; + bool write(const QByteArray& data); + + std::unique_ptr powershell_proc; + const std::string name; + + inline static const QString output_end_marker = "cmdlet status is"; +}; +} // namespace multipass + +#endif // MULTIPASS_POWERSHELL_H diff --git a/src/platform/backends/shared/windows/process_factory.cpp b/src/platform/backends/shared/windows/process_factory.cpp new file mode 100644 index 0000000000..1706237cb6 --- /dev/null +++ b/src/platform/backends/shared/windows/process_factory.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "process_factory.h" +#include +#include +#include +#include + +#include +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; + +namespace +{ +const auto category = "process"; + +// Returns the last Win32 error, in string format. Returns an empty string if there is no error. +std::string GetLastErrorAsString() +{ + // Get the error message, if any. + DWORD errorMessageID = ::GetLastError(); + if (errorMessageID == 0) + return std::string(); // No error message has been recorded + + LPSTR messageBuffer = nullptr; + size_t size = + FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + errorMessageID, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)&messageBuffer, + 0, + NULL); + + std::string message(messageBuffer, size); + + // Free the buffer. + LocalFree(messageBuffer); + + return message; +} + +} // namespace + +namespace +{ +class WindowsProcess : public mp::BasicProcess +{ +public: + WindowsProcess(HANDLE ghJob, std::unique_ptr&& process_spec) + : mp::BasicProcess(std::move(process_spec)) + { + if (ghJob != nullptr) + { + connect(&process, &QProcess::started, [this, ghJob]() { + auto pid = process.processId(); + if (0 == AssignProcessToJobObject(ghJob, OpenProcess(PROCESS_ALL_ACCESS, 0, pid))) + { + mpl::log( + mpl::Level::warning, + ::category, + fmt::format("Could not AssignProcessToObject the spawned process: {}", GetLastErrorAsString())); + } + }); + } + + process.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* args) { + // The CREATE_NEW_PROCESS_GROUP flag allows process to have its own signal + // group separate from the parent. This way, the parent can send signals + // e.g. (Ctrl-C) to the child for a graceful shutdown without having to + // disrupt other children, or the parent process itself if it has a signal + // handler. The constant is to avoid including windows.h & winbase.h. + constexpr static unsigned long kCreateNewProcessGroup = 0x00000200; + args->flags |= kCreateNewProcessGroup; + }); + } + + void terminate() override + { + // Let's send the child a signal first to let it gracefully terminate. + // the process_id() is also the console group id. + if (GenerateConsoleCtrlEvent(/*dwCtrlEvent*/ CTRL_BREAK_EVENT, /*dwProcessGroupId*/ process_id()) == 0) + { + // failed to Ctrl+C, resort to killing + mpl::warn(::category, + "Failed to Ctrl+Break, falling back to kill(). Error was: {}", + GetLastErrorAsString()); + kill(); + } + } +}; +} // namespace + +mp::ProcessFactory::ProcessFactory(const Singleton::PrivatePass& pass) + : Singleton::Singleton{pass}, ghJob{nullptr} +{ + /* Create a Windows Job Object that will ensure all child processes are collected on stop */ + BOOL alreadyInProcessJob; + bool bSuccess = IsProcessInJob(GetCurrentProcess(), nullptr, &alreadyInProcessJob); + if (!bSuccess) + { + mpl::log(mpl::Level::warning, + ::category, + fmt::format("IsProcessInJob failed: error {}", GetLastErrorAsString())); + } + if (alreadyInProcessJob) + { + mpl::log(mpl::Level::warning, + ::category, + "Process is already in Job, spawned processes will not be cleaned up"); + } + + ghJob = CreateJobObject(nullptr, nullptr); + if (ghJob == nullptr) + { + mpl::log(mpl::Level::warning, + ::category, + fmt::format("Could not create job object: {}", GetLastErrorAsString())); + } + else + { + JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = {0}; + + // Configure all child processes associated with the job to terminate when the + jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + if (0 == SetInformationJobObject(ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) + { + mpl::log(mpl::Level::warning, + ::category, + fmt::format("Could not SetInformationJobObject: {}", GetLastErrorAsString())); + } + } +} + +std::unique_ptr mp::ProcessFactory::create_process(std::unique_ptr&& process_spec) const +{ + return std::make_unique<::WindowsProcess>(ghJob, std::move(process_spec)); +} + +std::unique_ptr mp::ProcessFactory::create_process(const QString& command, + const QStringList& arguments) const +{ + return create_process(simple_process_spec(command, arguments)); +} diff --git a/src/platform/backends/shared/windows/process_factory.h b/src/platform/backends/shared/windows/process_factory.h new file mode 100644 index 0000000000..15279913ed --- /dev/null +++ b/src/platform/backends/shared/windows/process_factory.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_WINDOWS_PROCESS_FACTORY_H +#define MULTIPASS_WINDOWS_PROCESS_FACTORY_H + +#include + +#include +#include + +#include + +#define MP_PROCFACTORY multipass::ProcessFactory::instance() + +namespace multipass +{ +class Process; + +class ProcessFactory : public Singleton +{ +public: + ProcessFactory(const Singleton::PrivatePass&); + + virtual std::unique_ptr create_process(std::unique_ptr&& process_spec) const; + std::unique_ptr create_process(const QString& command, const QStringList& = QStringList()) const; + +private: + HANDLE ghJob; +}; + +} // namespace multipass +#endif // MULTIPASS_WINDOWS_PROCESS_FACTORY_H diff --git a/src/platform/backends/shared/windows/smb_mount_handler.cpp b/src/platform/backends/shared/windows/smb_mount_handler.cpp new file mode 100644 index 0000000000..524c369649 --- /dev/null +++ b/src/platform/backends/shared/windows/smb_mount_handler.cpp @@ -0,0 +1,351 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "smb_mount_handler.h" +#include "aes.h" + +#include "powershell.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#pragma comment(lib, "Netapi32.lib") + +namespace mp = multipass; +namespace mpl = multipass::logging; + +namespace +{ +constexpr auto category = "smb-mount-handler"; + +void install_cifs_for(const std::string& name, mp::SSHSession& session, const std::chrono::milliseconds& timeout) +try +{ + mpl::log(mpl::Level::info, category, fmt::format("Installing cifs-utils in '{}'", name)); + + auto proc = session.exec("sudo apt-get update && sudo apt-get install -y cifs-utils"); + if (proc.exit_code(timeout) != 0) + { + auto error_msg = proc.read_std_error(); + mpl::log(mpl::Level::warning, + category, + fmt::format("Failed to install 'cifs-utils', error message: '{}'", mp::utils::trim_end(error_msg))); + throw std::runtime_error("Failed to install cifs-utils"); + } +} +catch (const mp::ExitlessSSHProcessException&) +{ + mpl::log(mpl::Level::info, category, fmt::format("Timeout while installing 'cifs-utils' in '{}'", name)); + throw std::runtime_error("Timeout installing cifs-utils"); +} +} // namespace + +namespace multipass +{ +bool SmbManager::share_exists(const QString& share_name) const +{ + PSHARE_INFO_0 share_info; + auto wide_share_name = share_name.toStdWString(); + const auto res = NetShareGetInfo(nullptr, wide_share_name.data(), 0, (LPBYTE*)&share_info); + NetApiBufferFree(share_info); + return res == 0; +} + +void SmbManager::create_share(const QString& share_name, const QString& source, const QString& user) const +{ + if (share_exists(share_name)) + return; + + // TODO: I tried to use the proper Windows API to get ACL permissions for the user being passed in, but + // alas, the API is very convoluted. At some point, another attempt should be made to use the proper API though... + QString user_access_output; + const auto user_access_res = PowerShell::exec( + {QString{"(Get-Acl '%1').Access | ?{($_.IdentityReference -match '%2') -and ($_.FileSystemRights " + "-eq 'FullControl')}"} + .arg(source, user)}, + "Get ACLs", + &user_access_output); + + if (!user_access_res || user_access_output.isEmpty()) + throw std::runtime_error{fmt::format("cannot access \"{}\"", source)}; + + std::wstring remark = L"Multipass mount share"; + auto wide_share_name = share_name.toStdWString(); + auto wide_source = source.toStdWString(); + + DWORD parm_err = 0; + SHARE_INFO_2 share_info; + share_info.shi2_netname = wide_share_name.data(); + share_info.shi2_remark = remark.data(); + share_info.shi2_type = STYPE_DISKTREE; + share_info.shi2_permissions = 0; + share_info.shi2_max_uses = -1; + share_info.shi2_current_uses = 0; + share_info.shi2_path = wide_source.data(); + share_info.shi2_passwd = nullptr; + + if (NetShareAdd(nullptr, 2, (LPBYTE)&share_info, &parm_err) != 0) + throw std::runtime_error{fmt::format("failed creating SMB share for \"{}\": {}", source, parm_err)}; +} + +void SmbManager::remove_share(const QString& share_name) const +{ + auto wide_share_name = share_name.toStdWString(); + if (share_exists(share_name) && NetShareDel(nullptr, wide_share_name.data(), 0) != 0) + mpl::log(mpl::Level::warning, category, fmt::format("Failed removing SMB share \"{}\"'", share_name)); +} + +void SmbMountHandler::remove_cred_files(const QString& user_id) +{ + auto iv_filename = user_id + ".iv"; + auto cred_filename = user_id + ".cifs"; + + QFile cred_file{cred_dir.filePath(cred_filename)}; + QFile iv_file{cred_dir.filePath(iv_filename)}; + + MP_FILEOPS.remove(cred_file); + MP_FILEOPS.remove(iv_file); +} + +void SmbMountHandler::encrypt_credentials_to_file(const QString& cred_filename, + const QString& iv_filename, + const std::string& data) +try +{ + const auto iv = MP_UTILS.random_bytes(MP_AES.aes_256_block_size()); + const auto encrypted_data = MP_AES.encrypt(enc_key, iv, data); + + MP_UTILS.make_file_with_content(cred_dir.filePath(iv_filename).toStdString(), {iv.begin(), iv.end()}); + MP_UTILS.make_file_with_content(cred_dir.filePath(cred_filename).toStdString(), + {encrypted_data.begin(), encrypted_data.end()}); + + mpl::log(mpl::Level::info, category, "Successfully encrypted credentials"); +} +catch (const std::exception& e) +{ + mpl::log(mpl::Level::warning, category, fmt::format("Failed to encrypt credentials to file: {}", e.what())); +} + +std::string SmbMountHandler::decrypt_credentials_from_file(const QString& cred_filename, const QString& iv_filename) +try +{ + const auto encrypted_data = MP_UTILS.contents_of(cred_dir.filePath(cred_filename)); + const auto iv_str = MP_UTILS.contents_of(cred_dir.filePath(iv_filename)); + std::vector iv{iv_str.begin(), iv_str.end()}; + iv.resize(MP_AES.aes_256_block_size()); + + auto decrypted_data = MP_AES.decrypt(enc_key, iv, encrypted_data); + mpl::log(mpl::Level::info, category, "Successfully decrypted credentials"); + return decrypted_data; +} +catch (const std::exception& e) +{ + mpl::log(mpl::Level::warning, category, fmt::format("Failed to decrypt credentials from file: {}", e.what())); + return {}; +} + +SmbMountHandler::SmbMountHandler(VirtualMachine* vm, + const SSHKeyProvider* ssh_key_provider, + const std::string& target, + VMMount mount_spec, + const mp::Path& cred_dir, + const SmbManager& smb_manager) + : MountHandler{vm, ssh_key_provider, std::move(mount_spec), target}, + source{QString::fromStdString(get_mount_spec().get_source_path())}, + // share name must be unique and 80 chars max + share_name{ + QString("%1_%2:%3") + .arg(MP_UTILS.make_uuid(target), QString::fromStdString(vm->vm_name), QString::fromStdString(target)) + .left(80)}, + cred_dir{cred_dir}, + smb_manager{&smb_manager} +{ + mpl::log(mpl::Level::info, + category, + fmt::format("Initializing native mount {} => {} in '{}'", source, target, vm->vm_name)); + + auto data_location{MP_PLATFORM.multipass_storage_location() + "\\data"}; + auto enc_key_dir_path{MP_UTILS.make_dir(data_location, "enc-keys")}; + auto key_file = QDir{enc_key_dir_path}.filePath("aes.key"); + + if (MP_FILEOPS.exists(QFile{key_file})) + { + const auto key_str = MP_UTILS.contents_of(key_file); + enc_key.assign(key_str.begin(), key_str.end()); + enc_key.resize(MP_AES.aes_256_key_size()); + } + else + { + enc_key = MP_UTILS.random_bytes(MP_AES.aes_256_key_size()); + MP_UTILS.make_file_with_content(key_file.toStdString(), {enc_key.begin(), enc_key.end()}); + mpl::log(mpl::Level::info, category, "Successfully generated new encryption key"); + } +} + +bool SmbMountHandler::is_active() +try +{ + return active && smb_manager->share_exists(share_name) && + !SSHSession{vm->ssh_hostname(), vm->ssh_port(), vm->ssh_username(), *ssh_key_provider} + .exec(fmt::format("findmnt --type cifs | grep '{} //{}/{}'", + target, + QHostInfo::localHostName(), + share_name)) + .exit_code(); +} +catch (const std::exception& e) +{ + mpl::log(mpl::Level::warning, + category, + fmt::format("Failed checking SSHFS mount \"{}\" in instance '{}': {}", target, vm->vm_name, e.what())); + return false; +} + +void SmbMountHandler::activate_impl(ServerVariant server, std::chrono::milliseconds timeout) +try +{ + SSHSession session{vm->ssh_hostname(), vm->ssh_port(), vm->ssh_username(), *ssh_key_provider}; + + const auto username = MP_PLATFORM.get_username(); + const auto user_id = MP_UTILS.make_uuid(username.toStdString()); + const auto iv_filename = user_id + ".iv"; + const auto cred_filename = user_id + ".cifs"; + + if (session.exec("dpkg-query --show --showformat='${db:Status-Status}' cifs-utils").read_std_output() != + "installed") + { + auto visitor = [](auto server) { + if (server) + { + auto reply = make_reply_from_server(server); + reply.set_reply_message("Enabling support for mounting"); + server->Write(reply); + } + }; + + std::visit(visitor, server); + install_cifs_for(vm->vm_name, session, timeout); + } + + const auto rtext = decrypt_credentials_from_file(cred_filename, iv_filename); + const auto tokens = mp::utils::split(rtext, "="); + auto password = tokens.size() == 2 ? tokens.at(1) : ""; + + if (password.empty()) + { + password = std::visit( + [](auto&& server) { + auto reply = server ? make_reply_from_server(server) + : throw std::runtime_error("Cannot get password without client connection"); + + reply.set_password_requested(true); + if (!server->Write(reply)) + throw std::runtime_error("Cannot request password from client. Aborting..."); + + auto request = make_request_from_server(server); + if (!server->Read(&request)) + throw std::runtime_error("Cannot get password from client. Aborting..."); + + return request.password(); + }, + server); + + if (password.empty()) + throw std::runtime_error("A password is required for SMB mounts."); + + encrypt_credentials_to_file(cred_filename, iv_filename, fmt::format("password={}", password)); + } + + smb_manager->create_share(share_name, source, username); + + // The following mkdir in the instance will be replaced with refactored code + auto mkdir_proc = session.exec(fmt::format("mkdir -p {}", target)); + if (mkdir_proc.exit_code() != 0) + throw std::runtime_error( + fmt::format("Cannot create \"{}\" in instance '{}': {}", target, vm->vm_name, mkdir_proc.read_std_error())); + + auto smb_creds = fmt::format("username={}\npassword={}", username, password); + const std::string credentials_path{"/tmp/.smb_credentials"}; + auto sftp_client = MP_SFTPUTILS.make_SFTPClient(vm->ssh_hostname(), + vm->ssh_port(), + vm->ssh_username(), + ssh_key_provider->private_key_as_base64()); + std::istringstream creds_stringstream(smb_creds); + sftp_client->from_cin(creds_stringstream, credentials_path, false); + + auto hostname = QHostInfo::localHostName(); + auto mount_proc = + session.exec(fmt::format("sudo mount -t cifs //{}/{} {} -o credentials={},uid=$(id -u),gid=$(id -g)", + hostname, + share_name, + target, + credentials_path)); + auto mount_exit_code = mount_proc.exit_code(); + auto mount_error_msg = mount_proc.read_std_error(); + + auto rm_proc = session.exec(fmt::format("sudo rm {}", credentials_path)); + if (rm_proc.exit_code() != 0) + mpl::log(mpl::Level::warning, + category, + fmt::format("Failed deleting credentials file in \'{}\': {}", vm->vm_name, rm_proc.read_std_error())); + + if (mount_exit_code != 0) + { + remove_cred_files(user_id); + throw std::runtime_error(fmt::format("Error: {}", mount_error_msg)); + } +} +catch (...) +{ + smb_manager->remove_share(share_name); + throw; +} + +void SmbMountHandler::deactivate_impl(bool force) +try +{ + mpl::log(mpl::Level::info, + category, + fmt::format("Stopping native mount \"{}\" in instance '{}'", target, vm->vm_name)); + SSHSession session{vm->ssh_hostname(), vm->ssh_port(), vm->ssh_username(), *ssh_key_provider}; + MP_UTILS.run_in_ssh_session(session, + fmt::format("if mountpoint -q {0}; then sudo umount {0}; else true; fi", target)); + smb_manager->remove_share(share_name); +} +catch (const std::exception& e) +{ + if (!force) + throw; + mpl::log(mpl::Level::warning, + category, + fmt::format("Failed to gracefully stop mount \"{}\" in instance '{}': {}", target, vm->vm_name, e.what())); + smb_manager->remove_share(share_name); +} + +SmbMountHandler::~SmbMountHandler() +{ + deactivate(/*force=*/true); +} +} // namespace multipass diff --git a/src/platform/backends/shared/windows/smb_mount_handler.h b/src/platform/backends/shared/windows/smb_mount_handler.h new file mode 100644 index 0000000000..df49b6f969 --- /dev/null +++ b/src/platform/backends/shared/windows/smb_mount_handler.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_SMB_MOUNT_HANDLER_H +#define MULTIPASS_SMB_MOUNT_HANDLER_H + +#include +#include + +#include + +namespace multipass +{ +struct SmbManager +{ + virtual bool share_exists(const QString& share_name) const; + virtual void create_share(const QString& share_name, const QString& source, const QString& user) const; + virtual void remove_share(const QString& share_name) const; +}; + +class SmbMountHandler : public MountHandler +{ +public: + SmbMountHandler(VirtualMachine* vm, + const SSHKeyProvider* ssh_key_provider, + const std::string& target, + VMMount mount_spec, + const multipass::Path& cred_dir, + const SmbManager& smb_manager); + ~SmbMountHandler() override; + + void activate_impl(ServerVariant server, std::chrono::milliseconds timeout) override; + void deactivate_impl(bool force) override; + bool is_active() override; + +private: + QString source; + QString share_name; + QDir cred_dir; + std::vector enc_key; + const SmbManager* smb_manager; + + void remove_cred_files(const QString& user_id); + void encrypt_credentials_to_file(const QString& cred_filename, + const QString& iv_filename, + const std::string& ptext); + std::string decrypt_credentials_from_file(const QString& cred_filename, const QString& iv_filename); +}; +} // namespace multipass +#endif // MULTIPASS_SMB_MOUNT_HANDLER_H diff --git a/src/platform/backends/virtualbox/CMakeLists.txt b/src/platform/backends/virtualbox/CMakeLists.txt new file mode 100644 index 0000000000..b95fbcd71d --- /dev/null +++ b/src/platform/backends/virtualbox/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . +# + +add_library(virtualbox_backend STATIC + virtualbox_snapshot.cpp + virtualbox_virtual_machine.cpp + virtualbox_virtual_machine_factory.cpp + ${CMAKE_SOURCE_DIR}/include/multipass/process/basic_process.h + ${CMAKE_SOURCE_DIR}/include/multipass/process/process.h) + +target_link_libraries(virtualbox_backend + Qt6::Core + fmt::fmt-header-only + ip_address + logger + process + ssh + utils + yaml) diff --git a/src/platform/backends/virtualbox/virtualbox_snapshot.cpp b/src/platform/backends/virtualbox/virtualbox_snapshot.cpp new file mode 100644 index 0000000000..6d3aa95b8a --- /dev/null +++ b/src/platform/backends/virtualbox/virtualbox_snapshot.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "virtualbox_snapshot.h" +#include "virtualbox_virtual_machine.h" + +#include + +namespace mp = multipass; +namespace mpu = multipass::utils; + +namespace +{ +bool snapshot_exists(const QString& vm_name, const QString& snapshot_id) +{ + return mpu::process_log_on_error("VBoxManage", + {"snapshot", vm_name, "showvminfo", snapshot_id}, + "Could not find snapshot: {}", + vm_name); +} + +void require_unique_id(const QString& vm_name, const QString& snapshot_id) +{ + if (snapshot_exists(vm_name, snapshot_id)) + throw std::runtime_error{ + fmt::format("A snapshot with ID {} already exists for {} in VirtualBox", snapshot_id, vm_name)}; +} +} // namespace + +mp::VirtualBoxSnapshot::VirtualBoxSnapshot(const std::string& name, + const std::string& comment, + const std::string& cloud_init_instance_id, + std::shared_ptr parent, + const QString& vm_name, + const VMSpecs& specs, + VirtualBoxVirtualMachine& vm) + : BaseSnapshot{name, comment, cloud_init_instance_id, std::move(parent), specs, vm}, vm_name{vm_name} +{ +} + +mp::VirtualBoxSnapshot::VirtualBoxSnapshot(const QString& filename, + VirtualBoxVirtualMachine& vm, + const VirtualMachineDescription& desc) + : BaseSnapshot{filename, vm, desc}, vm_name{QString::fromStdString(desc.vm_name)} +{ +} + +void multipass::VirtualBoxSnapshot::capture_impl() +{ + const auto& id = get_id(); + require_unique_id(vm_name, id); + + const auto description_arg = QString{"--description=%1: %2"}.arg(get_name().c_str(), get_comment().c_str()); + mpu::process_throw_on_error("VBoxManage", + {"snapshot", vm_name, "take", id, description_arg}, + "Could not take snapshot: {}", + vm_name); +} + +void multipass::VirtualBoxSnapshot::erase_impl() +{ + const auto& id = get_id(); + if (snapshot_exists(vm_name, id)) + mpu::process_throw_on_error("VBoxManage", + {"snapshot", vm_name, "delete", get_id()}, + "Could not delete snapshot: {}", + vm_name); + else + mpl::log(mpl::Level::warning, + vm_name.toStdString(), + fmt::format("Could not find underlying VirtualBox snapshot for \"{}\". Ignoring...", get_name())); +} + +void multipass::VirtualBoxSnapshot::apply_impl() +{ + mpu::process_throw_on_error("VBoxManage", + {"snapshot", vm_name, "restore", get_id()}, + "Could not restore snapshot: {}", + vm_name); +} diff --git a/src/platform/backends/virtualbox/virtualbox_snapshot.h b/src/platform/backends/virtualbox/virtualbox_snapshot.h new file mode 100644 index 0000000000..87a116a762 --- /dev/null +++ b/src/platform/backends/virtualbox/virtualbox_snapshot.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_VIRTUALBOX_SNAPSHOT_H +#define MULTIPASS_VIRTUALBOX_SNAPSHOT_H + +#include + +namespace multipass +{ +class VirtualBoxVirtualMachine; +class VirtualMachineDescription; + +class VirtualBoxSnapshot : public BaseSnapshot +{ +public: + VirtualBoxSnapshot(const std::string& name, + const std::string& comment, + const std::string& cloud_init_instance_id, + std::shared_ptr parent, + const QString& vm_name, + const VMSpecs& specs, + VirtualBoxVirtualMachine& vm); + VirtualBoxSnapshot(const QString& filename, VirtualBoxVirtualMachine& vm, const VirtualMachineDescription& desc); + +protected: + void capture_impl() override; + void erase_impl() override; + void apply_impl() override; + +private: + const QString vm_name; +}; + +} // namespace multipass +#endif // MULTIPASS_VIRTUALBOX_SNAPSHOT_H diff --git a/src/platform/backends/virtualbox/virtualbox_virtual_machine.cpp b/src/platform/backends/virtualbox/virtualbox_virtual_machine.cpp new file mode 100644 index 0000000000..52d6d192a3 --- /dev/null +++ b/src/platform/backends/virtualbox/virtualbox_virtual_machine.cpp @@ -0,0 +1,603 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "virtualbox_virtual_machine.h" +#include "virtualbox_snapshot.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; +namespace mpu = multipass::utils; +namespace fs = std::filesystem; + +namespace +{ +auto instance_state_for(const QString& name) +{ + QRegularExpression vmstate_re("VMState=\"([a-z]+)\""); + + QProcess vminfo; + vminfo.start("VBoxManage", {"showvminfo", name, "--machinereadable"}); + auto success = vminfo.waitForFinished(); + if (!success || vminfo.exitStatus() != QProcess::NormalExit) + { + throw std::runtime_error(fmt::format("Failed to run VBoxManage: {}", vminfo.errorString().toStdString())); + } + auto vminfo_output = QString::fromUtf8(vminfo.readAllStandardOutput()); + auto vmstate_match = vmstate_re.match(vminfo_output); + + if (vmstate_match.hasMatch()) + { + auto state = vmstate_match.captured(1); + + mpl::log(mpl::Level::trace, name.toStdString(), fmt::format("Got VMState: {}", state.toStdString())); + + if (state == "starting" || state == "restoring") + { + return mp::VirtualMachine::State::starting; + } + else if (state == "running" || state == "paused" || state == "onlinesnapshotting" || state == "stopping") + { + return mp::VirtualMachine::State::running; + } + else if (state == "saving") + { + return mp::VirtualMachine::State::suspending; + } + else if (state == "saved") + { + return mp::VirtualMachine::State::suspended; + } + else if (state == "poweroff" || state == "aborted") + { + return mp::VirtualMachine::State::stopped; + } + + mpl::log(mpl::Level::error, + name.toStdString(), + fmt::format("Failed to parse instance state: {}", vmstate_match.captured().toStdString())); + } + else if (vminfo.exitCode() == 0) + { + mpl::log(mpl::Level::error, + name.toStdString(), + fmt::format("Failed to parse info output: {}", vminfo_output.toStdString())); + } + + return mp::VirtualMachine::State::unknown; +} + +QStringList extra_net_args(int index, const mp::NetworkInterface& net) +{ + QString iface_index_str = QString::number(index); + + return QStringList{"--nic" + iface_index_str, + "bridged", + "--nictype" + iface_index_str, + "virtio", + "--macaddress" + iface_index_str, + QString::fromStdString(net.mac_address).remove(':'), + "--bridgeadapter" + iface_index_str, + QString::fromStdString(mp::platform::reinterpret_interface_id(net.id))}; +} + +QStringList networking_arguments(const mp::VirtualMachineDescription& desc) +{ + QStringList arguments{"--nic1", + "nat", + "--nictype1", + "virtio", + "--macaddress1", + QString::fromStdString(desc.default_mac_address).remove(':')}; + + for (size_t i = 0; i < desc.extra_interfaces.size(); ++i) + { + arguments += extra_net_args(i + 2, desc.extra_interfaces[i]); + } + + return arguments; +} + +QStringList modifyvm_arguments(const mp::VirtualMachineDescription& desc, const QString& vm_name) +{ + const QString& tmp = MP_STDPATHS.writableLocation(mp::StandardPaths::TempLocation); + const QString& log_file = QString("%1/%2.log").arg(tmp).arg(vm_name); + QStringList modify_arguments{"modifyvm", vm_name, + "--cpus", QString::number(desc.num_cores), + "--memory", QString::number(desc.mem_size.in_megabytes()), + "--boot1", "disk", + "--boot2", "none", + "--boot3", "none", + "--boot4", "none", + "--acpi", "on", + "--firmware", "efi", + "--rtcuseutc", "on", + "--audio", "none", + "--uart1", "0x3f8", + "4", "--uartmode1", + "file", log_file}; + modify_arguments += networking_arguments(desc); + + return modify_arguments; +} + +void update_mac_addresses_of_network_adapters(const mp::VirtualMachineDescription& desc, const QString& vm_name) +{ + mpu::process_log_on_error( + "VBoxManage", + {"modifyvm", vm_name, "--macaddress1", QString::fromStdString(desc.default_mac_address).remove(':')}, + "Could not update the default network adapter address of: {}", + vm_name); + for (size_t i = 0; i < desc.extra_interfaces.size(); ++i) + { + const size_t current_adapter_number = i + 2; + mpu::process_log_on_error("VBoxManage", + {"modifyvm", + vm_name, + "--macaddress" + QString::number(current_adapter_number), + QString::fromStdString(desc.extra_interfaces[i].mac_address).remove(':')}, + "Could not update the network adapter address of: {}", + vm_name); + } +} + +} // namespace + +mp::VirtualBoxVirtualMachine::VirtualBoxVirtualMachine(const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const mp::Path& instance_dir_qstr) + : VirtualBoxVirtualMachine(desc, monitor, key_provider, instance_dir_qstr, true) +{ + if (desc.extra_interfaces.size() > 7) + { + throw std::runtime_error("VirtualBox does not support more than 8 interfaces"); + } + + if (!mpu::process_log_on_error("VBoxManage", + {"showvminfo", name, "--machinereadable"}, + "Could not get instance info: {}", + name)) + { + const fs::path instances_dir = fs::path{instance_dir_qstr.toStdString()}.parent_path(); + mpu::process_throw_on_error("VBoxManage", + {"createvm", + "--name", + name, + "--basefolder", + QString::fromStdString(instances_dir.string()), + "--ostype", + "ubuntu_64", + "--register"}, + "Could not create VM: {}", + name); + + mpu::process_throw_on_error("VBoxManage", modifyvm_arguments(desc, name), "Could not modify VM: {}", name); + + mpu::process_throw_on_error("VBoxManage", + {"storagectl", name, "--add", "sata", "--name", "SATA_0", "--portcount", "2"}, + "Could not modify VM: {}", + name); + + mpu::process_throw_on_error("VBoxManage", + {"storageattach", + name, + "--storagectl", + "SATA_0", + "--port", + "0", + "--device", + "0", + "--type", + "hdd", + "--medium", + desc.image.image_path}, + "Could not storageattach HDD: {}", + name); + + mpu::process_throw_on_error("VBoxManage", + {"storageattach", + name, + "--storagectl", + "SATA_0", + "--port", + "1", + "--device", + "0", + "--type", + "dvddrive", + "--medium", + desc.cloud_init_iso}, + "Could not storageattach DVD: {}", + name); + + state = State::off; + } + else + { + state = instance_state_for(name); + } +} + +mp::VirtualBoxVirtualMachine::VirtualBoxVirtualMachine(const std::string& source_vm_name, + const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& dest_instance_dir) + : VirtualBoxVirtualMachine(desc, monitor, key_provider, dest_instance_dir, true) +{ + const fs::path instances_dir = fs::path{dest_instance_dir.toStdString()}.parent_path(); + + // 1. clone the vm with certain options and mode. --mode value is all, which copies all snapshot history and it + // always includes the base disk whereas machine mode only copies the current differencing disk when the vm is + // snapshoted. --options has keepdisknames and keepallmacs, keepdisknames means disk file name will be kept instead + // of using .vdi, keepallmacs implies that the mac addresses of network adapters will not be generated by + // virtualbox because they will be overwritten by multipass generated mac addresses anyway. + mpu::process_throw_on_error("VBoxManage", + {"clonevm", + QString::fromStdString(source_vm_name), + "--name", + name, + "--register", + "--basefolder", + QString::fromStdString(instances_dir.string()), + "--mode", + "all", + "--options", + "keepdisknames,keepallmacs"}, + "Could not clone VM: {}", + QString::fromStdString(source_vm_name)); + + // 2. remove the old cloud-init file from the vm + mpu::process_throw_on_error("VBoxManage", + {"storageattach", + name, + "--storagectl", + "SATA_0", + "--port", + "1", + "--device", + "0", + "--type", + "dvddrive", + "--medium", + "none"}, + "Could not remove the cloud-init file from: {}", + name); + // 3. attach the new cloud-file to the vm + mpu::process_throw_on_error("VBoxManage", + {"storageattach", + name, + "--storagectl", + "SATA_0", + "--port", + "1", + "--device", + "0", + "--type", + "dvddrive", + "--medium", + desc.cloud_init_iso}, + "Could not attach the cloud-init file to: {}", + name); + // 4. reset the mac addresses of vm to the spec addres + update_mac_addresses_of_network_adapters(desc, name); + remove_snapshots_from_backend(); +} + +mp::VirtualBoxVirtualMachine::VirtualBoxVirtualMachine(const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const mp::Path& instance_dir_qstr, + bool /*is_internal*/) + : BaseVirtualMachine{desc.vm_name, key_provider, instance_dir_qstr}, + desc{desc}, + name{QString::fromStdString(desc.vm_name)}, + monitor{&monitor} +{ +} + +mp::VirtualBoxVirtualMachine::~VirtualBoxVirtualMachine() +{ + top_catch_all(vm_name, [this]() { + update_suspend_status = false; + + if (current_state() == State::running) + suspend(); + }); +} + +void mp::VirtualBoxVirtualMachine::start() +{ + state = State::starting; + update_state(); + + mpu::process_throw_on_error("VBoxManage", {"startvm", name, "--type", "headless"}, "Could not start VM: {}", name); +} + +void mp::VirtualBoxVirtualMachine::shutdown(ShutdownPolicy shutdown_policy) +{ + std::unique_lock lock{state_mutex}; + const auto present_state = current_state(); + + try + { + check_state_for_shutdown(shutdown_policy); + } + catch (const VMStateIdempotentException& e) + { + mpl::log(mpl::Level::info, vm_name, e.what()); + return; + } + + drop_ssh_session(); + + if (shutdown_policy == ShutdownPolicy::Poweroff) + { + mpl::log(mpl::Level::info, vm_name, "Forcing shutdown"); + // virtualbox needs the discardstate command to shutdown in the suspend state, it discards the saved state of + // the vm, which is akin to resetting it to the off state without a proper shutdown process + if (state == State::suspended) + { + mpu::process_throw_on_error("VBoxManage", {"discardstate", name}, "Could not power VM off: {}", name); + } + else + { + mpu::process_throw_on_error("VBoxManage", + {"controlvm", name, "poweroff"}, + "Could not power VM off: {}", + name); + } + } + else + { + mpu::process_throw_on_error("VBoxManage", + {"controlvm", name, "acpipowerbutton"}, + "Could not stop VM: {}", + name); + } + + state = State::stopped; + + // If it wasn't force, we wouldn't be here + if (present_state == State::starting) + { + state_wait.wait(lock, [this] { return shutdown_while_starting; }); + } + + port = std::nullopt; + update_state(); +} + +void mp::VirtualBoxVirtualMachine::suspend() +{ + auto present_state = instance_state_for(name); + + if (present_state == State::running || present_state == State::delayed_shutdown) + { + mpu::process_throw_on_error("VBoxManage", {"controlvm", name, "savestate"}, "Could not suspend VM: {}", name); + + drop_ssh_session(); + if (update_suspend_status) + { + state = State::suspended; + update_state(); + } + } + else if (present_state == State::stopped) + { + mpl::log(mpl::Level::info, vm_name, fmt::format("Ignoring suspend issued while stopped")); + } + + monitor->on_suspend(); +} + +mp::VirtualMachine::State mp::VirtualBoxVirtualMachine::current_state() +{ + auto present_state = instance_state_for(name); + + if ((state == State::delayed_shutdown && present_state == State::running) || state == State::starting) + return state; + + state = present_state; + if (state == State::suspended || state == State::suspending) + drop_ssh_session(); + + return state; +} + +int mp::VirtualBoxVirtualMachine::ssh_port() +{ + if (!port) + { + QTcpServer socket; + if (!socket.listen(QHostAddress("127.0.0.1"))) + { + throw std::runtime_error( + fmt::format("Could not find a port available to listen on: {}", socket.errorString())); + } + + mpu::process_log_on_error("VBoxManage", + {"controlvm", name, "natpf1", "delete", "ssh"}, + "Could not delete SSH port forwarding: {}", + name); + + mpu::process_throw_on_error( + "VBoxManage", + {"controlvm", name, "natpf1", QString::fromStdString(fmt::format("ssh,tcp,,{},,22", socket.serverPort()))}, + "Could not add SSH port forwarding: {}", + name); + + port.emplace(socket.serverPort()); + } + return *port; +} + +void mp::VirtualBoxVirtualMachine::ensure_vm_is_running() +{ + auto is_vm_running = [this] { return state != State::stopped; }; + + mp::backend::ensure_vm_is_running_for(this, is_vm_running, "Instance shutdown during start"); +} + +void mp::VirtualBoxVirtualMachine::update_state() +{ + monitor->persist_state_for(vm_name, state); +} + +std::string mp::VirtualBoxVirtualMachine::ssh_hostname(std::chrono::milliseconds /*timeout*/) +{ + return "127.0.0.1"; +} + +std::string mp::VirtualBoxVirtualMachine::ssh_username() +{ + return desc.ssh_username; +} + +std::string mp::VirtualBoxVirtualMachine::management_ipv4() +{ + return "N/A"; +} + +std::vector mp::VirtualBoxVirtualMachine::get_all_ipv4() +{ + using namespace std; + + auto all_ipv4 = BaseVirtualMachine::get_all_ipv4(); + all_ipv4.erase(remove(begin(all_ipv4), end(all_ipv4), "10.0.2.15"), end(all_ipv4)); + + return all_ipv4; +} + +std::string mp::VirtualBoxVirtualMachine::ipv6() +{ + return {}; +} + +void mp::VirtualBoxVirtualMachine::update_cpus(int num_cores) +{ + assert(num_cores > 0); + + mpu::process_throw_on_error("VBoxManage", + {"modifyvm", name, "--cpus", QString::number(num_cores)}, + "Could not update CPUs: {}", + name); +} + +void mp::VirtualBoxVirtualMachine::resize_memory(const MemorySize& new_size) +{ + assert(new_size.in_bytes() > 0); + + mpu::process_throw_on_error("VBoxManage", + {"modifyvm", name, "--memory", QString::number(new_size.in_megabytes())}, + "Could not update memory: {}", + name); +} + +void mp::VirtualBoxVirtualMachine::resize_disk(const MemorySize& new_size) +{ + assert(new_size.in_bytes() > 0); + + mpu::process_throw_on_error( + "VBoxManage", + {"modifyhd", desc.image.image_path, "--resizebyte", QString::number(new_size.in_bytes())}, + "Could not resize image: {}", + name); +} + +void mp::VirtualBoxVirtualMachine::add_network_interface(int index, + const std::string& default_mac_addr, + const NetworkInterface& extra_interface) +{ + auto arguments = QStringList{"modifyvm", name} + extra_net_args(index + 2, extra_interface); + + mpu::process_throw_on_error("VBoxManage", arguments, "Could not add network interface: {}", name); + add_extra_interface_to_instance_cloud_init(default_mac_addr, extra_interface); +} + +void mp::VirtualBoxVirtualMachine::remove_snapshots_from_backend() const +{ + // Name: @s1 (UUID: 93a6a9ba-9223-4b77-a8cf-80213439aaae) + // Description: snapshot1: + // Name: @s2 (UUID: 871d6b85-d11c-4969-8433-c4a143dba4d8) + // Description: snapshot2: + // Name: @s3 (UUID: c4800b70-1e50-4b84-b430-1856437fe967) + // Description: snapshot3: + + const QString snap_shot_list = + QString::fromStdString(MP_UTILS.run_cmd_for_output("VBoxManage", {"snapshot", name, "list"})); + const QRegularExpression uuid_key_value_regex(R"(UUID: ([\w-]+))"); + QRegularExpressionMatchIterator iter = uuid_key_value_regex.globalMatch(snap_shot_list); + + QStringList uuid_list; + while (iter.hasNext()) + { + QRegularExpressionMatch match = iter.next(); + // captured(0) is the entire match which contains UUID key and value, captured(1) is the first regex capture + // group which is the value of the UUID only + uuid_list.append(match.captured(1)); + } + + for (const auto& uuid : uuid_list) + { + mpu::process_throw_on_error("VBoxManage", + {"snapshot", name, "delete", uuid}, + "Could not delete snapshot: {}", + name); + } +} + +auto multipass::VirtualBoxVirtualMachine::make_specific_snapshot(const QString& filename) -> std::shared_ptr +{ + return std::make_shared(filename, *this, desc); +} + +auto multipass::VirtualBoxVirtualMachine::make_specific_snapshot(const std::string& snapshot_name, + const std::string& comment, + const std::string& instance_id, + const multipass::VMSpecs& specs, + std::shared_ptr parent) + -> std::shared_ptr +{ + return std::make_shared(snapshot_name, + comment, + instance_id, + std::move(parent), + name, + specs, + *this); +} diff --git a/src/platform/backends/virtualbox/virtualbox_virtual_machine.h b/src/platform/backends/virtualbox/virtualbox_virtual_machine.h new file mode 100644 index 0000000000..b8fc12cfff --- /dev/null +++ b/src/platform/backends/virtualbox/virtualbox_virtual_machine.h @@ -0,0 +1,99 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_VIRTUALBOX_VIRTUAL_MACHINE_H +#define MULTIPASS_VIRTUALBOX_VIRTUAL_MACHINE_H + +#include + +#include +#include +#include + +#include + +namespace multipass +{ +class PowerShell; +class SSHKeyProvider; +class VirtualMachineDescription; +class VMStatusMonitor; + +class VirtualBoxVirtualMachine final : public BaseVirtualMachine +{ +public: + VirtualBoxVirtualMachine(const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& instance_dir); + // Contruct the vm based on the source virtual machine + VirtualBoxVirtualMachine(const std::string& source_vm_name, + const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& dest_instance_dir); + ~VirtualBoxVirtualMachine() override; + + void start() override; + void shutdown(ShutdownPolicy shutdown_policy = ShutdownPolicy::Powerdown) override; + void suspend() override; + State current_state() override; + int ssh_port() override; + std::string ssh_hostname(std::chrono::milliseconds timeout) override; + std::string ssh_username() override; + std::string management_ipv4() override; + std::vector get_all_ipv4() override; + std::string ipv6() override; + void ensure_vm_is_running() override; + void update_state() override; + void update_cpus(int num_cores) override; + void resize_memory(const MemorySize& new_size) override; + void resize_disk(const MemorySize& new_size) override; + void add_network_interface(int index, + const std::string& default_mac_addr, + const NetworkInterface& extra_interface) override; + +protected: + void require_snapshots_support() const override; + std::shared_ptr make_specific_snapshot(const QString& filename) override; + std::shared_ptr make_specific_snapshot(const std::string& snapshot_name, + const std::string& comment, + const std::string& instance_id, + const VMSpecs& specs, + std::shared_ptr parent) override; + +private: + VirtualBoxVirtualMachine(const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider, + const Path& instance_dir_qstr, + bool is_internal); + void remove_snapshots_from_backend() const; + + VirtualMachineDescription desc; // TODO we should probably keep the VMDescription in the base VM class instead + const QString name; + std::optional port; + VMStatusMonitor* monitor; + bool update_suspend_status{true}; +}; +} // namespace multipass + +inline void multipass::VirtualBoxVirtualMachine::require_snapshots_support() const +{ +} + +#endif // MULTIPASS_VIRTUALBOX_VIRTUAL_MACHINE_H diff --git a/src/platform/backends/virtualbox/virtualbox_virtual_machine_factory.cpp b/src/platform/backends/virtualbox/virtualbox_virtual_machine_factory.cpp new file mode 100644 index 0000000000..f868819a9b --- /dev/null +++ b/src/platform/backends/virtualbox/virtualbox_virtual_machine_factory.cpp @@ -0,0 +1,261 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "virtualbox_virtual_machine_factory.h" +#include "virtualbox_virtual_machine.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; +namespace mpu = multipass::utils; + +namespace +{ + +struct VirtualBoxNetworkException : public std::runtime_error +{ + using std::runtime_error::runtime_error; +}; + +mp::NetworkInterfaceInfo list_vbox_network(const QString& vbox_iface_info, + const std::map& platform_info) +{ + // The Mac version of VBoxManage is the only one which gives us the field for some devices. + const auto name_pattern = QStringLiteral("^Name: +(?.+?)(: (?.+))?\r?$"); + const auto type_pattern = QStringLiteral("^MediumType: +(?\\w+)\r?$"); + const auto wireless_pattern = QStringLiteral("^Wireless: +(?\\w+)\r?$"); + + const auto regexp_options = QRegularExpression::MultilineOption; + + const auto name_regexp = QRegularExpression{name_pattern, regexp_options}; + const auto type_regexp = QRegularExpression{type_pattern, regexp_options}; + const auto wireless_regexp = QRegularExpression{wireless_pattern, regexp_options}; + + const auto name_match = name_regexp.match(vbox_iface_info); + + // If the name does not match, we know there is something strange in the input, so we throw. If it matches, we + // see if the interface is useful for us and the platform recognizes it; otherwise we throw as well. + if (name_match.hasMatch()) + { + std::string ifname = name_match.captured("name").toStdString(); + + auto platform_if_info = platform_info.find(ifname); + + // In Windows, VirtualBox lists interfaces using their description as name. + if (platform_if_info == platform_info.end()) // This will be true until VirtualBox fixes the issue. + { + auto comp_fun = [&ifname](const auto& keyval) { return keyval.second.description == ifname; }; + platform_if_info = std::find_if(platform_info.begin(), platform_info.end(), comp_fun); + } + + if (platform_if_info != platform_info.end()) + { + std::string iftype = type_regexp.match(vbox_iface_info).captured("type").toStdString(); + std::string ifdescription = name_match.captured("description").toStdString(); + bool wireless = wireless_regexp.match(vbox_iface_info).captured("wireless") == "Yes"; + + mp::NetworkInterfaceInfo if_info = platform_if_info->second; + + if (ifdescription.empty()) + { + // Use the OS information about the interface + return mp::NetworkInterfaceInfo{if_info.id, + wireless ? "wifi" : (if_info.type.empty() ? "unknown" : if_info.type), + if_info.description}; + } + else + { + // Get the information from the VBoxManage output. + iftype = wireless ? "wifi" : (ifdescription.compare(0, 11, "Thunderbolt") ? iftype : "thunderbolt"); + + return mp::NetworkInterfaceInfo{if_info.id, iftype, ifdescription}; + } + } + + throw VirtualBoxNetworkException(fmt::format("Network interface \"{}\" not recognized by platform", ifname)); + } + + throw std::runtime_error(fmt::format("Unexpected data from VBoxManage: \"{}\"", vbox_iface_info)); +} +} // namespace + +mp::VirtualBoxVirtualMachineFactory::VirtualBoxVirtualMachineFactory(const mp::Path& data_dir) + : BaseVirtualMachineFactory(MP_UTILS.derive_instances_dir(data_dir, get_backend_directory_name(), instances_subdir)) +{ +} + +auto mp::VirtualBoxVirtualMachineFactory::create_virtual_machine(const VirtualMachineDescription& desc, + const SSHKeyProvider& key_provider, + VMStatusMonitor& monitor) -> mp::VirtualMachine::UPtr +{ + return std::make_unique(desc, + monitor, + key_provider, + get_instance_directory(desc.vm_name)); +} + +void mp::VirtualBoxVirtualMachineFactory::remove_resources_for_impl(const std::string& name) +{ + QRegularExpression cloudinit_re("\"SATA_0-1-0\"=\"(?!emptydrive)(.+)\""); + + QProcess vminfo; + vminfo.start("VBoxManage", {"showvminfo", QString::fromStdString(name), "--machinereadable"}); + vminfo.waitForFinished(); + auto vminfo_output = QString::fromUtf8(vminfo.readAllStandardOutput()); + + auto cloudinit_match = cloudinit_re.match(vminfo_output); + + mpu::process_log_on_error("VBoxManage", + {"controlvm", QString::fromStdString(name), "poweroff"}, + "Could not power off VM: {}", + QString::fromStdString(name), + mpl::Level::warning); + mpu::process_log_on_error("VBoxManage", + {"unregistervm", QString::fromStdString(name), "--delete"}, + "Could not unregister VM: {}", + QString::fromStdString(name), + mpl::Level::error); + + if (cloudinit_match.hasMatch()) + { + mpu::process_log_on_error("VBoxManage", + {"closemedium", "dvd", cloudinit_match.captured(1)}, + "Could not unregister cloud-init medium: {}", + QString::fromStdString(name), + mpl::Level::warning); + } + else + { + mpl::log(mpl::Level::warning, name, "Could not find the cloud-init ISO path for removal."); + } +} + +mp::VMImage mp::VirtualBoxVirtualMachineFactory::prepare_source_image(const mp::VMImage& source_image) +{ + QFileInfo source_file{source_image.image_path}; + auto vdi_file = QString("%1/%2.vdi").arg(source_file.path()).arg(source_file.completeBaseName()); + + QStringList convert_args({"convert", "-O", "vdi", source_image.image_path, vdi_file}); + + auto qemuimg_convert_spec = + std::make_unique(convert_args, source_image.image_path, vdi_file); + auto qemuimg_convert_process = mp::platform::make_process(std::move(qemuimg_convert_spec)); + + auto process_state = qemuimg_convert_process->execute(mp::image_resize_timeout); + if (!process_state.completed_successfully()) + { + throw std::runtime_error(fmt::format("Conversion of image to VDI failed ({}) with the following output:\n{}", + process_state.failure_message(), + qemuimg_convert_process->read_all_standard_error())); + } + + if (!QFile::exists(vdi_file)) + { + throw std::runtime_error("vdi image file is missing"); + } + + auto prepared_image = source_image; + prepared_image.image_path = vdi_file; + return prepared_image; +} + +void mp::VirtualBoxVirtualMachineFactory::prepare_instance_image(const mp::VMImage& instance_image, + const VirtualMachineDescription& desc) +{ + // Need to generate a new medium UUID + mpu::process_throw_on_error("VBoxManage", + {"internalcommands", "sethduuid", instance_image.image_path}, + "Could not generate a new UUID: {}"); + + mpu::process_log_on_error( + "VBoxManage", + {"modifyhd", instance_image.image_path, "--resize", QString::number(desc.disk_space.in_megabytes())}, + "Could not resize image: {}", + QString::fromStdString(desc.vm_name), + mpl::Level::warning); +} + +void mp::VirtualBoxVirtualMachineFactory::hypervisor_health_check() +{ +} + +auto mp::VirtualBoxVirtualMachineFactory::networks() const -> std::vector +{ + std::string log_category("virtualbox factory"); + + std::vector networks; + + // Get the list of all the interfaces which can be bridged by VirtualBox. + QString ifs_info = QString::fromStdString(MP_UTILS.run_cmd_for_output("VBoxManage", {"list", "-l", "bridgedifs"})); + + // List to store the output of the query command; each element corresponds to one interface. + QStringList if_list(ifs_info.split(QRegularExpression("\r?\n\r?\n"), Qt::SkipEmptyParts)); + + mpl::log(mpl::Level::info, log_category, fmt::format("VirtualBox found {} interface(s)", if_list.size())); + + std::map platform_ifs_info = MP_PLATFORM.get_network_interfaces_info(); + + for (const auto& iface : if_list) + { + try + { + auto interface_info = list_vbox_network(iface, platform_ifs_info); + + networks.push_back(interface_info); + } + catch (VirtualBoxNetworkException& e) + { + mpl::log(mpl::Level::warning, log_category, e.what()); + } + } + + return networks; +} + +void multipass::VirtualBoxVirtualMachineFactory::prepare_networking(std::vector& vector) +{ + // Nothing to do here, VirtualBox takes host interfaces directly +} + +mp::VirtualMachine::UPtr mp::VirtualBoxVirtualMachineFactory::clone_vm_impl( + const std::string& src_name, + const multipass::VMSpecs& /*src_spec*/, + const VirtualMachineDescription& dest_vm_desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider) +{ + return std::make_unique(src_name, + dest_vm_desc, + monitor, + key_provider, + get_instance_directory(dest_vm_desc.vm_name)); +} diff --git a/src/platform/backends/virtualbox/virtualbox_virtual_machine_factory.h b/src/platform/backends/virtualbox/virtualbox_virtual_machine_factory.h new file mode 100644 index 0000000000..e54cd87d6d --- /dev/null +++ b/src/platform/backends/virtualbox/virtualbox_virtual_machine_factory.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_VIRTUALBOX_VIRTUAL_MACHINE_FACTORY_H +#define MULTIPASS_VIRTUALBOX_VIRTUAL_MACHINE_FACTORY_H + +#include + +namespace multipass +{ +class VirtualBoxVirtualMachineFactory final : public BaseVirtualMachineFactory +{ +public: + explicit VirtualBoxVirtualMachineFactory(const Path& data_dir); + + VirtualMachine::UPtr create_virtual_machine(const VirtualMachineDescription& desc, + const SSHKeyProvider& key_provider, + VMStatusMonitor& monitor) override; + + void prepare_networking(std::vector& vector) override; + VMImage prepare_source_image(const VMImage& source_image) override; + void prepare_instance_image(const VMImage& instance_image, const VirtualMachineDescription& desc) override; + void hypervisor_health_check() override; + QString get_backend_directory_name() const override + { + return "virtualbox"; + }; + QString get_backend_version_string() const override + { + return "virtualbox"; + }; + std::vector networks() const override; + void require_clone_support() const override + { + } + void require_snapshots_support() const override; + +protected: + void remove_resources_for_impl(const std::string& name) override; + +private: + VirtualMachine::UPtr clone_vm_impl(const std::string& source_vm_name, + const multipass::VMSpecs& src_vm_specs, + const VirtualMachineDescription& desc, + VMStatusMonitor& monitor, + const SSHKeyProvider& key_provider) override; +}; +} // namespace multipass + +inline void multipass::VirtualBoxVirtualMachineFactory::require_snapshots_support() const +{ +} + +#endif // MULTIPASS_VIRTUALBOX_VIRTUAL_MACHINE_FACTORY_H diff --git a/src/platform/client/CMakeLists.txt b/src/platform/client/CMakeLists.txt index 61295ef617..a9736ebbe4 100644 --- a/src/platform/client/CMakeLists.txt +++ b/src/platform/client/CMakeLists.txt @@ -12,7 +12,18 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +if(MSVC) +add_library(client_platform STATIC + client_platform_windows.cpp) +elseif(APPLE) +add_library(client_platform STATIC + client_platform.cpp) +else() add_library(client_platform STATIC client_platform.cpp) +endif() -target_link_libraries(client_platform Qt6::Core) +target_link_libraries(client_platform + Qt6::Core + console + fmt::fmt-header-only) diff --git a/src/platform/client/client_platform_windows.cpp b/src/platform/client/client_platform_windows.cpp new file mode 100644 index 0000000000..48bc12af51 --- /dev/null +++ b/src/platform/client/client_platform_windows.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +namespace mp = multipass; +namespace mcp = multipass::cli::platform; + +void mcp::parse_transfer_entry(const QString& entry, QString& path, QString& instance_name) +{ + auto colon_count = entry.count(":"); + + switch (colon_count) + { + case 0: + path = entry; + break; + case 1: + if (!QFileInfo::exists(entry) && !entry.contains(":\\")) + { + instance_name = entry.section(":", 0, 0); + path = entry.section(":", 1); + } + else + { + path = entry; + } + break; + } +} + +int mcp::getuid() +{ + return mp::no_id_info_available; +} + +int mcp::getgid() +{ + return mp::no_id_info_available; +} + +std::string mcp::Platform::get_password(mp::Terminal* term) const +{ + if (term->is_live()) + { + mp::PassphrasePrompter prompter(term); + auto password = prompter.prompt("Please enter your user password to allow Windows mounts"); + + return password; + } + + return {}; +} + +void mcp::Platform::enable_ansi_escape_chars() const +{ + HANDLE handleOut = GetStdHandle(STD_OUTPUT_HANDLE); + DWORD consoleMode; + + GetConsoleMode(handleOut, &consoleMode); + consoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; + SetConsoleMode(handleOut, consoleMode); +} diff --git a/src/platform/console/CMakeLists.txt b/src/platform/console/CMakeLists.txt index 15721d6b19..b13400d8c1 100644 --- a/src/platform/console/CMakeLists.txt +++ b/src/platform/console/CMakeLists.txt @@ -16,9 +16,18 @@ function(add_target TARGET_NAME) add_library(${TARGET_NAME} STATIC console.cpp - terminal.cpp - unix_console.cpp - unix_terminal.cpp) + terminal.cpp) + + if(MSVC) + target_sources(${TARGET_NAME} PRIVATE + windows_console.cpp + windows_terminal.cpp) + qt6_disable_unicode_defines(${TARGET_NAME}) + else() + target_sources(${TARGET_NAME} PRIVATE + unix_console.cpp + unix_terminal.cpp) + endif() target_link_libraries(${TARGET_NAME} client_platform diff --git a/src/platform/console/console.cpp b/src/platform/console/console.cpp index 8616f7122d..3280099dc1 100644 --- a/src/platform/console/console.cpp +++ b/src/platform/console/console.cpp @@ -18,12 +18,19 @@ #include #include +#ifdef MULTIPASS_PLATFORM_WINDOWS +#include "windows_console.h" +#include "windows_terminal.h" +#else #include "unix_console.h" #include "unix_terminal.h" +#endif namespace mp = multipass; void mp::Console::setup_environment() { +#ifndef MULTIPASS_PLATFORM_WINDOWS UnixConsole::setup_environment(); +#endif } diff --git a/src/platform/console/terminal.cpp b/src/platform/console/terminal.cpp index 2c877be664..2ea9f2bd0a 100644 --- a/src/platform/console/terminal.cpp +++ b/src/platform/console/terminal.cpp @@ -15,8 +15,14 @@ * */ -#include "unix_terminal.h" #include + +#ifdef MULTIPASS_PLATFORM_WINDOWS +#include "windows_terminal.h" +#else +#include "unix_terminal.h" +#endif + #include namespace mp = multipass; @@ -33,7 +39,11 @@ namespace mp = multipass; mp::Terminal::UPtr mp::Terminal::make_terminal() { +#ifdef MULTIPASS_PLATFORM_WINDOWS + return std::make_unique(); +#else return std::make_unique(); +#endif } std::istream& mp::Terminal::cin() diff --git a/src/platform/console/windows_console.cpp b/src/platform/console/windows_console.cpp new file mode 100644 index 0000000000..3720b6b52e --- /dev/null +++ b/src/platform/console/windows_console.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "windows_console.h" +#include "windows_terminal.h" + +#include +#include +#include + +#include + +#include +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; +namespace mcp = multipass::cli::platform; + +namespace +{ +constexpr auto category = "windows console"; +constexpr auto term_type = "xterm-256color"; +constexpr auto chunk = 4096u; + +mp::Console::ConsoleGeometry get_console_size(HANDLE handle) +{ + CONSOLE_SCREEN_BUFFER_INFO sb_info; + GetConsoleScreenBufferInfo(handle, &sb_info); + SHORT columns = sb_info.srWindow.Right - sb_info.srWindow.Left + 1; + SHORT rows = sb_info.srWindow.Bottom - sb_info.srWindow.Top + 1; + + return {rows, columns}; // rows come before columns in ConsoleGeometry (unlike libssh) +} +} // namespace + +mp::WindowsConsole::WindowsConsole(ssh_channel channel, WindowsTerminal* term) + : interactive{term->cout_is_live()}, + input_handle{term->cin_handle()}, + output_handle{term->cout_handle()}, + error_handle{term->cerr_handle()}, + channel{channel}, + session_socket_fd{ssh_get_fd(ssh_channel_get_session(channel))}, + last_geometry{get_console_size(output_handle)} +{ + setup_console(); +} + +void mp::WindowsConsole::setup_console() +{ + if (interactive) + { + GetConsoleMode(input_handle, &console_input_mode); + SetConsoleMode(input_handle, + console_input_mode & ~ENABLE_PROCESSED_INPUT & ~ENABLE_LINE_INPUT | + ENABLE_VIRTUAL_TERMINAL_INPUT | ENABLE_WINDOW_INPUT); + GetConsoleMode(output_handle, &console_output_mode); + SetConsoleMode(output_handle, console_output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING); + + ssh_channel_request_pty_size(channel, term_type, last_geometry.columns, last_geometry.rows); + } +} + +void mp::WindowsConsole::read_console() +{ + std::array input_records; + DWORD num_records_read = 0; + std::basic_string text_buffer; + text_buffer.reserve(chunk); + + if (!ReadConsoleInput(input_handle, input_records.data(), chunk, &num_records_read)) + { + mpl::log(mpl::Level::warning, + category, + fmt::format("Could not read console input; error code: {}", GetLastError())); + } + else + { + + for (auto i = 0u; i < num_records_read; ++i) + { + switch (input_records[i].EventType) + { + case KEY_EVENT: + { + const auto& key_event = input_records[i].Event.KeyEvent; + if (auto chr = key_event.uChar.AsciiChar; + key_event.bKeyDown && chr) // some keys yield null char (e.g. alt) + text_buffer.append(key_event.wRepeatCount, chr); + } + break; + case WINDOW_BUFFER_SIZE_EVENT: // The size in this event isn't reliable in WT (see microsoft/terminal#281) + update_ssh_pty_size(); // We obtain it ourselves to update here + break; + default: + break; // ignore + } + } + + std::lock_guard lock(ssh_mutex); + ssh_channel_write(channel, + text_buffer.data(), + static_cast(text_buffer.size() * sizeof(text_buffer.front()))); + } +} + +void mp::WindowsConsole::write_console() +{ + DWORD write; + std::array buffer; + int num_bytes{0}; + fd_set read_set; + HANDLE current_handle{output_handle}; + + FD_ZERO(&read_set); + FD_SET(session_socket_fd, &read_set); + + if (select(0, &read_set, nullptr, nullptr, nullptr) < 1) + return; + + { + std::lock_guard lock(ssh_mutex); + num_bytes = ssh_channel_read_nonblocking(channel, buffer.data(), chunk, 0); + + // Try reading from stderr if nothing is returned from stdout + if (num_bytes == 0) + { + num_bytes = ssh_channel_read_nonblocking(channel, buffer.data(), chunk, 1); + current_handle = error_handle; + } + } + + if (num_bytes < 1) + { + // Force the channel to close if EOF is detected from the channel_read + if (num_bytes == SSH_EOF) + ssh_channel_close(channel); + + return; + } + + DWORD mode; + if (GetConsoleMode(current_handle, &mode)) + { + WriteConsole(current_handle, buffer.data(), num_bytes, &write, nullptr); + } + else + { + WriteFile(current_handle, buffer.data(), num_bytes, &write, nullptr); + } +} + +void mp::WindowsConsole::exit_console() +{ + restore_console(); + FreeConsole(); +} + +void mp::WindowsConsole::restore_console() +{ + if (interactive) + { + SetConsoleMode(input_handle, console_input_mode); + SetConsoleMode(output_handle, console_output_mode); + } +} + +void mp::WindowsConsole::update_ssh_pty_size() +{ + auto [rows, columns] = get_console_size(output_handle); + + if (last_geometry.columns != columns || last_geometry.rows != rows) + { + last_geometry.columns = columns; + last_geometry.rows = rows; + std::lock_guard lock(ssh_mutex); + ssh_channel_change_pty_size(channel, columns, rows); + } +} diff --git a/src/platform/console/windows_console.h b/src/platform/console/windows_console.h new file mode 100644 index 0000000000..f44d0f8437 --- /dev/null +++ b/src/platform/console/windows_console.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_WINDOWS_CONSOLE_H +#define MULTIPASS_WINDOWS_CONSOLE_H + +#include + +#include + +#include +#include + +#include + +namespace multipass +{ +class WindowsTerminal; + +class WindowsConsole final : public Console +{ +public: + WindowsConsole(ssh_channel channel, WindowsTerminal* term); + + void read_console() override; + void write_console() override; + void exit_console() override; + +private: + void setup_console(); + void restore_console(); + void update_ssh_pty_size(); + + bool interactive{false}; + HANDLE input_handle; + HANDLE output_handle; + HANDLE error_handle; + DWORD console_input_mode; + DWORD console_output_mode; + ssh_channel channel; + socket_t session_socket_fd; + ConsoleGeometry last_geometry; + mutable std::mutex ssh_mutex; +}; +} // namespace multipass +#endif // MULTIPASS_WINDOWS_CONSOLE_H diff --git a/src/platform/console/windows_terminal.cpp b/src/platform/console/windows_terminal.cpp new file mode 100644 index 0000000000..b0a8721a04 --- /dev/null +++ b/src/platform/console/windows_terminal.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "windows_terminal.h" + +#include "windows_console.h" + +#include +#include +#include + +namespace mp = multipass; + +mp::WindowsTerminal::WindowsTerminal() : input_code_page{GetConsoleCP()}, output_code_page{GetConsoleOutputCP()} +{ + SetConsoleCP(CP_UTF8); + SetConsoleOutputCP(CP_UTF8); +} + +mp::WindowsTerminal::~WindowsTerminal() +{ + SetConsoleCP(input_code_page); + SetConsoleOutputCP(output_code_page); +} + +HANDLE mp::WindowsTerminal::cin_handle() const +{ + return GetStdHandle(STD_INPUT_HANDLE); +} + +bool mp::WindowsTerminal::cin_is_live() const +{ + // GetConsoleMode will fail if cin is not a console. If it does not fail, we check if cin can receive input. + DWORD mode; + return GetConsoleMode(cin_handle(), &mode) && (mode & ENABLE_LINE_INPUT); +} + +HANDLE mp::WindowsTerminal::cout_handle() const +{ + return GetStdHandle(STD_OUTPUT_HANDLE); +} + +HANDLE mp::WindowsTerminal::cerr_handle() const +{ + return GetStdHandle(STD_ERROR_HANDLE); +} + +bool mp::WindowsTerminal::cout_is_live() const +{ + // GetConsoleScreenBufferInfo will fail if cout is not a console. Since there is nothing to check in the + // CONSOLE_SCREEN_BUFFER_INFO structure, we return the result of GetConsoleScreenBufferInfo. + CONSOLE_SCREEN_BUFFER_INFO csbi; + return GetConsoleScreenBufferInfo(cout_handle(), &csbi); +} + +std::string mp::WindowsTerminal::read_all_cin() +{ + _setmode(_fileno(stdin), _O_BINARY); + return mp::Terminal::read_all_cin(); +} + +void mp::WindowsTerminal::set_cin_echo(const bool enable) +{ + DWORD console_input_mode; + + GetConsoleMode(cin_handle(), &console_input_mode); + + if (!enable) + console_input_mode &= ~ENABLE_ECHO_INPUT; + else + console_input_mode |= ENABLE_ECHO_INPUT; + + SetConsoleMode(cin_handle(), console_input_mode); +} + +mp::WindowsTerminal::ConsolePtr mp::WindowsTerminal::make_console(ssh_channel channel) +{ + return std::make_unique(channel, this); +} diff --git a/src/platform/console/windows_terminal.h b/src/platform/console/windows_terminal.h new file mode 100644 index 0000000000..9f403ad41f --- /dev/null +++ b/src/platform/console/windows_terminal.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_WINDOWS_TERMINAL_H +#define MULTIPASS_WINDOWS_TERMINAL_H + +#include + +#include + +namespace multipass +{ +class WindowsTerminal : public Terminal +{ +public: + explicit WindowsTerminal(); + virtual ~WindowsTerminal(); + + HANDLE cin_handle() const; + HANDLE cout_handle() const; + HANDLE cerr_handle() const; + + bool cin_is_live() const override; + bool cout_is_live() const override; + + std::string read_all_cin() override; + void set_cin_echo(const bool enable) override; + + ConsolePtr make_console(ssh_channel channel) override; + +private: + const UINT input_code_page; + const UINT output_code_page; +}; +} // namespace multipass + +#endif // MULTIPASS_WINDOWS_TERMINAL_H diff --git a/src/platform/logger/CMakeLists.txt b/src/platform/logger/CMakeLists.txt index 7e16de84af..7c0f5f360a 100644 --- a/src/platform/logger/CMakeLists.txt +++ b/src/platform/logger/CMakeLists.txt @@ -13,44 +13,52 @@ #along with this program.If not, see < http: // www.gnu.org/licenses/>. # -add_library(logger_linux_common STATIC linux_logger.cpp) -target_link_libraries(logger_linux_common Qt6::Core) - -# Determine whether journald is available. -find_package(PkgConfig) -pkg_check_modules(JOURNALD libsystemd) - -# Declare the journald target if found. -if(JOURNALD_FOUND) - set(JOURNALD_FOUND "${JOURNALD_FOUND}" PARENT_SCOPE) - add_library(logger_linux_journald STATIC journald_wrapper.cpp journald_logger.cpp) - target_include_directories(logger_linux_journald PRIVATE ${JOURNALD_INCLUDE_DIRS}) - target_link_libraries(logger_linux_journald logger_linux_common ${JOURNALD_LIBRARIES}) -endif() +if(MSVC) + add_library(wineventlogger STATIC win_event_logger.cpp) + qt6_disable_unicode_defines(wineventlogger) + target_link_libraries(wineventlogger fmt::fmt-header-only Qt6::Core) +elseif(APPLE) + # Platform specific logger library here +else() + add_library(logger_linux_common STATIC linux_logger.cpp) + target_link_libraries(logger_linux_common Qt6::Core) + # Determine whether journald is available. + find_package(PkgConfig) + pkg_check_modules(JOURNALD libsystemd) -# Determine if syslog is available. -check_include_files(syslog.h HAVE_SYSLOG_H) -check_function_exists(syslog HAVE_SYSLOG) + # Declare the journald target if found. + if(JOURNALD_FOUND) + set(JOURNALD_FOUND "${JOURNALD_FOUND}" PARENT_SCOPE) + add_library(logger_linux_journald STATIC journald_wrapper.cpp journald_logger.cpp) + target_include_directories(logger_linux_journald PRIVATE ${JOURNALD_INCLUDE_DIRS}) + target_link_libraries(logger_linux_journald logger_linux_common ${JOURNALD_LIBRARIES}) + endif() -set(SYSLOG_FOUND false) -if(HAVE_SYSLOG_H AND HAVE_SYSLOG) - set(SYSLOG_FOUND true) -endif() -# Declare the syslog target if found. -if(SYSLOG_FOUND) - add_library(logger_linux_syslog STATIC syslog_wrapper.cpp syslog_logger.cpp) - target_link_libraries(logger_linux_syslog logger_linux_common) -endif() + # Determine if syslog is available. + check_include_files(syslog.h HAVE_SYSLOG_H) + check_function_exists(syslog HAVE_SYSLOG) -# Settle on which logging backend to use -if(MULTIPASS_ENABLE_SYSLOG) - add_library(logger_linux ALIAS logger_linux_syslog) - message(STATUS "[logging] will use the syslog backend") -elseif(JOURNALD_FOUND) - add_library(logger_linux ALIAS logger_linux_journald) - message(STATUS "[logging] will use the journald backend") -else() - message(FATAL_ERROR "No viable logging backend found in the environment!") + set(SYSLOG_FOUND false) + if(HAVE_SYSLOG_H AND HAVE_SYSLOG) + set(SYSLOG_FOUND true) + endif() + + # Declare the syslog target if found. + if(SYSLOG_FOUND) + add_library(logger_linux_syslog STATIC syslog_wrapper.cpp syslog_logger.cpp) + target_link_libraries(logger_linux_syslog logger_linux_common) + endif() + + # Settle on which logging backend to use + if(MULTIPASS_ENABLE_SYSLOG) + add_library(logger_linux ALIAS logger_linux_syslog) + message(STATUS "[logging] will use the syslog backend") + elseif(JOURNALD_FOUND) + add_library(logger_linux ALIAS logger_linux_journald) + message(STATUS "[logging] will use the journald backend") + else() + message(FATAL_ERROR "No viable logging backend found in the environment!") + endif() endif() diff --git a/src/platform/logger/win_event_logger.cpp b/src/platform/logger/win_event_logger.cpp new file mode 100644 index 0000000000..23d56b7f79 --- /dev/null +++ b/src/platform/logger/win_event_logger.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "win_event_logger.h" + +#include + +#include + +#include + +namespace mpl = multipass::logging; + +namespace +{ +constexpr auto as_eventlog_type(mpl::Level level) noexcept +{ + switch (level) + { + case mpl::Level::info: + case mpl::Level::debug: + case mpl::Level::trace: + return EVENTLOG_INFORMATION_TYPE; + case mpl::Level::error: + return EVENTLOG_ERROR_TYPE; + case mpl::Level::warning: + return EVENTLOG_WARNING_TYPE; + } + return EVENTLOG_AUDIT_FAILURE; +} + +class EventSource +{ +public: + EventSource(const std::string& name) : event_source{RegisterEventSource(nullptr, name.c_str())} + { + } + + ~EventSource() + { + DeregisterEventSource(event_source); + } + + HANDLE get() const + { + return event_source; + } + +private: + HANDLE event_source; +}; +} // namespace + +mpl::EventLogger::EventLogger(mpl::Level level) : logging_level{level} +{ +} + +void mpl::EventLogger::log(mpl::Level level, std::string_view category, std::string_view message) const +{ + const static std::string event_source_name{"Multipass"}; + if (level <= logging_level) + { + /** + * FIXME: It's not ideal that the code Register/Deregister the event source + * in every single log call. We should refactor this. + */ + EventSource ev_source(event_source_name); + constexpr static WORD category_id{0}; + constexpr static WORD event_id{1}; + constexpr static PSID security_id{nullptr}; + constexpr static DWORD binary_size{0}; + constexpr static LPVOID raw_data{nullptr}; + + const auto log_msg = fmt::format("[{}] {}\n", category, message); + std::array messages = {log_msg.c_str()}; + const WORD num_strings{static_cast(messages.size())}; + + ReportEvent(ev_source.get(), + as_eventlog_type(level), + category_id, + event_id, + security_id, + num_strings, + binary_size, + messages.data(), + raw_data); + } +} diff --git a/include/multipass/exceptions/unsupported_alias_exception.h b/src/platform/logger/win_event_logger.h similarity index 63% rename from include/multipass/exceptions/unsupported_alias_exception.h rename to src/platform/logger/win_event_logger.h index eb2b0efa72..095e466340 100644 --- a/include/multipass/exceptions/unsupported_alias_exception.h +++ b/src/platform/logger/win_event_logger.h @@ -15,19 +15,25 @@ * */ -#ifndef MULTIPASS_UNSUPPORTED_ALIAS_EXCEPTION_H -#define MULTIPASS_UNSUPPORTED_ALIAS_EXCEPTION_H +#ifndef MULTIPASS_WIN_EVENT_LOGGER_H +#define MULTIPASS_WIN_EVENT_LOGGER_H -#include +#include namespace multipass { -class UnsupportedAliasException : public std::runtime_error +namespace logging +{ +class EventLogger : public Logger { public: - explicit UnsupportedAliasException(const std::string& message) : runtime_error(message) - { - } + explicit EventLogger(Level level); + void log(Level level, std::string_view category, std::string_view message) const override; + +private: + Level logging_level; }; +} // namespace logging } // namespace multipass -#endif // MULTIPASS_UNSUPPORTED_ALIAS_EXCEPTION_H + +#endif // MULTIPASS_WIN_EVENT_LOGGER_H diff --git a/src/platform/platform_linux.cpp b/src/platform/platform_linux.cpp index c5a0e46da8..7ecd648d18 100644 --- a/src/platform/platform_linux.cpp +++ b/src/platform/platform_linux.cpp @@ -37,6 +37,10 @@ #include "backends/qemu/qemu_virtual_machine_factory.h" #endif +#ifdef VIRTUALBOX_ENABLED +#include "backends/virtualbox/virtualbox_virtual_machine_factory.h" +#endif + #ifdef MULTIPASS_JOURNALD_ENABLED #include "logger/journald_logger.h" #else @@ -44,7 +48,6 @@ #endif #include "platform_linux_detail.h" -#include "platform_shared.h" #include "shared/linux/process_factory.h" #include "shared/sshfs_server_process_spec.h" #include @@ -258,31 +261,14 @@ std::map mp::platform::Platform::get_netw return detail::get_network_interfaces_from(sysfs); } -QString mp::platform::Platform::get_blueprints_url_override() const -{ - return QString::fromUtf8(qgetenv("MULTIPASS_BLUEPRINTS_URL")); -} - -bool mp::platform::Platform::is_alias_supported(const std::string& alias, const std::string& remote) const -{ - if (remote == mp::snapcraft_remote) - { - return supported_snapcraft_aliases.find(alias) != supported_snapcraft_aliases.end(); - } - - return true; -} - -bool mp::platform::Platform::is_remote_supported(const std::string& remote) const -{ - return true; -} - bool mp::platform::Platform::is_backend_supported(const QString& backend) const { return #ifdef QEMU_ENABLED backend == "qemu" || +#endif +#ifdef VIRTUALBOX_ENABLED + backend == "virtualbox" || #endif backend == "libvirt" || backend == "lxd"; } @@ -372,11 +358,6 @@ QString mp::platform::Platform::default_privileged_mounts() const return QStringLiteral("true"); } -bool mp::platform::Platform::is_image_url_supported() const -{ - return true; -} - std::string mp::platform::Platform::bridge_nomenclature() const { return br_nomenclature; @@ -441,6 +422,11 @@ mp::VirtualMachineFactory::UPtr mp::platform::vm_backend(const mp::Path& data_di if (driver == QStringLiteral("lxd")) return std::make_unique(data_dir); +#if VIRTUALBOX_ENABLED + if (driver == QStringLiteral("virtualbox")) + return std::make_unique(data_dir); +#endif + throw std::runtime_error(fmt::format("Unsupported virtualization driver: {}", driver)); } diff --git a/src/platform/platform_osx.cpp b/src/platform/platform_osx.cpp new file mode 100644 index 0000000000..fc2a90ceda --- /dev/null +++ b/src/platform/platform_osx.cpp @@ -0,0 +1,371 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef QEMU_ENABLED +#include "backends/qemu/qemu_virtual_machine_factory.h" +#endif + +#ifdef VIRTUALBOX_ENABLED +#include "backends/virtualbox/virtualbox_virtual_machine_factory.h" +#endif + +#include "shared/macos/process_factory.h" +#include "shared/sshfs_server_process_spec.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; + +namespace +{ +constexpr auto category = "osx platform"; +constexpr auto br_nomenclature = "bridge"; + +QString get_networksetup_output() +{ + auto nsetup_spec = mp::simple_process_spec("networksetup", {"-listallhardwareports"}); + auto nsetup_process = mp::platform::make_process(std::move(nsetup_spec)); + auto nsetup_exit_state = nsetup_process->execute(); + + if (!nsetup_exit_state.completed_successfully()) + { + throw std::runtime_error(fmt::format("networksetup failed ({}) with the following output:\n", + nsetup_exit_state.failure_message(), + nsetup_process->read_all_standard_error())); + } + + return nsetup_process->read_all_standard_output(); +} + +QString get_ifconfig_output() +{ + auto ifconfig_spec = mp::simple_process_spec("ifconfig", {}); + auto ifconfig_process = mp::platform::make_process(std::move(ifconfig_spec)); + auto ifconfig_exit_state = ifconfig_process->execute(); + + if (!ifconfig_exit_state.completed_successfully()) + { + throw std::runtime_error(fmt::format("ifconfig failed ({}) with the following output:\n{}", + ifconfig_exit_state.failure_message(), + ifconfig_process->read_all_standard_error())); + } + + return ifconfig_process->read_all_standard_output(); +} + +QStringList get_bridged_interfaces(const QString& if_name, const QString& ifconfig_output) +{ + // Search the substring of the full ifconfig output containing only the interface if_name. + int start = ifconfig_output.indexOf( + QRegularExpression{QStringLiteral("^%1:").arg(if_name), QRegularExpression::MultilineOption}); + int end = ifconfig_output.indexOf(QRegularExpression("^\\w+:", QRegularExpression::MultilineOption), start + 1); + auto ifconfig_entry = ifconfig_output.mid(start, end - start); + + // Search for the bridged interfaces in the resulting string ref. + const auto pattern = QStringLiteral("^[ \\t]+member: (?\\w+) flags.*$"); + const auto regexp = QRegularExpression{pattern, QRegularExpression::MultilineOption}; + QRegularExpressionMatchIterator match_it = regexp.globalMatch(ifconfig_entry); + + QStringList bridged_ifs; + + while (match_it.hasNext()) + { + auto match = match_it.next(); + if (match.hasMatch()) + { + bridged_ifs.push_back(match.captured("member")); + } + } + + return bridged_ifs; +} + +std::string describe_bridge(const QString& name, const QString& ifconfig_output) +{ + auto members = get_bridged_interfaces(name, ifconfig_output); + return members.isEmpty() ? "Empty network bridge" : fmt::format("Network bridge with {}", members.join(", ")); +} + +std::optional get_net_info(const QString& nsetup_entry, const QString& ifconfig_output) +{ + const auto name_pattern = QStringLiteral("^Device: ([\\w -]+)$"); + const auto desc_pattern = QStringLiteral("^Hardware Port: (.+)$"); + const auto name_regex = QRegularExpression{name_pattern, QRegularExpression::MultilineOption}; + const auto desc_regex = QRegularExpression{desc_pattern, QRegularExpression::MultilineOption}; + const auto name = name_regex.match(nsetup_entry).captured(1); + const auto desc = desc_regex.match(nsetup_entry).captured(1); + + mpl::log(mpl::Level::trace, category, fmt::format("Parsing networksetup chunk:\n{}", nsetup_entry)); + + if (!name.isEmpty() && !desc.isEmpty()) + { + auto id = name.toStdString(); + + // bridges first, so we match on things like "thunderbolt bridge" here + if (name.contains(br_nomenclature) || desc.contains(br_nomenclature, Qt::CaseInsensitive)) + return mp::NetworkInterfaceInfo{id, br_nomenclature, describe_bridge(name, ifconfig_output)}; + + // simple cases next + auto description = desc.toStdString(); + for (const auto& type : {"thunderbolt", "ethernet", "usb"}) + if (desc.contains(type, Qt::CaseInsensitive)) + return mp::NetworkInterfaceInfo{id, type, description}; + + // finally wifi, which we report without a dash in the middle + if (desc.contains("wi-fi", Qt::CaseInsensitive)) + return mp::NetworkInterfaceInfo{id, "wifi", description}; + + mpl::log(mpl::Level::warning, category, fmt::format("Unsupported device \"{}\" ({})", id, description)); + } + + mpl::log(mpl::Level::trace, category, fmt::format("Skipping chunk")); + return std::nullopt; +} + +std::string get_alias_script_path(const std::string& alias) +{ + QDir aliases_folder = MP_PLATFORM.get_alias_scripts_folder(); + + return aliases_folder.absoluteFilePath(QString::fromStdString(alias)).toStdString(); +} +} // namespace + +std::map mp::platform::Platform::get_network_interfaces_info() const +{ + auto networks = std::map(); + + // Get the output of 'ifconfig'. + auto ifconfig_output = get_ifconfig_output(); + auto nsetup_output = get_networksetup_output(); + + mpl::log(mpl::Level::trace, category, fmt::format("Got the following output from ifconfig:\n{}", ifconfig_output)); + mpl::log(mpl::Level::trace, + category, + fmt::format("Got the following output from networksetup:\n{}", nsetup_output)); + + // split the output of networksetup in multiple entries (one per interface) + auto empty_line_regex = QRegularExpression(QStringLiteral("^$"), QRegularExpression::MultilineOption); + auto nsetup_entries = nsetup_output.split(empty_line_regex, Qt::SkipEmptyParts); + + // Parse the output we got to obtain each interface's properties + for (const auto& nsetup_entry : nsetup_entries) + { + if (auto net_info = get_net_info(nsetup_entry, ifconfig_output); net_info) + { + const auto& net_id = net_info->id; + networks.emplace(net_id, std::move(*net_info)); + } + } + + return networks; +} + +bool mp::platform::Platform::is_backend_supported(const QString& backend) const +{ + return +#ifdef QEMU_ENABLED + (backend == "qemu" && QOperatingSystemVersion::current() >= QOperatingSystemVersion::MacOSBigSur) || +#endif +#ifdef VIRTUALBOX_ENABLED + backend == "virtualbox" || +#endif + false; +} + +auto mp::platform::Platform::extra_daemon_settings() const -> SettingSpec::Set +{ + return {}; +} + +auto mp::platform::Platform::extra_client_settings() const -> SettingSpec::Set +{ + return {}; +} + +QString mp::platform::interpret_setting(const QString& key, const QString& val) +{ + // this should not happen (settings should have found it to be an invalid key) + throw InvalidSettingException(key, val, "Setting unavailable on macOS"); +} + +void mp::platform::sync_winterm_profiles() +{ + // NOOP on macOS +} + +std::string mp::platform::default_server_address() +{ + return {"unix:/var/run/multipass_socket"}; +} + +QString mp::platform::Platform::default_driver() const +{ + assert(QEMU_ENABLED); + return QStringLiteral("qemu"); +} + +QString mp::platform::Platform::default_privileged_mounts() const +{ + return QStringLiteral("true"); +} + +std::string mp::platform::Platform::bridge_nomenclature() const +{ + return br_nomenclature; +} + +QString mp::platform::Platform::daemon_config_home() const // temporary +{ + auto ret = QStringLiteral("/var/root/Library/Preferences/"); + ret = QDir{ret}.absoluteFilePath(mp::daemon_name); + + return ret; +} + +mp::VirtualMachineFactory::UPtr mp::platform::vm_backend(const mp::Path& data_dir) +{ + auto driver = MP_SETTINGS.get(mp::driver_key); + + if (driver == QStringLiteral("virtualbox")) + { +#if VIRTUALBOX_ENABLED + qputenv("PATH", qgetenv("PATH") + ":/usr/local/bin"); /* + This is where the Virtualbox installer puts things, and relying on PATH + allows the user to do something about it, if the binaries are not found + there. + */ + + return std::make_unique(data_dir); +#endif + } + else if (driver == QStringLiteral("qemu")) + { +#if QEMU_ENABLED + return std::make_unique(data_dir); +#endif + } + + throw std::runtime_error(fmt::format("Unsupported virtualization driver: {}", driver)); +} + +std::unique_ptr mp::platform::make_sshfs_server_process(const mp::SSHFSServerConfig& config) +{ + return MP_PROCFACTORY.create_process(std::make_unique(config)); +} + +std::unique_ptr mp::platform::make_process(std::unique_ptr&& process_spec) +{ + return MP_PROCFACTORY.create_process(std::move(process_spec)); +} + +mp::logging::Logger::UPtr mp::platform::make_logger(mp::logging::Level level) +{ + return nullptr; +} + +mp::UpdatePrompt::UPtr mp::platform::make_update_prompt() +{ + return std::make_unique(); +} + +bool mp::platform::Platform::link(const char* target, const char* link) const +{ + QFileInfo file_info{target}; + + if (file_info.isSymLink()) + { + return ::symlink(file_info.symLinkTarget().toStdString().c_str(), link) == 0; + } + + return ::link(target, link) == 0; +} + +QDir mp::platform::Platform::get_alias_scripts_folder() const +{ + QDir aliases_folder; + + QString location = MP_STDPATHS.writableLocation(mp::StandardPaths::AppLocalDataLocation) + "/bin"; + aliases_folder = QDir{location}; + + return aliases_folder; +} + +void mp::platform::Platform::create_alias_script(const std::string& alias, const mp::AliasDefinition& def) const +{ + auto file_path = get_alias_script_path(alias); + + auto multipass_exec = QCoreApplication::applicationFilePath().toStdString(); + + std::string script = "#!/bin/sh\n\n\"" + multipass_exec + "\" " + alias + " -- " + "\"${@}\"\n"; + + MP_UTILS.make_file_with_content(file_path, script, true); + + auto permissions = + MP_FILEOPS.get_permissions(file_path) | fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec; + + if (!MP_PLATFORM.set_permissions(file_path, permissions)) + throw std::runtime_error(fmt::format("cannot set permissions to alias script '{}'", file_path)); +} + +void mp::platform::Platform::remove_alias_script(const std::string& alias) const +{ + std::string file_path = get_alias_script_path(alias); + + if (::unlink(file_path.c_str())) + throw std::runtime_error(strerror(errno)); +} + +std::string mp::platform::reinterpret_interface_id(const std::string& ux_id) +{ + return ux_id; +} + +std::filesystem::path mp::platform::Platform::get_root_cert_path() const +{ + return std::filesystem::path{"/Library/Keychains/multipass_root_cert.pem"}; +} diff --git a/include/multipass/exceptions/unsupported_remote_exception.h b/src/platform/platform_proprietary.cpp similarity index 61% rename from include/multipass/exceptions/unsupported_remote_exception.h rename to src/platform/platform_proprietary.cpp index 07bd694c3b..65472cfe36 100644 --- a/include/multipass/exceptions/unsupported_remote_exception.h +++ b/src/platform/platform_proprietary.cpp @@ -15,19 +15,18 @@ * */ -#ifndef MULTIPASS_UNSUPPORTED_REMOTE_EXCEPTION_H -#define MULTIPASS_UNSUPPORTED_REMOTE_EXCEPTION_H +/** + * @file + * @brief Implementations for proprietary platforms + * @details Platform-specific implementations that are common to proprietary platforms, i.e., Windows and macOS. + */ -#include +#include +#include -namespace multipass -{ -class UnsupportedRemoteException : public std::runtime_error +namespace mp = multipass; + +std::string mp::platform::host_version() { -public: - explicit UnsupportedRemoteException(const std::string& message) : runtime_error(message) - { - } -}; -} // namespace multipass -#endif // MULTIPASS_UNSUPPORTED_REMOTE_EXCEPTION_H + return fmt::format("{}-{}", QSysInfo::productType(), QSysInfo::productVersion()); +} diff --git a/src/platform/platform_win.cpp b/src/platform/platform_win.cpp new file mode 100644 index 0000000000..de6d732e3f --- /dev/null +++ b/src/platform/platform_win.cpp @@ -0,0 +1,992 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "backends/hyperv/hyperv_virtual_machine_factory.h" +#include "backends/virtualbox/virtualbox_virtual_machine_factory.h" +#include "logger/win_event_logger.h" +#include "shared/sshfs_server_process_spec.h" +#include "shared/windows/powershell.h" +#include "shared/windows/process_factory.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +// Needed for OpenSSL dll compatibility +extern "C" +{ +#include +} + +namespace mp = multipass; +namespace mpl = mp::logging; +namespace mpu = multipass::utils; + +namespace +{ +static const auto none = QStringLiteral("none"); + +time_t time_t_from(const FILETIME* ft) +{ + long long win_time = (static_cast(ft->dwHighDateTime) << 32) + ft->dwLowDateTime; + win_time -= 116444736000000000LL; + win_time /= 10000000; + return static_cast(win_time); +} + +FILETIME filetime_from(const time_t t) +{ + FILETIME ft; + auto win_time = Int32x32To64(t, 10000000) + 116444736000000000; + ft.dwLowDateTime = static_cast(win_time); + ft.dwHighDateTime = win_time >> 32; + + return ft; +} + +sftp_attributes_struct stat_to_attr(const WIN32_FILE_ATTRIBUTE_DATA* data) +{ + sftp_attributes_struct attr{}; + + attr.uid = -2; + attr.gid = -2; + + attr.flags = + SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_UIDGID | SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME; + + attr.atime = time_t_from(&(data->ftLastAccessTime)); + attr.mtime = time_t_from(&(data->ftLastWriteTime)); + + attr.permissions = SSH_S_IFLNK | 0777; + + return attr; +} + +QString interpret_winterm_setting(const QString& val) +{ + static const auto acceptable = QStringList{none, mp::petenv_default}; + + auto ret = val.toLower(); + if (!acceptable.contains(ret)) + throw mp::InvalidSettingException{ + mp::winterm_key, + val, + QStringLiteral("Unknown value. Try one of these: %1.").arg(acceptable.join(", "))}; + + return ret; +} + +QString locate_profiles_path() +{ + // The profiles file is expected in + // $env:LocalAppData\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json + // where $env:LocalAppData is normally C:\Users\\AppData\Local + return MP_STDPATHS.locate(mp::StandardPaths::GenericConfigLocation, + "Packages/Microsoft.WindowsTerminal_8wekyb3d8bbwe/LocalState/settings.json"); +} + +struct WintermSyncException : public std::runtime_error +{ + WintermSyncException(const std::string& msg, const QString& path, const std::string& reason) + : std::runtime_error{fmt::format("{}; location: \"{}\"; reason: {}.", msg, path, reason)} + { + } + + WintermSyncException(const std::string& msg, const QString& path) + : WintermSyncException{msg, path, fmt::format("{} (error code: {})", std::strerror(errno), errno)} + { + } +}; + +struct LesserWintermSyncException : public WintermSyncException +{ + using WintermSyncException::WintermSyncException; +}; + +struct ModerateWintermSyncException : public WintermSyncException +{ + using WintermSyncException::WintermSyncException; +}; + +struct GreaterWintermSyncException : public WintermSyncException +{ + using WintermSyncException::WintermSyncException; +}; + +Json::Value& edit_profiles(const QString& path, Json::Value& json_root) +{ + if (!json_root.isMember("profiles")) + throw ModerateWintermSyncException{"Could not find profiles in Windows Terminal's settings", + path, + "No \"profiles\" node under JSON root"}; + + auto& profiles = json_root["profiles"]; // the array of profiles can be in this node or in the subnode "list" + return profiles.isArray() || !profiles.isMember("list") ? profiles : profiles["list"]; /* Notes: + 1) don't index into "list" unless it already exists + 2) can't look for named member on array values */ +} + +Json::Value read_winterm_settings(const QString& path) +{ + std::ifstream json_file{path.toStdString(), std::ifstream::binary}; + if (!json_file) + throw ModerateWintermSyncException{"Could not read Windows Terminal's configuration", path}; + + Json::CharReaderBuilder rbuilder; + Json::Value json_root; + std::string errs; + if (!Json::parseFromStream(rbuilder, json_file, &json_root, &errs)) + throw ModerateWintermSyncException{"Could not parse Windows Terminal's configuration", path, errs}; + + return json_root; +} + +// work around white showing as pale-green, unless the user has a custom value +void wt_patch_colors(Json::Value& primary_profile) +{ + static constexpr auto off_white = "#FDFDFD"; + static constexpr auto comment_placement = Json::commentAfterOnSameLine; + + if (auto& cursor_color = primary_profile["cursorColor"]; cursor_color.isNull()) + { + cursor_color = off_white; + cursor_color.setComment("// work around white showing as pale-green", comment_placement); + + // match cursor color in the foreground if there is no custom value + if (auto& foreground = primary_profile["foreground"]; foreground.isNull()) + { + foreground = off_white; + foreground.setComment("// match cursor", comment_placement); + } + } +} + +Json::Value create_primary_profile() +{ + Json::Value primary_profile{}; + primary_profile["guid"] = mp::winterm_profile_guid; + primary_profile["name"] = "Multipass"; + primary_profile["commandline"] = "multipass shell"; + primary_profile["background"] = "#350425"; + primary_profile["cursorShape"] = "filledBox"; + primary_profile["fontFace"] = "Ubuntu Mono"; + primary_profile["historySize"] = 50000; + primary_profile["icon"] = QDir{QCoreApplication::applicationDirPath()}.filePath("multipass_wt.ico").toStdString(); + + return primary_profile; +} + +Json::Value update_profiles(const QString& path, const Json::Value& json_root, const QString& winterm_setting) +{ + Json::Value ret = json_root; + auto& profiles = edit_profiles(path, ret); + + auto primary_profile_it = std::find_if(std::begin(profiles), std::end(profiles), [](const auto& profile) { + return profile["guid"] == mp::winterm_profile_guid; + }); + + Json::Value* primary_profile_ptr = nullptr; + if (primary_profile_it != std::end(profiles)) + { + if (primary_profile_it->isMember("hidden") || winterm_setting == none) + (*primary_profile_it)["hidden"] = winterm_setting == none; + primary_profile_ptr = &(*primary_profile_it); + } + else if (winterm_setting != none) + primary_profile_ptr = &profiles.append(create_primary_profile()); + + if (primary_profile_ptr) + wt_patch_colors(*primary_profile_ptr); + + return ret; +} + +void write_profiles(const std::string& path, const Json::Value& json_root) +{ + std::ofstream json_file{path, std::ofstream::binary}; + json_file << json_root; + if (!json_file) + throw GreaterWintermSyncException{"Could not write Windows Terminal's configuration", + QString::fromStdString(path)}; +} + +std::string create_shadow_config_file(const QString& path) +{ + const auto tmp_file_template = path + ".XXXXXX"; + auto tmp_file = QTemporaryFile{tmp_file_template}; + + if (!tmp_file.open() || !tmp_file.exists()) + throw GreaterWintermSyncException{"Could not create temporary configuration file for Windows Terminal", + tmp_file_template}; + + tmp_file.setAutoRemove(false); + return tmp_file.fileName().toStdString(); +} + +void save_profiles(const QString& path, const Json::Value& json_root) +{ + std::string tmp_file_name = create_shadow_config_file(path); + auto tmp_file_removing_guard = sg::make_scope_guard([&tmp_file_name]() noexcept { + std::error_code ec; // ignored, there's an exception in flight and we're in a dtor, so best-effort only + std::filesystem::remove(tmp_file_name, ec); + }); + + write_profiles(tmp_file_name, json_root); + + try + { + std::filesystem::rename(tmp_file_name, path.toStdString()); + } + catch (std::filesystem::filesystem_error& e) + { + throw GreaterWintermSyncException{"Could not update Windows Terminal's configuration", path, e.what()}; + } + + tmp_file_removing_guard.dismiss(); // we succeeded, tmp file no longer there +} + +std::string interpret_net_type(const QString& media_type, const QString& physical_media_type) +{ + // Note: use the following to see what types may be returned + // `get-netadapter | select -first 1 | get-member -name physicalmediatype | select -expandproperty definition` + if (physical_media_type == "802.3") + return "ethernet"; + else if (physical_media_type == "Unspecified") + return media_type == "802.3" ? "ethernet" : "unknown"; // virtio covered here + else if (physical_media_type.contains("802.11")) + return "wifi"; + else + return physical_media_type.toLower().toStdString(); +} + +QString get_alias_script_path(const std::string& alias) +{ + auto aliases_folder = MP_PLATFORM.get_alias_scripts_folder(); + + return aliases_folder.absoluteFilePath(QString::fromStdString(alias)) + ".bat"; +} + +QString program_data_multipass_path() +{ + return QDir{qEnvironmentVariable("ProgramData", "C:\\ProgramData")}.absoluteFilePath("Multipass"); +} + +QString systemprofile_app_data_path() +{ + auto ret = QString{qgetenv("SYSTEMROOT")}; + ret = QDir{ret}.absoluteFilePath("system32"); + ret = QDir{ret}.absoluteFilePath("config"); + ret = QDir{ret}.absoluteFilePath("systemprofile"); + ret = QDir{ret}.absoluteFilePath("AppData"); + + return ret; +} + +DWORD set_privilege(HANDLE handle, LPCTSTR privilege, bool enable) +{ + LUID id; + if (!LookupPrivilegeValue(NULL, privilege, &id)) + { + return GetLastError(); + } + + TOKEN_PRIVILEGES privileges{}; + privileges.PrivilegeCount = 1; + privileges.Privileges[0].Luid = id; + privileges.Privileges[0].Attributes = (enable) ? SE_PRIVILEGE_ENABLED : 0; + + if (!AdjustTokenPrivileges(handle, false, &privileges, sizeof(privileges), NULL, NULL)) + { + return GetLastError(); + } + + return (GetLastError() == ERROR_NOT_ALL_ASSIGNED) ? ERROR_NOT_ALL_ASSIGNED : ERROR_SUCCESS; +} + +DWORD set_file_owner(LPSTR path, PSID new_owner) +{ + std::unique_ptr token(nullptr, CloseHandle); + if (HANDLE t; !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &t)) + { + return GetLastError(); + } + else + { + token.reset(t); + } + + if (auto err = set_privilege(token.get(), SE_TAKE_OWNERSHIP_NAME, true); err != ERROR_SUCCESS) + { + return err; + } + + auto r = SetNamedSecurityInfo(path, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, new_owner, NULL, NULL, NULL); + set_privilege(token.get(), SE_TAKE_OWNERSHIP_NAME, false); + return r; +} + +DWORD set_specific_perms(LPSTR path, PSID pSid, DWORD access_mask, bool inherit) +{ + PACL pOldDACL = NULL, pDACL = NULL; + PSECURITY_DESCRIPTOR pSD = NULL; + EXPLICIT_ACCESS ea; + + GetNamedSecurityInfo(path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pOldDACL, NULL, &pSD); + + ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS)); + + ea.grfAccessPermissions = access_mask; + ea.grfAccessMode = SET_ACCESS; + ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT; + ea.Trustee.TrusteeForm = TRUSTEE_IS_SID; + ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; + ea.Trustee.ptstrName = (LPTSTR)pSid; + + SetEntriesInAcl(1, &ea, pOldDACL, &pDACL); + auto error_code = + SetNamedSecurityInfo(path, + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION | ((inherit) ? UNPROTECTED_DACL_SECURITY_INFORMATION + : PROTECTED_DACL_SECURITY_INFORMATION), + NULL, + NULL, + pDACL, + NULL); + + LocalFree((HLOCAL)pSD); + LocalFree((HLOCAL)pDACL); + + return error_code; +} + +// returns a PSID unique_ptr for a well known pid +auto get_well_known_sid(WELL_KNOWN_SID_TYPE type) +{ + DWORD len = SECURITY_MAX_SID_SIZE; + auto sid = std::unique_ptr(LocalAlloc(LPTR, len), FreeSid); + if (!CreateWellKnownSid(type, nullptr, sid.get(), &len)) + { + throw std::system_error(GetLastError(), std::system_category(), "Failed to create well known SID"); + } + + return sid; +} + +DWORD set_specific_perms(LPSTR path, WELL_KNOWN_SID_TYPE sid_type, DWORD access_mask, bool inherit) +{ + auto pSid = get_well_known_sid(sid_type); + return set_specific_perms(path, pSid.get(), access_mask, inherit); +} + +DWORD convert_permissions(int unix_perms) +{ + if (unix_perms & 07) + return GENERIC_ALL; + + DWORD access_mask = 0; + if (unix_perms & 04) + access_mask |= GENERIC_READ; + if (unix_perms & 02) + access_mask |= GENERIC_WRITE; + if (unix_perms & 01) + access_mask |= GENERIC_EXECUTE; + + return access_mask; +} + +// Since the Windows API expects a C style function pointer, we cannot pass parameters. +// This means that only one watchdog can exist at a time. +HANDLE signal_event = (HANDLE) nullptr; + +BOOL signal_handler(DWORD dwCtrlType) +{ + switch (dwCtrlType) + { + case CTRL_C_EVENT: + // In Windows, ctrl-break is always delivered to all + // registered handlers no matter what the previous + // handlers return. + [[fallthrough]]; + case CTRL_BREAK_EVENT: + { + SetEvent(signal_event); + return TRUE; + } + default: + return FALSE; + } +} + +std::filesystem::path multipass_final_storage_location() +{ + const auto user_specified_mp_storage = MP_PLATFORM.multipass_storage_location(); + const auto mp_final_storage = user_specified_mp_storage.isEmpty() + ? MP_STDPATHS.writableLocation(mp::StandardPaths::AppDataLocation) + : user_specified_mp_storage; + return std::filesystem::path{mp_final_storage.toStdString()}; +} +} // namespace + +std::map mp::platform::Platform::get_network_interfaces_info() const +{ + static const auto ps_cmd_base = QStringLiteral( + "Get-NetAdapter -physical | Select-Object -Property Name,MediaType,PhysicalMediaType,InterfaceDescription"); + static const auto ps_args = QString{ps_cmd_base}.split(' ', Qt::SkipEmptyParts) + PowerShell::Snippets::to_bare_csv; + + QString ps_output; + QString ps_output_err; + if (PowerShell::exec(ps_args, "Network Listing on Windows Platform", &ps_output, &ps_output_err)) + { + std::map ret{}; + for (const auto& line : ps_output.split(QRegularExpression{"[\r\n]"}, Qt::SkipEmptyParts)) + { + auto terms = line.split(',', Qt::KeepEmptyParts); + if (terms.size() != 4) + { + throw std::runtime_error{ + fmt::format("Could not determine available networks - unexpected powershell output: {}", + ps_output)}; + } + + auto iface = mp::NetworkInterfaceInfo{terms[0].toStdString(), + interpret_net_type(terms[1], terms[2]), + terms[3].toStdString()}; + ret.emplace(iface.id, iface); + } + + return ret; + } + + auto detail = ps_output_err.isEmpty() ? "" : fmt::format(" Detail: {}", ps_output_err); + auto err = fmt::format("Could not determine available networks - error executing powershell command.{}", detail); + throw std::runtime_error{err}; +} + +bool mp::platform::Platform::is_backend_supported(const QString& backend) const +{ + return backend == "hyperv" || backend == "virtualbox"; +} + +void mp::platform::Platform::set_server_socket_restrictions(const std::string& /* server_address */, + const bool /* restricted */) const +{ +} + +QString mp::platform::interpret_setting(const QString& key, const QString& val) +{ + if (key == mp::winterm_key) + return interpret_winterm_setting(val); + + // this should not happen (settings should have found it to be an invalid key) + throw InvalidSettingException(key, val, "Setting unavailable on Windows"); +} + +void mp::platform::sync_winterm_profiles() +{ + constexpr auto log_category = "winterm"; + const auto profiles_path = locate_profiles_path(); + const auto winterm_setting = MP_SETTINGS.get(mp::winterm_key); + + try + { + if (profiles_path.isEmpty()) + throw LesserWintermSyncException{"Could not find Windows Terminal's settings", + profiles_path, + "File not found"}; + + auto json_root = read_winterm_settings(profiles_path); + auto updated_json = update_profiles(profiles_path, json_root, winterm_setting); + if (updated_json != json_root) + save_profiles(profiles_path, updated_json); + } + catch (LesserWintermSyncException& e) + { + const auto level = winterm_setting == none ? mpl::Level::debug : mpl::Level::warning; + mpl::log(level, log_category, e.what()); + } + catch (ModerateWintermSyncException& e) + { + const auto level = winterm_setting == none ? mpl::Level::info : mpl::Level::error; + mpl::log(level, log_category, e.what()); + } + catch (GreaterWintermSyncException& e) + { + mpl::log(mpl::Level::error, log_category, e.what()); + } +} + +std::string mp::platform::default_server_address() +{ + return {"localhost:50051"}; +} + +QString mp::platform::Platform::default_driver() const +{ + return QStringLiteral("hyperv"); +} + +QString mp::platform::Platform::default_privileged_mounts() const +{ + return QStringLiteral("false"); +} + +std::string mp::platform::Platform::bridge_nomenclature() const +{ + return "switch"; +} + +QString mp::platform::Platform::daemon_config_home() const // temporary +{ + auto ret = systemprofile_app_data_path(); + ret = + QDir{ret}.absoluteFilePath("Local"); // what LOCALAPPDATA would point to under the system account, at this point + ret = QDir{ret}.absoluteFilePath(mp::daemon_name); + + if (QFile::exists(ret)) + { + return ret; // should be something like "C:/Windows/system32/config/systemprofile/AppData/Local/multipassd" + } + else + { + return MP_PLATFORM.multipass_storage_location(); + } +} + +mp::VirtualMachineFactory::UPtr mp::platform::vm_backend(const mp::Path& data_dir) +{ + const auto driver = MP_SETTINGS.get(mp::driver_key); + + if (driver == QStringLiteral("hyperv")) + return std::make_unique(data_dir); + else if (driver == QStringLiteral("virtualbox")) + { + qputenv("Path", qgetenv("Path") + ";C:\\Program Files\\Oracle\\VirtualBox"); /* + This is where the Virtualbox installer puts things, and relying on PATH + allows the user to do something about it, if the binaries are not found + there. + */ + + return std::make_unique(data_dir); + } + + throw std::runtime_error("Invalid virtualization driver set in the environment"); +} + +std::unique_ptr mp::platform::make_sshfs_server_process(const mp::SSHFSServerConfig& config) +{ + return MP_PROCFACTORY.create_process(std::make_unique(config)); +} + +std::unique_ptr mp::platform::make_process(std::unique_ptr&& process_spec) +{ + return MP_PROCFACTORY.create_process(std::move(process_spec)); +} + +mp::logging::Logger::UPtr mp::platform::make_logger(mp::logging::Level level) +{ + return std::make_unique(level); +} + +mp::UpdatePrompt::UPtr mp::platform::make_update_prompt() +{ + return std::make_unique(); +} + +int mp::platform::Platform::chown(const char* path, unsigned int uid, unsigned int gid) const +{ + return -1; +} + +// new_ACL returns a new ACL unique ptr that retains all existing Hyper-V ACEs or NULL if no entries exist. +auto new_ACL(LPSTR path) +{ + auto deleter = [](ACL* acl) noexcept { return LocalFree(HLOCAL(acl)); }; + auto newACL = std::unique_ptr{NULL, deleter}; + + PSECURITY_DESCRIPTOR pSD; + auto pSD_guard = sg::make_scope_guard([&pSD]() noexcept { LocalFree((HLOCAL)(pSD)); }); + + PACL pOldDACL = NULL; + if (GetNamedSecurityInfo(path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pOldDACL, NULL, &pSD) != + ERROR_SUCCESS) + { + return newACL; + } + + DWORD size = sizeof(ACL); + std::vector aces{}; + + // iterate over ACEs in old ACL. + for (DWORD i = 0; i < pOldDACL->AceCount; ++i) + { + ACCESS_ALLOWED_ACE* pACE = NULL; + if (!GetAce(pOldDACL, i, (LPVOID*)(&pACE))) + { + continue; + } + + PSID sid = (PSID)(&pACE->SidStart); + + // convert SID to string so we can examine it. + LPSTR sidStr = NULL; + if (ConvertSidToStringSid(sid, &sidStr)) + { + // Magic string given to us by + // https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers#well-known-sids + // All Hyper-V SIDs begin with this magic string. + static constexpr char VM_SID_ID[] = "S-1-5-83-"; + auto cmp = strncmp(sidStr, VM_SID_ID, sizeof(VM_SID_ID) - 1); + LocalFree((HLOCAL)sidStr); + + if (cmp == 0) + { + aces.emplace_back(pACE); + size += GetLengthSid(sid); + } + } + } + + if (aces.size() > 0) + { + size += sizeof(ACCESS_ALLOWED_ACE) * aces.size(); + + // Align size to a DWORD. (taken from + // https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-initializeacl) + size = (size + (sizeof(DWORD) - 1)) & 0xfffffffc; + + if (newACL.reset((PACL)LocalAlloc(LPTR, size)); newACL) + { + if (!InitializeAcl(newACL.get(), size, ACL_REVISION)) + { + throw std::system_error(GetLastError(), std::system_category(), "Failed to initialize new ACL"); + } + + // try to add all Hyper-V ACEs + for (const auto& ace : aces) + { + if (!AddAce(newACL.get(), ACL_REVISION, MAXDWORD, ace, ace->Header.AceSize)) + { + throw std::system_error(GetLastError(), + std::system_category(), + "Failed to add Hyper-V ACE to new ACL"); + } + } + } + } + + return newACL; +} + +bool mp::platform::Platform::set_permissions(const std::filesystem::path& path, + std::filesystem::perms perms, + bool inherit) const +{ + // Windows has both ACLs and very limited POSIX permissions + + // This handles the POSIX side of things. + std::error_code ec{}; + std::filesystem::permissions(path, perms, ec); + + // Rest handles ACLs + auto u8path = path.u8string(); + LPSTR lpPath = u8path.data(); + auto success = true; + + auto newACL = new_ACL(lpPath); + + // Wipe out current ACLs + SetNamedSecurityInfo(lpPath, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, newACL.get(), nullptr); + + if (int others = int(perms) & 0007; others != 0) + success &= set_specific_perms(lpPath, WinWorldSid, convert_permissions(others), inherit) == ERROR_SUCCESS; + if (int group = int(perms) & 0070; group != 0) + success &= + set_specific_perms(lpPath, WinCreatorGroupSid, convert_permissions(group >> 3), inherit) == ERROR_SUCCESS; + if (int owner = int(perms) & 0700; owner != 0) + success &= + set_specific_perms(lpPath, WinCreatorOwnerSid, convert_permissions(owner >> 6), inherit) == ERROR_SUCCESS; + + // #3216 Set the owner as Admin and give the Admins group blanket access + success &= take_ownership(path); + success &= set_specific_perms(lpPath, WinBuiltinAdministratorsSid, GENERIC_ALL, inherit) == ERROR_SUCCESS; + + return success; +} + +bool mp::platform::Platform::take_ownership(const std::filesystem::path& path) const +{ + auto u8path = path.u8string(); + LPSTR lpPath = u8path.data(); + + return set_file_owner(lpPath, get_well_known_sid(WinBuiltinAdministratorsSid).get()) == ERROR_SUCCESS; +} + +void mp::platform::Platform::setup_permission_inheritance(bool) const +{ + // this does nothing since Windows doesn't use global state +} + +bool mp::platform::Platform::symlink(const char* target, const char* link, bool is_dir) const +{ + DWORD flags = is_dir ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0x00 | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE; + return CreateSymbolicLink(link, target, flags); +} + +bool mp::platform::Platform::link(const char* target, const char* link) const +{ + return CreateHardLink(link, target, nullptr); +} + +int mp::platform::Platform::utime(const char* path, int atime, int mtime) const +{ + DWORD ret = NO_ERROR; + auto handle = CreateFile(path, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT, + NULL); + + if (handle != INVALID_HANDLE_VALUE) + { + auto atime_filetime = filetime_from(atime); + auto mtime_filetime = filetime_from(mtime); + + if (!SetFileTime(handle, nullptr, &atime_filetime, &mtime_filetime)) + { + ret = GetLastError(); + } + CloseHandle(handle); + } + else + { + ret = GetLastError(); + } + + return ret; +} + +QString mp::platform::Platform::get_username() const +{ + QString username; + mp::PowerShell::exec({"((Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username))"}, + "get-username", + &username); + return username.section('\\', 1); +} + +QDir mp::platform::Platform::get_alias_scripts_folder() const +{ + QDir aliases_folder; + + QString location = MP_STDPATHS.writableLocation(mp::StandardPaths::HomeLocation) + "/AppData/local/multipass/bin"; + aliases_folder = QDir{location}; + + if (!aliases_folder.mkpath(aliases_folder.path())) + throw std::runtime_error(fmt::format("error creating \"{}\"\n", aliases_folder.path())); + + return aliases_folder; +} + +void mp::platform::Platform::create_alias_script(const std::string& alias, const mp::AliasDefinition& def) const +{ + auto file_path = get_alias_script_path(alias); + + std::string multipass_exec = QCoreApplication::applicationFilePath().toStdString(); + + std::string script = "@\"" + multipass_exec + "\" " + alias + " -- %*\n"; + + MP_UTILS.make_file_with_content(file_path.toStdString(), script, true); +} + +void mp::platform::Platform::remove_alias_script(const std::string& alias) const +{ + auto file_path = get_alias_script_path(alias); + + if (!QFile::remove(file_path)) + throw std::runtime_error("error removing alias script"); +} + +auto mp::platform::Platform::extra_daemon_settings() const -> SettingSpec::Set +{ + return {}; +} + +auto mp::platform::Platform::extra_client_settings() const -> SettingSpec::Set +{ + SettingSpec::Set ret; + ret.insert(std::make_unique(winterm_key, petenv_default, [](const QString& val) { + return interpret_setting(winterm_key, val); + })); + + return ret; +} + +std::string mp::platform::Platform::alias_path_message() const +{ + return fmt::format("You'll need to add the script alias folder to your path for aliases to work\n" + "without prefixing with `multipass`. For now, you can just do:\n\n" + "In PowerShell:\n$ENV:PATH=\"$ENV:PATH;{0}\"\n\n" + "Or in Command Prompt:\nPATH=%PATH%;{0}\n", + get_alias_scripts_folder().absolutePath()); +} + +QString mp::platform::Platform::multipass_storage_location() const +{ + auto storage_location = mp::utils::get_multipass_storage(); + + // If MULTIPASS_STORAGE env var is set, use that + if (!storage_location.isEmpty()) + { + return storage_location; + } + + auto program_data_path = program_data_multipass_path(); + auto systemprofile_roaming_path = QDir{systemprofile_app_data_path()}.absoluteFilePath("Roaming"); + + // If %PROGRAMDATA%\Multipass exists or if %SYSTEMROOT%\system32\config\AppData\Roaming\multipassd doesn't + // exist, use %PROGRAMDATA%\Multipass + if (QFile::exists(program_data_path) || + !QFile::exists(QDir{systemprofile_roaming_path}.absoluteFilePath("multipassd"))) + { + return program_data_path; + } + + // If %SYSTEMROOT%\system32\config\AppData\Roaming\multipassd exists, return empty and let the + // caller use Qt's StandardPaths to figure it out (legacy) + return QString(); +} + +int mp::platform::symlink_attr_from(const char* path, sftp_attributes_struct* attr) +{ + WIN32_FILE_ATTRIBUTE_DATA data; + + if (GetFileAttributesEx(path, GetFileExInfoStandard, &data)) + { + *attr = stat_to_attr(&data); + attr->size = QFile::symLinkTarget(path).size(); + } + + return 0; +} + +std::function(const std::function&)> mp::platform::make_quit_watchdog( + const std::chrono::milliseconds& timeout) +{ + signal_event = CreateEvent(nullptr, TRUE, FALSE, nullptr); + if (signal_event == (HANDLE) nullptr) + throw std::runtime_error("Unable to create signal object\n"); + + SetConsoleCtrlHandler(signal_handler, TRUE); + + return [millis = timeout.count()](const std::function& condition) -> std::optional { + ResetEvent(signal_event); + + while (condition()) + { + // Ctrl+C will break this wait. + if (WaitForSingleObject(signal_event, millis) != WAIT_TIMEOUT) + return 0; + } + + return std::nullopt; + }; +} + +std::string mp::platform::reinterpret_interface_id(const std::string& ux_id) +{ + auto ps_cmd = QStringLiteral("Get-NetAdapter -Name \"%1\" | Select-Object -ExpandProperty InterfaceDescription") + .arg(QString::fromStdString(ux_id)) + .split(' ', Qt::SkipEmptyParts); + + QString ps_output; + QString ps_output_err; + if (PowerShell::exec(ps_cmd, "Adapter description from name", &ps_output, &ps_output_err)) + { + auto output_lines = ps_output.split(QRegularExpression{"[\r\n]"}, Qt::SkipEmptyParts); + if (output_lines.size() != 1) + { + throw std::runtime_error{ + fmt::format("Could not obtain adapter description from name \"{}\" - unexpected powershell output: {}", + ux_id, + ps_output)}; + } + + return output_lines.first().toStdString(); + } + + auto detail = ps_output_err.isEmpty() ? "" : fmt::format(" Detail: {}", ps_output_err); + auto err = + fmt::format("Could not obtain adapter description from name \"{}\" - error executing powershell command.{}", + ux_id, + detail); + throw std::runtime_error{err}; +} + +int mp::platform::Platform::get_cpus() const +{ + SYSTEM_INFO sysinfo; + GetSystemInfo(&sysinfo); + return sysinfo.dwNumberOfProcessors; +} + +long long mp::platform::Platform::get_total_ram() const +{ + MEMORYSTATUSEX status; + status.dwLength = sizeof(status); + GlobalMemoryStatusEx(&status); + return status.ullTotalPhys; +} + +std::filesystem::path mp::platform::Platform::get_root_cert_path() const +{ + return multipass_final_storage_location() / "data" / "certificates" / "multipass_root_cert.pem"; +} diff --git a/src/process/basic_process.cpp b/src/process/basic_process.cpp index 1d03254726..3d6eb22418 100644 --- a/src/process/basic_process.cpp +++ b/src/process/basic_process.cpp @@ -34,7 +34,9 @@ static auto reg = []() -> bool { mp::BasicProcess::CustomQProcess::CustomQProcess(BasicProcess* p) : QProcess{p} { +#ifndef MULTIPASS_PLATFORM_WINDOWS setChildProcessModifier([p] { p->setup_child_process(); }); +#endif } mp::BasicProcess::BasicProcess(std::shared_ptr spec) : process_spec{spec}, process{this} diff --git a/src/rpc/CMakeLists.txt b/src/rpc/CMakeLists.txt index c151a89fff..e6095860a4 100644 --- a/src/rpc/CMakeLists.txt +++ b/src/rpc/CMakeLists.txt @@ -16,7 +16,9 @@ set(MULTIPASS_PROTOCOL_SPEC multipass.proto) set(GRPC_GENERATED_SOURCE_DIR ${MULTIPASS_GENERATED_SOURCE_DIR}/multipass/rpc) file(MAKE_DIRECTORY ${GRPC_GENERATED_SOURCE_DIR}) -add_compile_options(-Wno-error=pedantic) +if(NOT MSVC) + add_compile_options(-Wno-error=pedantic) +endif() generate_grpc_cpp(GRPC_GENERATED_SOURCES ${GRPC_GENERATED_SOURCE_DIR} ${MULTIPASS_PROTOCOL_SPEC}) diff --git a/src/simplestreams/simple_streams_index.cpp b/src/simplestreams/simple_streams_index.cpp index 169a1cdd4f..95ed5a5ece 100644 --- a/src/simplestreams/simple_streams_index.cpp +++ b/src/simplestreams/simple_streams_index.cpp @@ -23,6 +23,8 @@ #include #include +#include + namespace mp = multipass; namespace diff --git a/src/ssh/ssh_client.cpp b/src/ssh/ssh_client.cpp index 731eaf4f57..0db54503c2 100644 --- a/src/ssh/ssh_client.cpp +++ b/src/ssh/ssh_client.cpp @@ -21,6 +21,11 @@ #include "ssh_client_key_provider.h" +#ifdef MULTIPASS_PLATFORM_WINDOWS +#include +#include +#endif + namespace mp = multipass; namespace @@ -76,6 +81,7 @@ int mp::SSHClient::exec(const std::vector>& args_list) void mp::SSHClient::handle_ssh_events() { +#ifndef MULTIPASS_PLATFORM_WINDOWS using ConnectorUPtr = std::unique_ptr; std::unique_ptr event{ssh_event_new(), ssh_event_free}; @@ -105,6 +111,22 @@ void mp::SSHClient::handle_ssh_events() ssh_event_remove_connector(event.get(), connector_in.get()); ssh_event_remove_connector(event.get(), connector_out.get()); ssh_event_remove_connector(event.get(), connector_err.get()); +#else + auto stdout_thread = std::thread([this]() { + while (ssh_channel_is_open(channel.get()) && !ssh_channel_is_eof(channel.get())) + { + console->write_console(); + } + console->exit_console(); + }); + + while (ssh_channel_is_open(channel.get()) && !ssh_channel_is_eof(channel.get())) + { + console->read_console(); + } + + stdout_thread.join(); +#endif } int mp::SSHClient::exec_string(const std::string& cmd_line) diff --git a/src/sshfs_mount/CMakeLists.txt b/src/sshfs_mount/CMakeLists.txt index 75b4949d17..0d9e771b2e 100644 --- a/src/sshfs_mount/CMakeLists.txt +++ b/src/sshfs_mount/CMakeLists.txt @@ -45,6 +45,9 @@ target_link_libraries(sshfs_server logger sshfs_mount) +set_target_properties(sshfs_server + PROPERTIES INSTALL_RPATH "@executable_path/../lib") + target_include_directories(sshfs_server BEFORE PRIVATE ${CMAKE_SOURCE_DIR}/src diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 872913db66..7d047e1d1c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -221,6 +221,14 @@ set_target_properties(mock_process add_dependencies(multipass_tests mock_process) +if(MSVC) + add_definitions(-DGTEST_LANG_CXX11=1) + target_compile_options(multipass_tests PRIVATE /bigobj) +elseif(APPLE) + set(CMAKE_CXX_FLAGS "-Wno-inconsistent-missing-override") + add_definitions(-DHOST_ARCH="${HOST_ARCH}") +endif() + target_include_directories(multipass_tests BEFORE PRIVATE ${CMAKE_SOURCE_DIR}/src/platform/backends/shared/${MULTIPASS_PLATFORM} diff --git a/tests/blueprint_test_lambdas.cpp b/tests/blueprint_test_lambdas.cpp index 25ac345e27..9c9f80aedb 100644 --- a/tests/blueprint_test_lambdas.cpp +++ b/tests/blueprint_test_lambdas.cpp @@ -38,7 +38,6 @@ std::function, const mp::Path&)> mpt::fetch_image_lambda(const std::string& release, const std::string& remote, const bool must_have_checksum) @@ -47,7 +46,6 @@ mpt::fetch_image_lambda(const std::string& release, const std::string& remote, c const mp::Query& query, const mp::VMImageVault::PrepareAction& prepare, const mp::ProgressMonitor& monitor, - const bool unlock, const std::optional& checksum, const mp::Path& save_dir) { EXPECT_EQ(query.release, release); @@ -65,7 +63,7 @@ mpt::fetch_image_lambda(const std::string& release, const std::string& remote, c EXPECT_NE(checksum, std::nullopt); } - return mpt::StubVMImageVault().fetch_image(fetch_type, query, prepare, monitor, unlock, checksum, save_dir); + return mpt::StubVMImageVault().fetch_image(fetch_type, query, prepare, monitor, checksum, save_dir); }; } diff --git a/tests/blueprint_test_lambdas.h b/tests/blueprint_test_lambdas.h index 63515e0dfa..a69d5d63a5 100644 --- a/tests/blueprint_test_lambdas.h +++ b/tests/blueprint_test_lambdas.h @@ -43,7 +43,6 @@ std::function, const multipass::Path&)> fetch_image_lambda(const std::string& release, const std::string& remote, const bool must_have_checksum = false); diff --git a/tests/file_operations.cpp b/tests/file_operations.cpp index 49c92d3749..06fd7213e3 100644 --- a/tests/file_operations.cpp +++ b/tests/file_operations.cpp @@ -27,6 +27,8 @@ #include #include +#include + namespace mpt = multipass::test; QByteArray mpt::load(QString path) diff --git a/tests/hyperv/CMakeLists.txt b/tests/hyperv/CMakeLists.txt new file mode 100644 index 0000000000..f325f56e9d --- /dev/null +++ b/tests/hyperv/CMakeLists.txt @@ -0,0 +1,4 @@ +target_sources(multipass_tests + PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/test_hyperv_backend.cpp +) diff --git a/tests/hyperv/test_hyperv_backend.cpp b/tests/hyperv/test_hyperv_backend.cpp new file mode 100644 index 0000000000..baf42dd618 --- /dev/null +++ b/tests/hyperv/test_hyperv_backend.cpp @@ -0,0 +1,742 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "tests/common.h" +#include "tests/mock_logger.h" +#include "tests/mock_platform.h" +#include "tests/mock_process_factory.h" +#include "tests/stub_ssh_key_provider.h" +#include "tests/stub_status_monitor.h" +#include "tests/temp_dir.h" +#include "tests/temp_file.h" +#include "tests/windows/powershell_test_helper.h" + +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; +namespace mpt = multipass::test; +using namespace testing; + +namespace multipass::test +{ +struct HyperVNetworkAccessor +{ + explicit HyperVNetworkAccessor(HyperVVirtualMachineFactory& backend) : backend{backend} + { + } + + static auto get_switches(const std::vector& adapters) + { + return mp::HyperVVirtualMachineFactory::get_switches(adapters); // private, but we're friends + } + + static auto get_adapters() + { + return mp::HyperVVirtualMachineFactory::get_adapters(); // private, but we're friends + } + + std::string create_bridge_with(const mp::NetworkInterfaceInfo& interface) + { + return backend.create_bridge_with(interface); // protected, but we're friends + } + + HyperVVirtualMachineFactory& backend; +}; +} // namespace multipass::test + +namespace +{ +struct HyperVBackend : public Test +{ + using RunSpec = mpt::PowerShellTestHelper::RunSpec; + + void SetUp() override + { + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + } + + void TearDown() override + { + ASSERT_TRUE(ps_helper.was_ps_run()); + } + + std::vector standard_ps_run_sequence(const std::vector& network_runs = {default_network_run}) + { + std::vector ret = prefix_ctor_runs; + ret.insert(std::end(ret), std::cbegin(network_runs), std::cend(network_runs)); + + auto failing_run_it = std::find_if(std::cbegin(network_runs), std::cend(network_runs), [](const auto& run) { + return !run.will_return; + }); + if (failing_run_it == std::cend(network_runs)) // if the ctor succeeds + { + // network runs are executed in the ctor, so if they fail the object is never contructed & no further cmds + // are executed for either ctor or dtor + ret.insert(std::end(ret), std::cbegin(postfix_ctor_runs), std::cend(postfix_ctor_runs)); + ret.emplace_back(min_dtor_run); + } + + return ret; + } + + inline static const std::vector prefix_ctor_runs = {{"Get-VM", "", false}, + {"Get-VMSwitch"}, + {"New-VM"}, + {"-EnableSecureBoot Off"}, + {"Set-VMProcessor"}, + {"Add-VMDvdDrive"}, + {"Set-VMMemory"}}; + inline static const std::vector postfix_ctor_runs = {{"Set-VM"}, {"Get-VMCheckpoint"}}; + inline static const RunSpec default_network_run = {"Set-VMNetworkAdapter"}; + inline static const RunSpec min_dtor_run = {"-ExpandProperty State", "Off"}; + + mpt::TempFile dummy_image; + mpt::TempFile dummy_cloud_init_iso; + mpt::TempDir data_dir; + mp::VirtualMachineDescription default_description{2, + mp::MemorySize{"3M"}, + mp::MemorySize{}, // not used, + "pied-piper-valley", + "ba:ba:ca:ca:ca:ba", + {}, + "", + {dummy_image.name(), "", "", "", "", {}}, + dummy_cloud_init_iso.name()}; + mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(); + mpt::PowerShellTestHelper ps_helper; + mp::HyperVVirtualMachineFactory backend{data_dir.path()}; + mpt::StubVMStatusMonitor stub_monitor; + mpt::StubSSHKeyProvider stub_key_provider; +}; + +TEST_F(HyperVBackend, creates_in_off_state) +{ + ps_helper.setup_mocked_run_sequence(standard_ps_run_sequence()); + + auto machine = backend.create_virtual_machine(default_description, stub_key_provider, stub_monitor); + ASSERT_THAT(machine.get(), NotNull()); + EXPECT_THAT(machine->state, Eq(mp::VirtualMachine::State::off)); +} + +TEST_F(HyperVBackend, sets_mac_address_on_default_network_adapter) +{ + auto network_run = RunSpec{fmt::format("Set-VMNetworkAdapter -VMName {} -StaticMacAddress \"{}\"", + default_description.vm_name, + default_description.default_mac_address)}; + ps_helper.setup_mocked_run_sequence(standard_ps_run_sequence({network_run})); + + backend.create_virtual_machine(default_description, stub_key_provider, stub_monitor); +} + +TEST_F(HyperVBackend, throws_on_failure_to_setup_default_network_adapter) +{ + auto default_tweaked_run = default_network_run; + default_tweaked_run.will_return = false; + + ps_helper.setup_mocked_run_sequence(standard_ps_run_sequence({default_tweaked_run, {"Get-VM"}})); + + MP_EXPECT_THROW_THAT(backend.create_virtual_machine(default_description, stub_key_provider, stub_monitor), + std::runtime_error, + Property(&std::runtime_error::what, HasSubstr("default adapter"))); +} + +TEST_F(HyperVBackend, adds_extra_network_adapters) +{ + default_description.extra_interfaces = {{"switchA", "55:66:44:77:33:88"}, + {"switchB", "15:16:14:17:13:18"}, + {"switchC", "5e:6f:4e:7f:3e:8f"}}; + + auto network_runs = std::vector{default_network_run}; + for (const auto& iface : default_description.extra_interfaces) + { + network_runs.push_back({fmt::format("Get-VMSwitch -Name \"{}\"", iface.id)}); + network_runs.push_back( + {fmt::format("Add-VMNetworkAdapter -VMName {} -SwitchName \"{}\" -StaticMacAddress \"{}\"", + default_description.vm_name, + iface.id, + iface.mac_address)}); + }; + + ps_helper.setup_mocked_run_sequence(standard_ps_run_sequence(std::move(network_runs))); + + backend.create_virtual_machine(default_description, stub_key_provider, stub_monitor); +} + +TEST_F(HyperVBackend, throws_on_failure_to_detect_switch_from_extra_interface) +{ + auto extra_iface = mp::NetworkInterface{"MissingSwitch", "55:66:44:77:33:88"}; + default_description.extra_interfaces.push_back(extra_iface); + + auto failing_cmd = fmt::format("Get-VMSwitch -Name \"{}\"", extra_iface.id); + ps_helper.setup_mocked_run_sequence( + standard_ps_run_sequence({default_network_run, {failing_cmd, "", false}, {"Get-VM"}})); + + MP_EXPECT_THROW_THAT( + backend.create_virtual_machine(default_description, stub_key_provider, stub_monitor), + std::runtime_error, + Property(&std::runtime_error::what, AllOf(HasSubstr("Could not find"), HasSubstr(extra_iface.id)))); +} + +TEST_F(HyperVBackend, throws_on_failure_to_add_extra_interface) +{ + auto extra_iface = mp::NetworkInterface{"SuperPriviledgedSwitch", "55:66:44:77:33:88"}; + default_description.extra_interfaces.push_back(extra_iface); + + auto failing_cmd = fmt::format("Add-VMNetworkAdapter -VMName {} -SwitchName \"{}\" -StaticMacAddress \"{}\"", + default_description.vm_name, + extra_iface.id, + extra_iface.mac_address); + + ps_helper.setup_mocked_run_sequence( + standard_ps_run_sequence({default_network_run, {"Get-VMSwitch"}, {failing_cmd, "", false}, {"Get-VM"}})); + + MP_EXPECT_THROW_THAT( + backend.create_virtual_machine(default_description, stub_key_provider, stub_monitor), + std::runtime_error, + Property(&std::runtime_error::what, AllOf(HasSubstr("Could not setup"), HasSubstr(extra_iface.id)))); +} + +TEST_F(HyperVBackend, createBridgeRequestsNewSwitch) +{ + const mp::NetworkInterfaceInfo net{"asdf", "ethernet", "The asdf net"}; + + ps_helper.setup( + [&net](auto* process) { + EXPECT_THAT(process->arguments(), + IsSupersetOf({mpt::match_qstring("New-VMSwitch"), + mpt::match_qstring(HasSubstr("ExtSwitch")), + mpt::match_qstring(HasSubstr(net.id))})); + EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(true)); + }, + /* auto_exit = */ false); + + EXPECT_ANY_THROW(mpt::HyperVNetworkAccessor{backend}.create_bridge_with(net)); +} + +TEST_F(HyperVBackend, createBridgeReturnsNewSwitchName) +{ + const mp::NetworkInterfaceInfo net{"e1", "ethernet", "Ethernet network"}; + const auto switch_name = fmt::format("ExtSwitch ({})", net.id); + ps_helper.mock_ps_exec(QByteArray::fromStdString(switch_name)); + EXPECT_THAT(mpt::HyperVNetworkAccessor{backend}.create_bridge_with(net), Eq(switch_name)); +} + +TEST_F(HyperVBackend, createBridgeThrowsOnNameMismatch) +{ + const auto bad = "wrong"; + ps_helper.mock_ps_exec(bad); + + MP_EXPECT_THROW_THAT(mpt::HyperVNetworkAccessor{backend}.create_bridge_with({"lagwagon", "ethernet", "duh"}), + std::runtime_error, + mpt::match_what(HasSubstr(bad))); +} + +TEST_F(HyperVBackend, createBridgeThrowsOnProcessFailure) +{ + const mp::NetworkInterfaceInfo net{"rerere", "ethernet", "lilo"}; + ps_helper.mock_ps_exec(std::nullopt, + QByteArray::fromStdString(fmt::format("ExtSwitch ({})", net.id)), + /* succeed = */ false); + + logger_scope.mock_logger->expect_log(mpl::Level::warning, "Process failed"); + logger_scope.mock_logger->expect_log(mpl::Level::warning, "stderr"); + MP_EXPECT_THROW_THAT(mpt::HyperVNetworkAccessor{backend}.create_bridge_with(net), + std::runtime_error, + mpt::match_what(HasSubstr("Could not create external switch"))); +} + +TEST_F(HyperVBackend, createBridgeIncludesErrorMsgInException) +{ + const auto error = "Bad Astronaut"; + ps_helper.mock_ps_exec(std::nullopt, error, /* succeed = */ false); + + logger_scope.mock_logger->expect_log(mpl::Level::warning, "Process failed"); + logger_scope.mock_logger->expect_log(mpl::Level::warning, "stderr"); + MP_EXPECT_THROW_THAT(mpt::HyperVNetworkAccessor{backend}.create_bridge_with({"Needle", "ethernet", "in the hay"}), + std::runtime_error, + mpt::match_what(HasSubstr(error))); +} + +struct CheckFineSuite : public HyperVBackend, public WithParamInterface> +{ +}; + +TEST_P(CheckFineSuite, CheckDoesntThrow) +{ + ps_helper.setup_mocked_run_sequence(GetParam()); + EXPECT_NO_THROW(backend.hypervisor_health_check()); +} + +INSTANTIATE_TEST_SUITE_P( + HyperVBackend, + CheckFineSuite, + // Common case, vmms running + Values(std::vector{{"CurrentMajorVersionNumber", "10"}, + {"ReleaseId", "1803"}, + {"HypervisorPresent", "True"}, + {"Microsoft-Hyper-V", "Enabled"}, + {"Microsoft-Hyper-V-Hypervisor", "Enabled"}, + {"vmms", "Running"}}, + // Common case, vmms needs to be started + std::vector{{"CurrentMajorVersionNumber", "10"}, + {"ReleaseId", "1803"}, + {"HypervisorPresent", "True"}, + {"Microsoft-Hyper-V", "Enabled"}, + {"Microsoft-Hyper-V-Hypervisor", "Enabled"}, + {"vmms", "Stopped"}, + {"Get-Service", "Automatic"}, + {"Start-Service"}}, + // New ReleaseId format + std::vector{{"CurrentMajorVersionNumber", "10"}, + {"ReleaseId", "21H2"}, + {"HypervisorPresent", "True"}, + {"Microsoft-Hyper-V", "Enabled"}, + {"Microsoft-Hyper-V-Hypervisor", "Enabled"}, + {"vmms", "Running"}}, + // Windows 11, no need to check ReleaseId + std::vector{{"CurrentMajorVersionNumber", "11"}, + {"HypervisorPresent", "True"}, + {"Microsoft-Hyper-V", "Enabled"}, + {"Microsoft-Hyper-V-Hypervisor", "Enabled"}, + {"vmms", "Running"}})); + +struct CheckBadSuite : public HyperVBackend, public WithParamInterface> +{ +}; + +TEST_P(CheckBadSuite, CheckThrows) +{ + ps_helper.setup_mocked_run_sequence(GetParam()); + EXPECT_THROW(backend.hypervisor_health_check(), std::runtime_error); +} + +INSTANTIATE_TEST_SUITE_P( + HyperVBackend, + CheckBadSuite, + // Windows 7 + Values(std::vector{{"CurrentMajorVersionNumber", "7"}}, + // Windows 10, too old + std::vector{{"CurrentMajorVersionNumber", "10"}, {"ReleaseId", "1802"}}, + // vmms service fails to start + std::vector{{"CurrentMajorVersionNumber", "11"}, + {"HypervisorPresent", "True"}, + {"Microsoft-Hyper-V", "Enabled"}, + {"Microsoft-Hyper-V-Hypervisor", "Enabled"}, + {"vmms", "Stopped"}, + {"Get-Service", "Automatic"}, + {"Start-Service", "", false}}, + // vmms service disabled + std::vector{{"CurrentMajorVersionNumber", "11"}, + {"HypervisorPresent", "True"}, + {"Microsoft-Hyper-V", "Enabled"}, + {"Microsoft-Hyper-V-Hypervisor", "Enabled"}, + {"vmms", "Stopped"}, + {"Get-Service", "Disabled"}})); +struct HyperVNetworks : public Test +{ + void SetUp() override + { + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + } + + std::map network_map_from_vector(std::vector nets) + { + std::map ret; + for (const auto& net : nets) + { + auto id = net.id; // avoid param evaluation order issues - we'd need the copy anyway + ret.emplace(std::move(id), std::move(net)); + } + + return ret; + } + + mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(); + mpt::MockPlatform::GuardedMock attr = mpt::MockPlatform::inject(); + mpt::MockPlatform* mock_platform = attr.first; + mpt::TempDir data_dir; + mp::HyperVVirtualMachineFactory backend{data_dir.path()}; +}; + +struct HyperVNetworksPS : public HyperVNetworks +{ + void TearDown() override + { + ASSERT_TRUE(ps_helper.was_ps_run()); + } + + mpt::PowerShellTestHelper ps_helper; + inline static constexpr auto cmdlet = "Get-VMSwitch"; +}; + +TEST_F(HyperVNetworksPS, requestsSwitches) +{ + ps_helper.setup( + [](auto* process) { + EXPECT_THAT(process->arguments(), Contains(cmdlet)); + EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(true)); + }, + /* auto_exit = */ false); + + backend.networks(); +} + +TEST_F(HyperVNetworksPS, requestsPlatformInterfaces) +{ + ps_helper.mock_ps_exec(""); + EXPECT_CALL(*mock_platform, get_network_interfaces_info).Times(1); + backend.networks(); +} + +TEST_F(HyperVNetworksPS, joinsSwitchesAndAdapters) +{ + ps_helper.mock_ps_exec("switch,External, a switch,\n"); + EXPECT_CALL(*mock_platform, get_network_interfaces_info) + .WillOnce(Return(network_map_from_vector({{"eth", "ethernet", "wired"}}))); + + auto got_nets = backend.networks(); + EXPECT_THAT(got_nets, SizeIs(2)); + EXPECT_THAT(got_nets, Contains(Field(&mp::NetworkInterfaceInfo::type, Eq("switch")))); + EXPECT_THAT(got_nets, Contains(Field(&mp::NetworkInterfaceInfo::type, Eq("ethernet")))); +} + +TEST_F(HyperVNetworksPS, throwsOnFailureToExecuteCmdlet) +{ + constexpr auto error = "error msg"; + + auto& logger = *logger_scope.mock_logger; + logger.screen_logs(mpl::Level::warning); + logger.expect_log(mpl::Level::warning, "Process failed"); + logger.expect_log(mpl::Level::warning, error); + + ps_helper.mock_ps_exec(std::nullopt, error, false); + MP_ASSERT_THROW_THAT(backend.networks(), std::runtime_error, Property(&std::runtime_error::what, HasSubstr(error))); +} + +TEST_F(HyperVNetworksPS, throwsOnUnexpectedCmdletOutput) +{ + constexpr auto output = "g1bb€r1$h"; + ps_helper.mock_ps_exec(output); + MP_ASSERT_THROW_THAT(backend.networks(), + std::runtime_error, + Property(&std::runtime_error::what, AllOf(HasSubstr(output), HasSubstr("unexpected")))); +} + +struct TestWrongNumFields : public HyperVNetworksPS, public WithParamInterface +{ + inline static constexpr auto bad_line_in_output_format = "a,few,,\ngood,lines,,\n{}\naround,a,,\nbad,one,,"; +}; + +TEST_P(TestWrongNumFields, throwsOnOutputWithWrongFields) +{ + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format(bad_line_in_output_format, GetParam()))); + ASSERT_THROW(backend.networks(), std::runtime_error); +} + +INSTANTIATE_TEST_SUITE_P(HyperVNetworksPS, + TestWrongNumFields, + Values("too,many,fields,in,here", "insufficient,fields")); + +struct TestNonExternalSwitchesWithLinks : public HyperVNetworksPS, public WithParamInterface +{ + inline static constexpr auto bad_line_in_output_format = TestWrongNumFields::bad_line_in_output_format; +}; + +TEST_P(TestNonExternalSwitchesWithLinks, throwsOnNonExternalSwitchWithLink) +{ + constexpr auto link_description = "foo bar net"; + EXPECT_CALL(*mock_platform, get_network_interfaces_info) + .WillOnce(Return(network_map_from_vector({{"eth", "ethernet", link_description}}))); + + auto switch_type = GetParam(); + auto switch_line = fmt::format("a switch,{},{},", switch_type, link_description); + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format(bad_line_in_output_format, switch_line))); + + MP_ASSERT_THROW_THAT(backend.networks(), + std::runtime_error, + mpt::match_what(AllOf(HasSubstr("Unexpected"), HasSubstr("non-external")))); +} + +INSTANTIATE_TEST_SUITE_P(HyperVNetworksPS, TestNonExternalSwitchesWithLinks, Values("internal", "private")); + +template +QRegularExpression make_case_insensitive_regex(Str&& str) +{ + return QRegularExpression{std::forward(str), QRegularExpression::CaseInsensitiveOption}; +} + +template +auto make_required_forbidden_regex_matcher(Str1&& required, Str2&& forbidden) +{ + return Truly([required = make_case_insensitive_regex(std::forward(required)), + forbidden = make_case_insensitive_regex(std::forward(forbidden))](const std::string& str) { + auto qstr = QString::fromStdString(str); + return qstr.contains(required) && !qstr.contains(forbidden); + }); +} + +template +auto adapt_to_single_description_matcher(Matcher&& matcher) +{ + return ElementsAre(Field(&mp::NetworkInterfaceInfo::description, std::forward(matcher))); +} + +struct TestNonExternalSwitchTypes : public HyperVNetworksPS, public WithParamInterface +{ +}; + +TEST_P(TestNonExternalSwitchTypes, recognizes_switch_type) +{ + const auto& type = GetParam(); + const auto matcher = + adapt_to_single_description_matcher(make_required_forbidden_regex_matcher(type, "external|unknown")); + + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format("some switch,{},,", type))); + EXPECT_THAT(backend.networks(), matcher); +} + +INSTANTIATE_TEST_SUITE_P(HyperVNetworksPS, TestNonExternalSwitchTypes, Values("Private", "Internal")); + +TEST_F(HyperVNetworksPS, recognizesExternalSwitch) +{ + const auto name = "some switch"; + + const auto id_matcher = Field(&mp::NetworkInterfaceInfo::id, name); + const auto type_matcher = Field(&mp::NetworkInterfaceInfo::type, "switch"); + const auto desc_matcher = + Field(&mp::NetworkInterfaceInfo::description, make_required_forbidden_regex_matcher("external", "unknown")); + const auto switch_matcher = AllOf(id_matcher, type_matcher, desc_matcher); + + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format("{},external,fake nic,", name))); + EXPECT_THAT(backend.networks(), ElementsAre(switch_matcher)); +} + +TEST_F(HyperVNetworksPS, handlesUnknownSwitchTypes) +{ + constexpr auto type = "Strange"; + const auto matcher = adapt_to_single_description_matcher( + AllOf(make_required_forbidden_regex_matcher("unknown", "private|internal|external"), HasSubstr(type))); + + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format("Custom Switch,{},,", type))); + EXPECT_THAT(backend.networks(), matcher); +} + +TEST_F(HyperVNetworksPS, includesSwitchLinksToKnownAdapters) +{ + mp::NetworkInterfaceInfo net_a{"a", "ethernet", "an a a aaa"}; + mp::NetworkInterfaceInfo net_c{"c", "ethernet", "a c cc cc"}; + + EXPECT_CALL(*mock_platform, get_network_interfaces_info).WillOnce(Return(network_map_from_vector({net_a, net_c}))); + ps_helper.mock_ps_exec( + QByteArray::fromStdString(fmt::format("switch_{},external,{},", net_c.id, net_c.description))); + + auto match = [](const auto& expect_link) { + return AllOf(Field(&mp::NetworkInterfaceInfo::id, EndsWith(expect_link)), + Field(&mp::NetworkInterfaceInfo::links, ElementsAre(expect_link))); + }; + EXPECT_THAT(backend.networks(), IsSupersetOf({match(net_c.id)})); +} + +struct TestSwitchUnsupportedLinks : public HyperVNetworksPS, + public WithParamInterface> +{ +}; + +TEST_P(TestSwitchUnsupportedLinks, excludesSwitchLinksToUnknownAdapters) +{ + EXPECT_CALL(*mock_platform, get_network_interfaces_info).WillOnce(Return(network_map_from_vector(GetParam()))); + ps_helper.mock_ps_exec("switchin,external,crazy adapter,\nnope,external,nope,"); + + auto switch_matcher = + AllOf(Field(&mp::NetworkInterfaceInfo::type, Eq("switch")), Field(&mp::NetworkInterfaceInfo::links, IsEmpty())); + EXPECT_THAT(backend.networks(), IsSupersetOf({switch_matcher, switch_matcher})); // expect two such switches +} + +TEST_P(TestSwitchUnsupportedLinks, omitsUnsupportedAdapterFromExternalSwitchDescription) +{ + EXPECT_CALL(*mock_platform, get_network_interfaces_info).WillOnce(Return(network_map_from_vector(GetParam()))); + const auto desc_matcher = + Field(&mp::NetworkInterfaceInfo::description, + make_required_forbidden_regex_matcher("^(?=.*switch)(?=.*external)", "via|internal|private")); + + ps_helper.mock_ps_exec("some switch,external,some unknown NIC,"); + EXPECT_THAT(backend.networks(), Contains(desc_matcher)); +} + +INSTANTIATE_TEST_SUITE_P(HyperVNetworksPS, + TestSwitchUnsupportedLinks, + Values(std::vector{}, + std::vector{{"nic", "wifi", "a wifi"}, + {"eth", "ethernet", "an ethernet"}}, + std::vector{{"nic", "crazy_type", "some unknown NIC"}, + {"eth", "ethernet", "an ethernet"}})); + +TEST_F(HyperVNetworksPS, includesSupportedAdapterInExternalSwitchDescription) +{ + mp::NetworkInterfaceInfo eth{"Ethernet", "ethernet", "An Ethernet NIC"}; + mp::NetworkInterfaceInfo other{"Quantumwire", "quantum wire", "Future tech"}; + EXPECT_CALL(*mock_platform, get_network_interfaces_info).WillOnce(Return(network_map_from_vector({eth, other}))); + + auto match = [](const auto& expect_link) { + return Field(&mp::NetworkInterfaceInfo::description, + AllOf(make_required_forbidden_regex_matcher("external", "unknown"), HasSubstr(expect_link))); + }; + + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format("some switch,external,{},\n", eth.description))); + EXPECT_THAT(backend.networks(), IsSupersetOf({match(eth.id)})); +} + +TEST_F(HyperVNetworksPS, includesExistingNotesInSwitchDescription) +{ + constexpr auto notes = "custom notes"; + constexpr auto adapter_id = "Ethernet"; + constexpr auto output_format = "PrivSwitch,Private,,{0}\n" + "IntSwitch,Internal,,{0}\n" + "ExtSwitchA,External,,{0}\n" + "ExtSwitchB,External,{1},{0}\n"; + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format(output_format, notes, adapter_id))); + + EXPECT_CALL(*mock_platform, get_network_interfaces_info) + .WillOnce(Return(network_map_from_vector({mp::NetworkInterfaceInfo{adapter_id, "ethernet", "eth adapter"}}))); + + auto matchers = std::vector{4, Field(&mp::NetworkInterfaceInfo::description, HasSubstr(notes))}; + matchers.push_back(Field(&mp::NetworkInterfaceInfo::id, Eq(adapter_id))); + EXPECT_THAT(backend.networks(), UnorderedElementsAreArray(matchers)); +} + +struct TestAdapterAuthorization : public HyperVNetworksPS, public WithParamInterface +{ +}; + +TEST_P(TestAdapterAuthorization, requiresNoAuthorizationForKnownAdaptersInSwitches) +{ + const auto& net = GetParam(); + EXPECT_CALL(*mock_platform, get_network_interfaces_info).WillOnce(Return(network_map_from_vector({net}))); + + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format("switch,external,{},\n", net.description))); + EXPECT_THAT(backend.networks(), + Contains(AllOf(Field(&mp::NetworkInterfaceInfo::id, net.id), + Field(&mp::NetworkInterfaceInfo::needs_authorization, false)))); +} + +TEST_P(TestAdapterAuthorization, requiresAuthorizationForKnownAdaptersInNoSwitches) +{ + const auto& net = GetParam(); + EXPECT_CALL(*mock_platform, get_network_interfaces_info).WillOnce(Return(network_map_from_vector({net}))); + + ps_helper.mock_ps_exec("switch,external,unknown adapter,\n"); + EXPECT_THAT(backend.networks(), + Contains(AllOf(Field(&mp::NetworkInterfaceInfo::id, net.id), + Field(&mp::NetworkInterfaceInfo::needs_authorization, true)))); +} + +TEST_P(TestAdapterAuthorization, requiresNoAuthorizationForSwitches) +{ + const auto& net = GetParam(); + EXPECT_CALL(*mock_platform, get_network_interfaces_info).WillOnce(Return(network_map_from_vector({net}))); + + constexpr auto ps_output = "ext_switch_a,external,unknown adapter,\next_switch_a,external,{}," + "\nint_switch,internal,,\npriv_switch,private,,\n"; + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format(ps_output, net.description))); + + const auto networks = backend.networks(); + EXPECT_THAT(std::count_if(networks.cbegin(), networks.cend(), [](const auto& x) { return x.type == "switch"; }), 4); + EXPECT_THAT(networks, + Each(AnyOf(Field(&mp::NetworkInterfaceInfo::type, Ne("switch")), + Field(&mp::NetworkInterfaceInfo::needs_authorization, false)))); +} + +INSTANTIATE_TEST_SUITE_P(HyperVNetworkPS, + TestAdapterAuthorization, + Values(mp::NetworkInterfaceInfo{"abc", "ethernet", "An adapter", {}, false}, + mp::NetworkInterfaceInfo{"ghi", "ethernet", "Yet another", {"x", "y", "z"}, false})); + +TEST_F(HyperVNetworksPS, getSwitchesReturnsEmptyWhenNoSwitchesFound) +{ + ps_helper.mock_ps_exec(""); + EXPECT_THAT(mpt::HyperVNetworkAccessor::get_switches({}), IsEmpty()); +} + +TEST_F(HyperVNetworksPS, getSwitchesReturnsAsManyItemsAsLinesInProperOutput) +{ + ps_helper.mock_ps_exec("a,b,,\nd,e,,\ng,h,,\nj,k,,\n,,,\n,m,,\njj,external,asdf,\n"); + EXPECT_THAT(mpt::HyperVNetworkAccessor::get_switches({{}}), SizeIs(7)); +} + +TEST_F(HyperVNetworksPS, getSwitchesReturnsProvidedInterfaceIds) +{ + constexpr auto id1 = "\"toto\""; + constexpr auto id2 = " te et te"; + constexpr auto id3 = "\"ti\"-+%ti\t"; + constexpr auto output_format = "{},Private,,\n" + "{},Internal,,\n" + "{},External,adapter description,\n"; + + ps_helper.mock_ps_exec(QByteArray::fromStdString(fmt::format(output_format, id1, id2, id3))); + auto id_matcher = [](const auto& expect) { return Field(&mp::NetworkInterfaceInfo::id, expect); }; + EXPECT_THAT(mpt::HyperVNetworkAccessor::get_switches({{}, {}}), + UnorderedElementsAre(id_matcher(id1), id_matcher(id2), id_matcher(id3))); +} + +TEST_F(HyperVNetworksPS, getSwitchesReturnsOnlySwitches) +{ + ps_helper.mock_ps_exec("a,b,,\nc,d,,\nasdf,internal,,\nsdfg,external,dfgh,\nfghj,private,,"); + EXPECT_THAT(mpt::HyperVNetworkAccessor::get_switches({}), Each(Field(&mp::NetworkInterfaceInfo::type, "switch"))); +} + +TEST_F(HyperVNetworks, getAdaptersReturnsEthernetAndNoWifi) +{ + mp::NetworkInterfaceInfo strange{"strange", "strangewire", "waka waka"}; + mp::NetworkInterfaceInfo weird{"weird", "future tech", "wika wika"}; + mp::NetworkInterfaceInfo unknown{"virtio", "unknown", "wuka wuka"}; + mp::NetworkInterfaceInfo eth1{"eth1", "ethernet", "ethththth"}; + mp::NetworkInterfaceInfo eth2{"eth2", "ethernet", "ethththth"}; + mp::NetworkInterfaceInfo wifi1{"wireless1", "wifi", "wiiiiiii"}; + + EXPECT_CALL(*mock_platform, get_network_interfaces_info) + .WillOnce(Return(network_map_from_vector({strange, eth1, unknown, eth2, weird}))); + + auto got_nets = mpt::HyperVNetworkAccessor::get_adapters(); + EXPECT_EQ(got_nets.size(), 2); + + auto same_net = [](const mp::NetworkInterfaceInfo& a, const mp::NetworkInterfaceInfo& b) { + return make_tuple(a.id, a.type, a.description) == make_tuple(b.id, b.type, b.description); + }; + + for (const auto& expected_net : {eth1, eth2}) + EXPECT_TRUE(std::any_of(got_nets.begin(), got_nets.end(), [&expected_net, &same_net](const auto& got_net) { + return same_net(got_net, expected_net); + })); + + for (const auto& got_net : got_nets) + EXPECT_FALSE(same_net(got_net, wifi1)); +} + +} // namespace diff --git a/tests/json_test_utils.cpp b/tests/json_test_utils.cpp index ca2d4dc692..75a1c92fde 100644 --- a/tests/json_test_utils.cpp +++ b/tests/json_test_utils.cpp @@ -123,7 +123,7 @@ void check_interfaces_in_json(const QJsonObject& doc_object, ASSERT_EQ((unsigned)extra.size(), extra_ifaces.size()); auto it = extra_ifaces.cbegin(); - for (const auto& extra_i : extra) + for (const auto extra_i : extra) { const auto interface = extra_i.toObject(); ASSERT_EQ(interface["mac_address"].toString().toStdString(), it->mac_address); @@ -153,7 +153,7 @@ void check_mounts_in_json(const QJsonObject& doc_object, const std::unordered_ma const auto json_mounts = instance_object["mounts"].toArray(); ASSERT_EQ(json_mounts.count(), mounts.size()); - for (const QJsonValue& json_mount : json_mounts) + for (const QJsonValue json_mount : json_mounts) { const auto& json_target_path = json_mount["target_path"].toString().toStdString(); const auto& json_source_path = json_mount["source_path"].toString().toStdString(); diff --git a/tests/linux/test_platform_linux.cpp b/tests/linux/test_platform_linux.cpp index 137140629a..6c51db0b7f 100644 --- a/tests/linux/test_platform_linux.cpp +++ b/tests/linux/test_platform_linux.cpp @@ -176,39 +176,6 @@ TEST_F(PlatformLinux, test_libvirt_in_env_var_is_ignored) aux_test_driver_factory(DEFAULT_DRIVER); } -TEST_F(PlatformLinux, blueprintsURLOverrideSetReturnsExpectedData) -{ - const QString fake_url{"https://a.fake.url"}; - mpt::SetEnvScope blueprints_url("MULTIPASS_BLUEPRINTS_URL", fake_url.toUtf8()); - - EXPECT_EQ(MP_PLATFORM.get_blueprints_url_override(), fake_url); -} - -TEST_F(PlatformLinux, blueprintsURLOverrideNotSetReturnsEmptyString) -{ - EXPECT_TRUE(MP_PLATFORM.get_blueprints_url_override().isEmpty()); -} - -TEST_F(PlatformLinux, test_is_remote_supported_returns_true) -{ - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("release")); - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("daily")); - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("")); - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("snapcraft")); - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("appliance")); -} - -TEST_F(PlatformLinux, test_is_remote_supported_lxd) -{ - setup_driver_settings("lxd"); - - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("release")); - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("daily")); - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("")); - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("appliance")); - EXPECT_TRUE(MP_PLATFORM.is_remote_supported("snapcraft")); -} - TEST_F(PlatformLinux, test_snap_returns_expected_default_address) { const QByteArray base_dir{"/tmp"}; @@ -230,11 +197,6 @@ TEST_F(PlatformLinux, test_not_snap_returns_expected_default_address) EXPECT_EQ(mp::platform::default_server_address(), fmt::format("unix:/run/multipass_socket")); } -TEST_F(PlatformLinux, test_is_alias_supported_returns_true) -{ - EXPECT_TRUE(MP_PLATFORM.is_alias_supported("focal", "release")); -} - struct TestUnsupportedDrivers : public PlatformLinux, WithParamInterface { }; diff --git a/tests/lxd/test_lxd_backend.cpp b/tests/lxd/test_lxd_backend.cpp index 5de1d4f70e..60e6a69957 100644 --- a/tests/lxd/test_lxd_backend.cpp +++ b/tests/lxd/test_lxd_backend.cpp @@ -2302,7 +2302,7 @@ class CustomLXDFactory : public mp::LXDVirtualMachineFactory }; } // namespace -TEST_F(LXDBackend, prepares_networking_via_base_factory) +TEST_F(LXDBackend, preparesNetworkingViaBaseFactory) { CustomLXDFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url}; std::vector extra_networks{{"netid", "mac", false}}; diff --git a/tests/lxd/test_lxd_image_vault.cpp b/tests/lxd/test_lxd_image_vault.cpp index ad0cbb480e..9fb8b0ca36 100644 --- a/tests/lxd/test_lxd_image_vault.cpp +++ b/tests/lxd/test_lxd_image_vault.cpp @@ -99,7 +99,6 @@ TEST_F(LXDImageVault, instance_exists_fetch_returns_expected_image_info) default_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path())); @@ -132,7 +131,6 @@ TEST_F(LXDImageVault, instance_exists_custom_image_returns_expected_image_info) default_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path())); @@ -166,7 +164,6 @@ TEST_F(LXDImageVault, instance_exists_uses_cached_release_title) default_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path())); @@ -201,7 +198,6 @@ TEST_F(LXDImageVault, instance_exists_no_cached_release_title_info_for_fails) default_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path())); @@ -236,7 +232,6 @@ TEST_F(LXDImageVault, returns_expected_info_with_valid_remote) query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path())); @@ -267,13 +262,8 @@ TEST_F(LXDImageVault, throws_with_invalid_alias) base_url, cache_dir.path(), mp::days{0}}; MP_EXPECT_THROW_THAT( - image_vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - save_dir.path()), + image_vault + .fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, save_dir.path()), std::runtime_error, mpt::match_what( StrEq(fmt::format("Unable to find an image matching \"{}\" in remote \"{}\".", alias, "release")))); @@ -291,15 +281,11 @@ TEST_F(LXDImageVault, throws_with_invalid_remote) mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(), base_url, cache_dir.path(), mp::days{0}}; - MP_EXPECT_THROW_THAT(image_vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - save_dir.path()), - std::runtime_error, - mpt::match_what(HasSubstr(fmt::format("Remote \'{}\' is not found.", remote)))); + MP_EXPECT_THROW_THAT( + image_vault + .fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, save_dir.path()), + std::runtime_error, + mpt::match_what(HasSubstr(fmt::format("Remote \'{}\' is not found.", remote)))); } TEST_F(LXDImageVault, does_not_download_if_image_exists) @@ -330,7 +316,6 @@ TEST_F(LXDImageVault, does_not_download_if_image_exists) default_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path())); } @@ -372,7 +357,6 @@ TEST_F(LXDImageVault, instance_exists_missing_image_does_not_download_image) default_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path())); EXPECT_FALSE(download_requested); @@ -404,7 +388,6 @@ TEST_F(LXDImageVault, requests_download_if_image_does_not_exist) default_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path())); EXPECT_TRUE(download_requested); @@ -433,13 +416,9 @@ TEST_F(LXDImageVault, sets_fingerprint_with_hash_query) base_url, cache_dir.path(), mp::days{0}}; const mp::Query query{"", "e3b0c44298fc1c1", false, "release", mp::Query::Type::Alias}; - EXPECT_NO_THROW(image_vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - save_dir.path())); + EXPECT_NO_THROW( + image_vault + .fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, save_dir.path())); } TEST_F(LXDImageVault, download_deletes_and_throws_on_cancel) @@ -477,14 +456,10 @@ TEST_F(LXDImageVault, download_deletes_and_throws_on_cancel) mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(), base_url, cache_dir.path(), mp::days{0}}; - EXPECT_THROW(image_vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - stub_prepare, - monitor, - false, - std::nullopt, - save_dir.path()), - mp::AbortedDownloadException); + EXPECT_THROW( + image_vault + .fetch_image(mp::FetchType::ImageOnly, default_query, stub_prepare, monitor, std::nullopt, save_dir.path()), + mp::AbortedDownloadException); EXPECT_TRUE(delete_requested); } @@ -520,14 +495,10 @@ TEST_F(LXDImageVault, percent_complete_returns_negative_on_metadata_download) mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(), base_url, cache_dir.path(), mp::days{0}}; - EXPECT_THROW(image_vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - stub_prepare, - monitor, - false, - std::nullopt, - save_dir.path()), - mp::AbortedDownloadException); + EXPECT_THROW( + image_vault + .fetch_image(mp::FetchType::ImageOnly, default_query, stub_prepare, monitor, std::nullopt, save_dir.path()), + mp::AbortedDownloadException); } TEST_F(LXDImageVault, delete_requested_on_instance_remove) @@ -901,7 +872,6 @@ TEST_F(LXDImageVault, custom_image_found_returns_expected_info) query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path()); @@ -964,7 +934,6 @@ TEST_F(LXDImageVault, custom_image_downloads_and_creates_correct_upload) query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path()); @@ -994,7 +963,6 @@ TEST_F(LXDImageVault, fetch_image_unable_to_connect_logs_error_and_returns_blank default_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path()); @@ -1127,7 +1095,6 @@ TEST_F(LXDImageVault, http_based_image_downloads_and_creates_correct_upload) query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path()); @@ -1198,7 +1165,6 @@ TEST_F(LXDImageVault, file_based_fetch_copies_image_and_returns_expected_info) query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.path()); @@ -1221,15 +1187,11 @@ TEST_F(LXDImageVault, invalid_local_file_image_throws) const std::string missing_file{"/foo"}; const mp::Query query{"", fmt::format("file://{}", missing_file), false, "", mp::Query::Type::LocalFile}; - MP_EXPECT_THROW_THAT(image_vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - save_dir.path()), - std::runtime_error, - mpt::match_what(StrEq(fmt::format("Custom image `{}` does not exist.", missing_file)))); + MP_EXPECT_THROW_THAT( + image_vault + .fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, save_dir.path()), + std::runtime_error, + mpt::match_what(StrEq(fmt::format("Custom image `{}` does not exist.", missing_file)))); } TEST_F(LXDImageVault, updateImagesThrowsOnMissingImage) diff --git a/tests/macos/CMakeLists.txt b/tests/macos/CMakeLists.txt new file mode 100644 index 0000000000..861b210ee5 --- /dev/null +++ b/tests/macos/CMakeLists.txt @@ -0,0 +1,5 @@ +target_sources(multipass_tests + PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/test_platform_osx.cpp + ${CMAKE_CURRENT_LIST_DIR}/test_backend_utils.cpp +) diff --git a/tests/macos/test_backend_utils.cpp b/tests/macos/test_backend_utils.cpp new file mode 100644 index 0000000000..f479f66987 --- /dev/null +++ b/tests/macos/test_backend_utils.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "src/platform/backends/shared/macos/backend_utils.h" +#include "tests/mock_process_factory.h" + +namespace mp = multipass; +namespace mpt = multipass::test; + +namespace +{ +const QByteArray mock_arp_output_stream = QByteArray{R"( +? (192.168.1.1) at 3c:37:86:8a:e6:84 on en0 ifscope [ethernet] +? (192.168.1.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet] +? (192.168.64.2) at 52:54:0:2a:12:b6 on bridge100 ifscope [bridge] +? (192.168.64.3) at 52:54:0:85:72:55 on bridge100 ifscope [bridge] +? (192.168.64.4) at 52:54:0:e1:cd:ab on bridge100 ifscope [bridge] +? (192.168.64.255) at ff:ff:ff:ff:ff:ff on bridge100 ifscope [bridge] +? (224.0.0.251) at 1:0:5e:0:0:fb on en0 ifscope permanent [ethernet])"}; +} + +class GetNeighbourIpFixture : public Test +{ +public: + GetNeighbourIpFixture() + { + mpt::MockProcessFactory::Callback arp_output_callback = [](mpt::MockProcess* process) { + if (process->program().contains("arp") && process->arguments().contains("-an")) + { + EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(mock_arp_output_stream)); + } + }; + + mock_process_factory->register_callback(arp_output_callback); + } + +private: + const std::unique_ptr mock_process_factory{mpt::MockProcessFactory::Inject()}; +}; + +struct GetNeighbourIPValidInputsTests : public GetNeighbourIpFixture, + public WithParamInterface> +{ +}; + +TEST_P(GetNeighbourIPValidInputsTests, ValidInputCases) +{ + const auto& [existed_mac, expected_mapped_ip] = GetParam(); + EXPECT_EQ(mp::backend::get_neighbour_ip(existed_mac).value().as_string(), expected_mapped_ip); +} + +INSTANTIATE_TEST_SUITE_P(GetNeighbourIPTestsInstantiation, + GetNeighbourIPValidInputsTests, + Values(std::make_pair("52:54:00:2a:12:b6", "192.168.64.2"), + std::make_pair("52:54:00:85:72:55", "192.168.64.3"), + std::make_pair("52:54:00:e1:cd:ab", "192.168.64.4"), + std::make_pair("01:00:5e:00:00:fb", "224.0.0.251"))); + +struct GetNeighbourIPInValidInputsTests : public GetNeighbourIpFixture, public WithParamInterface +{ +}; + +TEST_P(GetNeighbourIPInValidInputsTests, InValidInputCases) +{ + const auto& non_exist_mac = GetParam(); + EXPECT_FALSE(mp::backend::get_neighbour_ip(non_exist_mac).has_value()); +} + +INSTANTIATE_TEST_SUITE_P(GetNeighbourIPTestsInstantiation, + GetNeighbourIPInValidInputsTests, + Values("11:11:11:11:11:11", "ee:ee:ee:ee:ee:ee")); diff --git a/tests/macos/test_platform_osx.cpp b/tests/macos/test_platform_osx.cpp new file mode 100644 index 0000000000..1be3123160 --- /dev/null +++ b/tests/macos/test_platform_osx.cpp @@ -0,0 +1,383 @@ + +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "tests/common.h" +#include "tests/file_operations.h" +#include "tests/mock_environment_helpers.h" +#include "tests/mock_file_ops.h" +#include "tests/mock_platform.h" +#include "tests/mock_process_factory.h" +#include "tests/mock_standard_paths.h" +#include "tests/mock_utils.h" +#include "tests/temp_dir.h" + +#include +#include +#include +#include + +namespace mp = multipass; +namespace mpt = multipass::test; +namespace mpu = multipass::utils; +using namespace testing; + +namespace +{ + +std::unordered_map ifconfig_output{ + {"lo0", + QByteArrayLiteral("lo0: flags=8049 mtu 16384\n" + "\toptions=1203\n" + "\tinet 127.0.0.1 netmask 0xff000000 \n" + "\tinet6 ::1 prefixlen 128 \n" + "\tinet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 \n" + "\tnd6 options=201\n")}, + {"gif0", QByteArrayLiteral("gif0: flags=8010 mtu 1280\n")}, + {"stf0", QByteArrayLiteral("stf0: flags=0<> mtu 1280\n")}, + {"en0", + QByteArrayLiteral("en0: flags=8863 mtu 1500\n" + "\toptions=50b\n" + "\tether 98:10:e8:f3:14:97 \n" + "\tinet 10.2.0.42 netmask 0xffffff00 broadcast 10.2.0.255\n" + "\tmedia: autoselect (1000baseT )\n" + "\tstatus: active\n")}, + {"en1", + QByteArrayLiteral("en1: flags=8823 mtu 1500\n" + "\toptions=400\n" + "\tether dc:a4:ca:f3:67:03 \n" + "\tmedia: autoselect ()\n" + "\tstatus: inactive\n")}, + {"en2", + QByteArrayLiteral("en2: flags=8963 mtu 1500\n" + "\toptions=460\n" + "\tether 82:15:07:f3:c5:40 \n" + "\tmedia: autoselect \n" + "\tstatus: inactive\n")}, + {"en3", + QByteArrayLiteral("en3: flags=8963 mtu 1500\n" + "\toptions=460\n" + "\tether 82:15:07:f3:c5:41 \n" + "\tmedia: autoselect \n" + "\tstatus: inactive\n")}, + {"en11", + QByteArrayLiteral("en11: flags=8963 mtu 1500\n" + "\toptions=460\n" + "\tether 82:f1:07:f3:c5:41 \n" + "\tmedia: autoselect \n" + "\tstatus: inactive\n")}, + {"en12", + QByteArrayLiteral("en12: flags=8963 mtu 1500\n" + "\toptions=460\n" + "\tether 82:f1:07:f3:c1:42 \n" + "\tmedia: autoselect \n" + "\tstatus: inactive\n")}, + {"bridge0", + QByteArrayLiteral("bridge0: flags=8863 mtu 1500\n" + "\toptions=63\n" + "\tether 82:15:07:f3:c5:40 \n" + "\tConfiguration:\n" + "\t id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0\n" + "\t maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200\n" + "\t root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0\n" + "\t ipfilter disabled flags 0x0\n" + "\tmember: en2 flags=3\n" + "\t ifmaxaddr 0 port 6 priority 0 path cost 0\n" + "\tmember: en3 flags=3\n" + "\t ifmaxaddr 0 port 7 priority 0 path cost 0\n" + "\tmedia: \n" + "\tstatus: inactive\n")}, + {"bridge2", + QByteArrayLiteral("bridge2: flags=8863 mtu 1500\n" + "\toptions=63\n" + "\tether a6:83:e7:56:07:02\n" + "\tConfiguration:\n" + "\t id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0\n" + "\t maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200\n" + "\t root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0\n" + "\t ipfilter disabled flags 0x0\n" + "\tAddress cache:\n" + "\tnd6 options=201\n" + "\tmedia: \n" + "\tstatus: inactive\n")}, + {"p2p0", + QByteArrayLiteral("p2p0: flags=8802 mtu 2304\n" + "\toptions=400\n" + "\tether 0e:a4:ca:f3:67:03 \n" + "\tmedia: autoselect\n" + "\tstatus: inactive\n")}, + {"awdl0", + QByteArrayLiteral("awdl0: flags=8903 mtu 1484\n" + "\toptions=400\n" + "\tether 86:fd:f6:fe:81:c1 \n" + "\tnd6 options=201\n" + "\tmedia: autoselect\n" + "\tstatus: inactive\n")}, + {"llw0", + QByteArrayLiteral("llw0: flags=8822 mtu 1500\n" + "\toptions=400\n" + "\tether 86:fd:f6:fe:81:c1 \n")}, + {"utun0", + QByteArrayLiteral("utun0: flags=8051 mtu 1380\n" + "\tinet6 fe80::a0ac:cff1:2263:c3d2%utun0 prefixlen 64 scopeid 0xc \n" + "\tnd6 options=201\n")}, + {"utun1", + QByteArrayLiteral("utun1: flags=8051 mtu 2000\n" + "\tinet6 fe80::e899:920a:c955:b124%utun1 prefixlen 64 scopeid 0xd \n" + "\tnd6 options=201\n")}, + {"utun2", + QByteArrayLiteral("utun2: flags=8051 mtu 1500\n" + "\tinet 10.8.0.6 --> 10.8.0.5 netmask 0xffffffff\n")}, + {"utun3", + QByteArrayLiteral("utun3: flags=8051 mtu 1380\n" + "\tinet6 fe80::4ba1:886c:9e17:fd30%utun3 prefixlen 64 scopeid 0xf \n" + "\tnd6 options=201\n")}, + {"utun4", + QByteArrayLiteral("utun4: flags=8051 mtu 2000\n" + "\tinet6 fe80::15f1:255f:bb39:92a9%utun4 prefixlen 64 scopeid 0x10 \n" + "\tnd6 options=201\n")}}; + +QByteArray networksetup_output = + QByteArrayLiteral("\nHardware Port: Ethernet\nDevice: en0\nEthernet Address: 98:10:e8:f3:14:97\n" + "\nHardware Port: Wi-Fi\nDevice: en1\nEthernet Address: dc:a4:ca:f3:67:03\n" + "\nHardware Port: Bluetooth PAN\nDevice: en4\nEthernet Address: dc:a4:ca:f3:67:04\n" + "\nHardware Port: Thunderbolt 1\nDevice: en2\nEthernet Address: 82:15:07:f3:c5:40\n" + "\nHardware Port: Thunderbolt 2\nDevice: en3\nEthernet Address: 82:15:07:f3:c5:41\n" + "\nHardware Port: Thunderbolt Bridge\nDevice: bridge0\nEthernet Address: 82:15:07:f3:c5:40\n" + "\nHardware Port: USB 10/100/1000 LAN\nDevice: en11\nEthernet Address: 9c:eb:e8:98:0e:62\n" + "\nHardware Port: iPhone USB\nDevice: en12\nEthernet Address: 92:8c:43:1e:b2:1c\n" + "\nHardware Port: TestBridge2\nDevice: bridge2\nEthernet Address: a6:83:e7:56:07:02\n" + "\nVLAN Configurations\n===================\n" + "\nVLAN User Defined Name: TestVLAN\nParent Device: en0\nDevice (\"Hardware\" Port): vlan0" + "\nTag: 1\n"); + +std::unordered_map expect_interfaces{ + {"en0", {"en0", "ethernet", "Ethernet"}}, + {"en1", {"en1", "wifi", "Wi-Fi"}}, + {"en2", {"en2", "thunderbolt", "Thunderbolt 1"}}, + {"en3", {"en3", "thunderbolt", "Thunderbolt 2"}}, + {"en11", {"en11", "usb", "USB 10/100/1000 LAN"}}, + {"en12", {"en12", "usb", "iPhone USB"}}, + {"bridge0", {"bridge0", "bridge", "Network bridge with en2, en3"}}, + {"bridge2", {"bridge2", "bridge", "Empty network bridge"}}}; + +void simulate_ifconfig(const mpt::MockProcess* process, const mp::ProcessState& exit_status) +{ + ASSERT_EQ(process->program(), "ifconfig"); + + QByteArray output; + + const auto& args = process->arguments(); + ASSERT_EQ(args.size(), 0); + + for (const auto& [key, val] : ifconfig_output) + output += val; + + EXPECT_CALL(*process, execute).WillOnce(Return(exit_status)); + if (exit_status.completed_successfully()) + EXPECT_CALL(*process, read_all_standard_output).WillOnce(Return(output)); +} + +void simulate_networksetup(const mpt::MockProcess* process, const mp::ProcessState& exit_status) +{ + ASSERT_EQ(process->program(), "networksetup"); + + const auto& args = process->arguments(); + ASSERT_EQ(args.size(), 1); + EXPECT_EQ(args.constFirst(), "-listallhardwareports"); + + EXPECT_CALL(*process, execute).WillOnce(Return(exit_status)); + + if (exit_status.completed_successfully()) + { + QByteArray success_output = networksetup_output; + EXPECT_CALL(*process, read_all_standard_output).WillOnce(Return(success_output)); + } + else + { + QByteArray fail_output("Fail"); + + if (exit_status.exit_code) + EXPECT_CALL(*process, read_all_standard_error).WillOnce(Return(fail_output)); + else + ON_CALL(*process, read_all_standard_error).WillByDefault(Return(fail_output)); + } +} + +void simulate_environment(const mpt::MockProcess* process, + const mp::ProcessState& ifconfig_exit, + const mp::ProcessState& networksetup_exit) +{ + auto program = process->program(); + + if (program == "ifconfig") + simulate_ifconfig(process, ifconfig_exit); + else if (program == "networksetup") + simulate_networksetup(process, networksetup_exit); + else + throw std::runtime_error(fmt::format("Program {} not mocked.", program)); +} + +TEST(PlatformOSX, test_no_extra_client_settings) +{ + EXPECT_THAT(MP_PLATFORM.extra_client_settings(), IsEmpty()); +} + +TEST(PlatformOSX, test_no_extra_daemon_settings) +{ + EXPECT_THAT(MP_PLATFORM.extra_daemon_settings(), IsEmpty()); +} + +TEST(PlatformOSX, test_interpretation_of_winterm_setting_not_supported) +{ + for (const auto x : {"no", "matter", "what"}) + EXPECT_THROW(mp::platform::interpret_setting(mp::winterm_key, x), mp::InvalidSettingException); +} + +TEST(PlatformOSX, test_interpretation_of_unknown_settings_not_supported) +{ + for (const auto k : {"unimaginable", "katxama", "katxatxa"}) + for (const auto v : {"no", "matter", "what"}) + EXPECT_THROW(mp::platform::interpret_setting(k, v), mp::InvalidSettingException); +} + +TEST(PlatformOSX, test_empty_sync_winterm_profiles) +{ + EXPECT_NO_THROW(mp::platform::sync_winterm_profiles()); +} + +TEST(PlatformOSX, test_default_driver) +{ + EXPECT_THAT(MP_PLATFORM.default_driver(), AnyOf("qemu", "virtualbox")); +} + +TEST(PlatformOSX, test_default_privileged_mounts) +{ + EXPECT_EQ(MP_PLATFORM.default_privileged_mounts(), "true"); +} + +TEST(PlatformOSX, test_network_interfaces) +{ + std::unique_ptr mock_factory_scope = mpt::MockProcessFactory::Inject(); + const mp::ProcessState success{0, std::nullopt}; + mock_factory_scope->register_callback( + [&](mpt::MockProcess* process) { simulate_environment(process, success, success); }); + + auto got_interfaces = MP_PLATFORM.get_network_interfaces_info(); + + ASSERT_EQ(got_interfaces.size(), expect_interfaces.size()); + for (const auto& [got_name, got_iface] : got_interfaces) + EXPECT_NO_THROW({ + ASSERT_EQ(got_name, got_iface.id); + + const auto& expected_iface = expect_interfaces.at(got_name); + EXPECT_EQ(got_iface.id, expected_iface.id); + EXPECT_EQ(got_iface.type, expected_iface.type); + EXPECT_EQ(got_iface.description, expected_iface.description); + }); +} + +TEST(PlatformOSX, create_alias_script_works) +{ + const mpt::TempDir tmp_dir; + + EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::AppLocalDataLocation)) + .WillOnce(Return(tmp_dir.path())); + + EXPECT_NO_THROW(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command"})); + + QFile checked_script(tmp_dir.path() + "/bin/alias_name"); + checked_script.open(QFile::ReadOnly); + + EXPECT_EQ(checked_script.readLine().toStdString(), "#!/bin/sh\n"); + EXPECT_EQ(checked_script.readLine().toStdString(), "\n"); + EXPECT_THAT(checked_script.readLine().toStdString(), HasSubstr("alias_name -- \"${@}\"\n")); + EXPECT_TRUE(checked_script.atEnd()); + + auto script_permissions = checked_script.permissions(); + EXPECT_TRUE(script_permissions & QFileDevice::ExeOwner); + EXPECT_TRUE(script_permissions & QFileDevice::ExeGroup); + EXPECT_TRUE(script_permissions & QFileDevice::ExeOther); +} + +TEST(PlatformOSX, create_alias_script_overwrites) +{ + auto [mock_utils, guard1] = mpt::MockUtils::inject(); + auto [mock_file_ops, guard2] = mpt::MockFileOps::inject(); + auto [mock_platform, guard3] = mpt::MockPlatform::inject(); + + EXPECT_CALL(*mock_utils, make_file_with_content(_, _, true)).Times(1); + EXPECT_CALL(*mock_file_ops, get_permissions(_)) + .WillOnce(Return(std::filesystem::perms::owner_read | std::filesystem::perms::owner_write)); + EXPECT_CALL(*mock_platform, set_permissions(_, _, _)).WillOnce(Return(true)); + + EXPECT_NO_THROW( + mock_platform->Platform::create_alias_script("alias_name", mp::AliasDefinition{"instance", "other_command"})); +} + +TEST(PlatformOSX, create_alias_script_throws_if_cannot_create_path) +{ + auto [mock_file_ops, guard] = mpt::MockFileOps::inject(); + + EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(false)); + + MP_EXPECT_THROW_THAT(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command"}), + std::runtime_error, + mpt::match_what(HasSubstr("failed to create dir '"))); +} + +TEST(PlatformOSX, create_alias_script_throws_if_cannot_write_script) +{ + auto [mock_file_ops, guard] = mpt::MockFileOps::inject(); + + EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(true)); + EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true)); + EXPECT_CALL(*mock_file_ops, write(A(), _, _)).WillOnce(Return(747)); + + MP_EXPECT_THROW_THAT(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command"}), + std::runtime_error, + mpt::match_what(HasSubstr("failed to write to file '"))); +} + +TEST(PlatformOSX, remove_alias_script_works) +{ + const mpt::TempDir tmp_dir; + QFile script_file(tmp_dir.path() + "/bin/alias_name"); + + EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::AppLocalDataLocation)) + .WillOnce(Return(tmp_dir.path())); + + MP_UTILS.make_file_with_content(script_file.fileName().toStdString(), "script content\n"); + + EXPECT_NO_THROW(MP_PLATFORM.remove_alias_script("alias_name")); + + EXPECT_FALSE(script_file.exists()); +} + +TEST(PlatformOSX, remove_alias_script_throws_if_cannot_remove_script) +{ + const mpt::TempDir tmp_dir; + QFile script_file(tmp_dir.path() + "/bin/alias_name"); + + EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::AppLocalDataLocation)) + .WillOnce(Return(tmp_dir.path())); + + MP_EXPECT_THROW_THAT(MP_PLATFORM.remove_alias_script("alias_name"), + std::runtime_error, + mpt::match_what(StrEq("No such file or directory"))); +} +} // namespace diff --git a/tests/mock_aes.h b/tests/mock_aes.h new file mode 100644 index 0000000000..ece10424e3 --- /dev/null +++ b/tests/mock_aes.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_MOCK_AES_H +#define MULTIPASS_MOCK_AES_H + +#include "common.h" +#include "mock_singleton_helpers.h" + +#include + +namespace multipass::test +{ +class MockAES : public AES +{ +public: + MockAES(const Singleton::PrivatePass& pass) noexcept : AES{pass} + { + ON_CALL(*this, aes_256_key_size).WillByDefault(testing::Return(AES::aes_256_key_size())); + ON_CALL(*this, aes_256_block_size).WillByDefault(testing::Return(AES::aes_256_block_size())); + } + + MOCK_METHOD(int, aes_256_key_size, (), (const, override)); + MOCK_METHOD(int, aes_256_block_size, (), (const, override)); + MOCK_METHOD(std::string, + decrypt, + (const std::vector&, const std::vector&, const std::string&), + (const, override)); + MOCK_METHOD(std::string, + encrypt, + (const std::vector&, const std::vector&, const std::string&), + (const, override)); + + MP_MOCK_SINGLETON_BOILERPLATE(MockAES, AES); +}; +} // namespace multipass::test + +#endif // MULTIPASS_MOCK_AES_H diff --git a/tests/mock_platform.h b/tests/mock_platform.h index 5d56ff5e87..eee2438a2b 100644 --- a/tests/mock_platform.h +++ b/tests/mock_platform.h @@ -36,10 +36,7 @@ class MockPlatform : public platform::Platform }; MOCK_METHOD((std::map < std::string, NetworkInterfaceInfo) >, get_network_interfaces_info, (), (const, override)); - MOCK_METHOD(QString, get_blueprints_url_override, (), (const, override)); - MOCK_METHOD(bool, is_remote_supported, (const std::string&), (const, override)); MOCK_METHOD(bool, is_backend_supported, (const QString&), (const, override)); - MOCK_METHOD(bool, is_alias_supported, (const std::string&, const std::string&), (const, override)); MOCK_METHOD(int, chown, (const char*, unsigned int, unsigned int), (const, override)); MOCK_METHOD(bool, set_permissions, (const std::filesystem::path&, std::filesystem::perms, bool), (const, override)); MOCK_METHOD(bool, take_ownership, (const std::filesystem::path&), (const, override)); @@ -56,7 +53,6 @@ class MockPlatform : public platform::Platform MOCK_METHOD(QString, daemon_config_home, (), (const, override)); MOCK_METHOD(QString, default_driver, (), (const, override)); MOCK_METHOD(QString, default_privileged_mounts, (), (const, override)); - MOCK_METHOD(bool, is_image_url_supported, (), (const, override)); MOCK_METHOD(QString, get_username, (), (const, override)); MOCK_METHOD(std::string, bridge_nomenclature, (), (const, override)); MOCK_METHOD(std::filesystem::path, get_root_cert_path, (), (const, override)); diff --git a/tests/mock_vm_image_vault.h b/tests/mock_vm_image_vault.h index 9f17883fcf..8966cde0ba 100644 --- a/tests/mock_vm_image_vault.h +++ b/tests/mock_vm_image_vault.h @@ -35,10 +35,9 @@ class MockVMImageVault : public VMImageVault public: MockVMImageVault() { - ON_CALL(*this, fetch_image(_, _, _, _, _, _, _)) - .WillByDefault([this](auto, auto, const PrepareAction& prepare, auto, auto, auto, auto) { - return VMImage{dummy_image.name(), {}, {}, {}, {}, {}}; - }); + ON_CALL(*this, fetch_image).WillByDefault([this](auto&&...) { + return VMImage{dummy_image.name(), {}, {}, {}, {}, {}}; + }); ON_CALL(*this, has_record_for(_)).WillByDefault(Return(true)); ON_CALL(*this, minimum_image_size_for(_)).WillByDefault(Return(MemorySize{"1048576"})); }; @@ -49,7 +48,6 @@ class MockVMImageVault : public VMImageVault const Query&, const PrepareAction&, const ProgressMonitor&, - const bool, const std::optional&, const mp::Path&), (override)); diff --git a/tests/path.cpp b/tests/path.cpp index a9eee7cf2d..31a946daae 100644 --- a/tests/path.cpp +++ b/tests/path.cpp @@ -23,6 +23,8 @@ #include #include +#include + namespace mpt = multipass::test; QString mpt::test_data_path() diff --git a/tests/qemu/macos/CMakeLists.txt b/tests/qemu/macos/CMakeLists.txt new file mode 100644 index 0000000000..f265268646 --- /dev/null +++ b/tests/qemu/macos/CMakeLists.txt @@ -0,0 +1,21 @@ +# Copyright (C) Canonical, Ltd. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 3 as +# published by the Free Software Foundation. +# +# 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 . +# + +target_sources(multipass_tests + PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/test_qemu_platform_detail.cpp +) + +target_include_directories(multipass_tests PRIVATE ${CMAKE_SOURCE_DIR}/src/platform/backends/qemu) diff --git a/tests/qemu/macos/test_qemu_platform_detail.cpp b/tests/qemu/macos/test_qemu_platform_detail.cpp new file mode 100644 index 0000000000..5934c84058 --- /dev/null +++ b/tests/qemu/macos/test_qemu_platform_detail.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "tests/common.h" + +#include + +#include +#include + +namespace mp = multipass; + +using namespace testing; + +namespace +{ +struct TestQemuPlatformDetail : public Test +{ + void check_expected_args(const std::vector& expected_args, const QStringList& platform_args) + { + if (expected_args.empty()) + { + EXPECT_TRUE(platform_args.isEmpty()); + } + else + { + for (const auto& args : expected_args) + { + auto it = std::search(platform_args.cbegin(), platform_args.cend(), args.cbegin(), args.cend()); + + EXPECT_NE(it, platform_args.cend()); + } + } + }; + + const std::string hw_addr{"52:54:00:6f:29:7e"}; + const QString host_arch{HOST_ARCH}; + mp::QemuPlatformDetail qemu_platform_detail; +}; +} // namespace + +TEST_F(TestQemuPlatformDetail, vm_platform_args_returns_expected_arguments) +{ + std::vector expected_args{ + {"-accel", "hvf"}, + {"-nic", QString("vmnet-shared,model=virtio-net-pci,mac=%1").arg(QString::fromStdString(hw_addr))}, + {"-cpu", "host"}}; + mp::VirtualMachineDescription vm_desc; + vm_desc.vm_name = "foo"; + vm_desc.default_mac_address = hw_addr; + + if (host_arch == "aarch64") + { + expected_args.push_back(QStringList({"-machine", "virt,gic-version=3"})); + } + + check_expected_args(expected_args, qemu_platform_detail.vm_platform_args(vm_desc)); +} + +TEST_F(TestQemuPlatformDetail, vmstate_platform_args_returns_expected_arguments) +{ + std::vector expected_args; + + if (host_arch == "aarch64") + { + expected_args.push_back(QStringList({"-machine", "virt,gic-version=3"})); + } + + check_expected_args(expected_args, qemu_platform_detail.vmstate_platform_args()); +} + +TEST_F(TestQemuPlatformDetail, get_directory_name_returns_expected_string) +{ + EXPECT_EQ(qemu_platform_detail.get_directory_name(), "qemu"); +} diff --git a/tests/stub_ssh_key_provider.h b/tests/stub_ssh_key_provider.h index df37e00c86..ddc6698a2c 100644 --- a/tests/stub_ssh_key_provider.h +++ b/tests/stub_ssh_key_provider.h @@ -29,6 +29,9 @@ namespace test class StubSSHKeyProvider : public SSHKeyProvider { public: + // A default constructor is needed by Clang++-13, see https://stackoverflow.com/questions/77283333 + StubSSHKeyProvider(){}; + std::string private_key_as_base64() const override { return {}; diff --git a/tests/stub_vm_image_vault.h b/tests/stub_vm_image_vault.h index 2e363decc6..50169baf5b 100644 --- a/tests/stub_vm_image_vault.h +++ b/tests/stub_vm_image_vault.h @@ -32,7 +32,6 @@ struct StubVMImageVault final : public multipass::VMImageVault const multipass::Query&, const PrepareAction& prepare, const multipass::ProgressMonitor&, - const bool, const std::optional&, const multipass::Path&) override { diff --git a/tests/test_alias_dict.cpp b/tests/test_alias_dict.cpp index 8123f893e4..ac73fff4c1 100644 --- a/tests/test_alias_dict.cpp +++ b/tests/test_alias_dict.cpp @@ -622,7 +622,7 @@ TEST_P(DaemonAliasTestsuite, purge_removes_purged_instance_aliases_and_scripts) auto mock_image_vault = std::make_unique>(); EXPECT_CALL(*mock_image_vault, remove(_)).WillRepeatedly(Return()); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillRepeatedly(Return(mp::VMImage{})); + EXPECT_CALL(*mock_image_vault, fetch_image).WillRepeatedly(Return(mp::VMImage{})); EXPECT_CALL(*mock_image_vault, prune_expired_images()).WillRepeatedly(Return()); EXPECT_CALL(*mock_image_vault, has_record_for(_)).WillRepeatedly(Return(true)); diff --git a/tests/test_blueprint_provider.cpp b/tests/test_blueprint_provider.cpp index 1b152e8b7e..17ad305b88 100644 --- a/tests/test_blueprint_provider.cpp +++ b/tests/test_blueprint_provider.cpp @@ -807,8 +807,6 @@ TEST_P(VMBlueprintFileLaunchFromFile, loadsFile) file.open(QFile::WriteOnly); }); - ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); - auto blueprint_path = QString(mpt::test_data_path() + "/blueprints/" + QString::fromStdString(file)).toStdString(); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &mock_url_downloader, cache_dir.path(), @@ -834,8 +832,6 @@ INSTANTIATE_TEST_SUITE_P(VMBlueprintFileLaunch, VMBlueprintFileLaunchFromFile, TEST_F(VMBlueprintFileLaunch, mergesBlueprintVendorData) { - ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); - mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), @@ -870,8 +866,6 @@ TEST_F(VMBlueprintFileLaunch, mergesBlueprintVendorData) TEST_F(VMBlueprintFileLaunch, failsMergeVmBlueprintVendorDataDifferentTypes) { - ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); - mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), @@ -894,8 +888,6 @@ TEST_F(VMBlueprintFileLaunch, failsMergeVmBlueprintVendorDataDifferentTypes) TEST_F(VMBlueprintFileLaunch, failsMergeVmBlueprintVendorDataScalarValues) { - ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); - mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), @@ -918,8 +910,6 @@ TEST_F(VMBlueprintFileLaunch, failsMergeVmBlueprintVendorDataScalarValues) TEST_F(VMBlueprintFileLaunch, failsWithNonexistentFile) { - ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); - mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; @@ -933,8 +923,6 @@ TEST_F(VMBlueprintFileLaunch, failsWithNonexistentFile) TEST_F(VMBlueprintFileLaunch, fileLoadfailsWithInvalidHostName) { - ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); - auto blueprint_path = QString(mpt::test_data_path() + "/blueprints/v1/42-invalid-hostname-blueprint.yaml").toStdString(); @@ -951,22 +939,6 @@ TEST_F(VMBlueprintFileLaunch, fileLoadfailsWithInvalidHostName) mpt::match_what(StrEq("Invalid Blueprint name \'42-invalid-hostname-blueprint\': must be a valid host name"))); } -TEST_F(VMBlueprintFileLaunch, failsIfFileLaunchIsUnsupported) -{ - ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(false)); - - mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), - default_ttl}; - - mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; - - mp::ClientLaunchData dummy_data; - - MP_EXPECT_THROW_THAT(blueprint_provider.blueprint_from_file("/blah.yaml", "blah", vm_desc, dummy_data), - std::runtime_error, - mpt::match_what(StrEq("Launching a Blueprint from a file is not supported"))); -} - struct NameFromBlueprintTestSuite : public VMBlueprintProvider, public WithParamInterface> { @@ -991,8 +963,6 @@ TEST_F(VMBlueprintFileLaunch, fileLoadfailsWithNoUrl) { auto blueprint_path = QString(mpt::test_data_path() + "/blueprints/v2/test-blueprint1.yaml").toStdString(); - ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); - mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "microvac"}; diff --git a/tests/test_cli_client.cpp b/tests/test_cli_client.cpp index 303d83babe..5dc699f3e1 100644 --- a/tests/test_cli_client.cpp +++ b/tests/test_cli_client.cpp @@ -3670,7 +3670,7 @@ TEST_P(ClientAliasNameSuite, creates_correct_default_alias_name) EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function()); std::vector arguments{"alias"}; - arguments.push_back(fmt::format("primary:{}{}", path, command)); + arguments.push_back("primary:" + path + command); arguments.push_back("--no-map-working-directory"); EXPECT_EQ(send_command(arguments), mp::ReturnCode::Ok); diff --git a/tests/test_cli_prompters.cpp b/tests/test_cli_prompters.cpp index 411e3e3a5f..cd4fb3d11a 100644 --- a/tests/test_cli_prompters.cpp +++ b/tests/test_cli_prompters.cpp @@ -180,8 +180,8 @@ TEST_F(CLIPrompters, failsIfNoNetworks) EXPECT_CALL(mock_terminal, cin_is_live()).WillRepeatedly(Return(false)); EXPECT_CALL(mock_terminal, cout_is_live()).WillRepeatedly(Return(false)); - - ASSERT_DEBUG_DEATH(prompter.bridge_prompt(nets), "[Aa]ssert"); + // https://google.github.io/googletest/advanced.html#regular-expression-syntax + ASSERT_DEBUG_DEATH(prompter.bridge_prompt(nets), "\\wssert"); } TEST_P(BridgePrompterTests, correctlyReturns) diff --git a/tests/test_custom_image_host.cpp b/tests/test_custom_image_host.cpp index 349e6f3bc2..dba3d6a17d 100644 --- a/tests/test_custom_image_host.cpp +++ b/tests/test_custom_image_host.cpp @@ -25,8 +25,6 @@ #include #include -#include -#include #include #include @@ -56,9 +54,6 @@ struct CustomImageHost : public Test { CustomImageHost() { - EXPECT_CALL(*mock_platform, is_remote_supported(_)).WillRepeatedly(Return(true)); - EXPECT_CALL(*mock_platform, is_alias_supported(_, _)).WillRepeatedly(Return(true)); - ON_CALL(mock_url_downloader, last_modified(_)).WillByDefault(Return(QDateTime::currentDateTime())); ON_CALL(mock_url_downloader, download(_)).WillByDefault(Return(sha256_sums)); ON_CALL(mock_url_downloader, download(_, _)).WillByDefault(Return(sha256_sums)); @@ -129,36 +124,6 @@ TEST_F(CustomImageHost, iterates_over_all_entries) "192c40c8f3361f4f9da2757d87e409ac5abb2df393145983d3696e21f486b552")); } -TEST_F(CustomImageHost, unsupported_alias_iterates_over_expected_entries) -{ - std::unordered_set ids; - EXPECT_CALL(*mock_platform, is_alias_supported("core18", _)).WillRepeatedly(Return(false)); - - auto action = [&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); }; - mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; - host.update_manifests(false); - host.for_each_entry_do(action); - - const size_t expected_entries{4}; - EXPECT_EQ(ids.size(), expected_entries); -} - -TEST_F(CustomImageHost, unsupported_remote_iterates_over_expected_entries) -{ - const std::string unsupported_remote{""}; - EXPECT_CALL(*mock_platform, is_remote_supported(unsupported_remote)).WillRepeatedly(Return(false)); - - mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; - host.update_manifests(false); - - std::unordered_set ids; - auto action = [&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); }; - host.for_each_entry_do(action); - - const size_t expected_entries{0}; - EXPECT_EQ(ids.size(), expected_entries); -} - TEST_F(CustomImageHost, all_images_for_no_remote_returns_appropriate_matches) { mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; @@ -169,20 +134,6 @@ TEST_F(CustomImageHost, all_images_for_no_remote_returns_appropriate_matches) EXPECT_THAT(images.size(), Eq(expected_matches)); } -TEST_F(CustomImageHost, all_images_for_no_remote_unsupported_alias_returns_appropriate_matches) -{ - mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; - host.update_manifests(false); - - const std::string unsupported_alias{"core18"}; - EXPECT_CALL(*mock_platform, is_alias_supported(unsupported_alias, _)).WillOnce(Return(false)); - - auto images = host.all_images_for("", false); - - const size_t expected_matches{4}; - EXPECT_EQ(images.size(), expected_matches); -} - TEST_F(CustomImageHost, all_info_for_no_remote_returns_one_alias_match) { mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; @@ -193,19 +144,6 @@ TEST_F(CustomImageHost, all_info_for_no_remote_returns_one_alias_match) EXPECT_THAT(images_info.size(), Eq(expected_matches)); } -TEST_F(CustomImageHost, all_info_for_unsupported_alias_throws) -{ - mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; - host.update_manifests(false); - - const std::string unsupported_alias{"core20"}; - EXPECT_CALL(*mock_platform, is_alias_supported(unsupported_alias, _)).WillOnce(Return(false)); - - MP_EXPECT_THROW_THAT( - host.all_info_for(make_query(unsupported_alias, "")), mp::UnsupportedAliasException, - mpt::match_what(HasSubstr(fmt::format("\'{}\' is not a supported alias.", unsupported_alias)))); -} - TEST_F(CustomImageHost, supported_remotes_returns_expected_values) { mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; @@ -294,19 +232,6 @@ TEST_F(CustomImageHost, handles_and_recovers_from_independent_server_failures) } } -TEST_F(CustomImageHost, info_for_unsupported_remote_throws) -{ - mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; - host.update_manifests(false); - - const std::string unsupported_remote{"foo"}; - EXPECT_CALL(*mock_platform, is_remote_supported(unsupported_remote)).WillRepeatedly(Return(false)); - - MP_EXPECT_THROW_THAT(host.info_for(make_query("xenial", unsupported_remote)), mp::UnsupportedRemoteException, - mpt::match_what(HasSubstr(fmt::format( - "Remote \'{}\' is not a supported remote for this platform.", unsupported_remote)))); -} - TEST_F(CustomImageHost, info_for_full_hash_returns_empty_image_info) { mp::CustomVMImageHost host{"x86_64", &mock_url_downloader}; diff --git a/tests/test_daemon.cpp b/tests/test_daemon.cpp index 40e1457ffc..8ceaf74de1 100644 --- a/tests/test_daemon.cpp +++ b/tests/test_daemon.cpp @@ -115,7 +115,7 @@ struct Daemon : public mpt::DaemonTestFixture return mock_utils.Utils::filesystem_bytes_available(data_directory); }); ON_CALL(mock_utils, contents_of(_)).WillByDefault(Return(mpt::root_cert)); - EXPECT_CALL(mock_platform, get_blueprints_url_override()).WillRepeatedly([] { return QString{}; }); + EXPECT_CALL(mock_platform, multipass_storage_location()).Times(AnyNumber()).WillRepeatedly(Return(QString())); EXPECT_CALL(mock_platform, create_alias_script(_, _)).WillRepeatedly(Return()); EXPECT_CALL(mock_platform, remove_alias_script(_)).WillRepeatedly(Return()); @@ -344,9 +344,7 @@ TEST_F(Daemon, blueprintsURLOverrideIsCorrect) auto url_downloader = std::make_unique(); const QString test_blueprints_zip{mpt::test_data_path() + "test-blueprints.zip"}; - EXPECT_CALL(mock_platform, get_blueprints_url_override()).WillOnce([&test_blueprints_zip] { - return QUrl::fromLocalFile(test_blueprints_zip).toEncoded(); - }); + mpt::SetEnvScope env_scope{"MULTIPASS_BLUEPRINTS_URL", QUrl::fromLocalFile(test_blueprints_zip).toEncoded()}; config_builder.cache_directory = cache_dir.path(); config_builder.url_downloader = std::move(url_downloader); @@ -824,7 +822,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundPassesExpectedAliases) EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); auto alias = std::make_optional(std::make_pair(alias_name, mp::AliasDefinition{name, alias_command, alias_wdir})); @@ -863,7 +861,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundMountsWorkspace) EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)) .WillOnce( @@ -897,7 +895,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundMountsWorkspaceConfined) EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)) .WillOnce( @@ -935,7 +933,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundMountsWorkspaceInExisting EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)) .WillOnce( @@ -978,7 +976,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundDoesNotMountUnwrittableWo EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)) .WillOnce( @@ -1025,7 +1023,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundButCannotMount) EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)) .WillOnce( @@ -1076,7 +1074,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundPassesExpectedAliasesWith EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, command_line_name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); auto alias = std::make_optional(std::make_pair(alias_name, mp::AliasDefinition{name, alias_command, alias_wdir})); @@ -1123,7 +1121,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundDoesNotOverwriteAliases) EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); auto alias = std::make_optional(std::make_pair(alias_name, mp::AliasDefinition{name, alias_command, alias_wdir})); @@ -1172,7 +1170,7 @@ TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundDoesNotOverwriteAliasesIf EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); auto alias = std::make_optional(std::make_pair(alias_name, mp::AliasDefinition{name, alias_command, alias_wdir})); @@ -1213,7 +1211,7 @@ TEST_P(DaemonCreateLaunchTestSuite, blueprint_found_passes_expected_data) EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)) .WillOnce(mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote)); @@ -1241,7 +1239,7 @@ TEST_P(DaemonCreateLaunchTestSuite, blueprint_not_found_passes_expected_data) EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, empty)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, empty)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, empty)); config_builder.vault = std::move(mock_image_vault); mp::Daemon daemon{config_builder.build()}; @@ -1507,7 +1505,7 @@ TEST_F(DaemonCreateLaunchTestSuite, blueprintFromFileCallsCorrectFunction) EXPECT_CALL(*mock_factory, create_virtual_machine).Times(1); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).Times(1); + EXPECT_CALL(*mock_image_vault, fetch_image).Times(1); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)).Times(0); @@ -1868,9 +1866,9 @@ TEST_F(Daemon, ctor_drops_removed_instances) config_builder.data_directory = temp_dir->path(); auto mock_image_vault = std::make_unique>(); - EXPECT_CALL(*mock_image_vault, fetch_image(_, Field(&mp::Query::name, stayed), _, _, _, _, _)) + EXPECT_CALL(*mock_image_vault, fetch_image(_, Field(&mp::Query::name, stayed), _, _, _, _)) .WillRepeatedly(DoDefault()); // returns an image that can be verified to exist for this instance - EXPECT_CALL(*mock_image_vault, fetch_image(_, Field(&mp::Query::name, gone), _, _, _, _, _)) + EXPECT_CALL(*mock_image_vault, fetch_image(_, Field(&mp::Query::name, gone), _, _, _, _)) .WillOnce(Return(mp::VMImage{"/path/to/nowhere", "", "", "", "", {}})); // an image that can't be verified to // exist for this instance config_builder.vault = std::move(mock_image_vault); diff --git a/tests/test_daemon_launch.cpp b/tests/test_daemon_launch.cpp index 9a0c66a799..e01bff9f80 100644 --- a/tests/test_daemon_launch.cpp +++ b/tests/test_daemon_launch.cpp @@ -80,7 +80,7 @@ TEST_F(TestDaemonLaunch, blueprintFoundMountsWorkspaceWithNameOverride) EXPECT_CALL(*mock_factory, create_virtual_machine) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, command_line_name)); - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote)); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)) .WillOnce( @@ -135,8 +135,7 @@ TEST_F(TestDaemonLaunch, v2BlueprintFoundPropagatesSha) .WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, command_line_name)); // The expectation of this test is set in fetch_image_lambda(). - EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)) - .WillOnce(mpt::fetch_image_lambda(release, remote, true)); + EXPECT_CALL(*mock_image_vault, fetch_image).WillOnce(mpt::fetch_image_lambda(release, remote, true)); EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)) .WillOnce(mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, std::nullopt, diff --git a/tests/test_image_vault.cpp b/tests/test_image_vault.cpp index 7cc693d2dc..75494d4624 100644 --- a/tests/test_image_vault.cpp +++ b/tests/test_image_vault.cpp @@ -185,7 +185,6 @@ TEST_F(ImageVault, downloads_image) default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -200,7 +199,6 @@ TEST_F(ImageVault, returned_image_contains_instance_name) default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -210,13 +208,7 @@ TEST_F(ImageVault, returned_image_contains_instance_name) TEST_F(ImageVault, imageCloneSuccess) { mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}}; - vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + vault.fetch_image(mp::FetchType::ImageOnly, default_query, stub_prepare, stub_monitor, std::nullopt, instance_dir); const std::string dest_name = instance_name + "clone"; EXPECT_NO_THROW(vault.clone(instance_name, dest_name)); @@ -233,13 +225,7 @@ TEST_F(ImageVault, imageCloneFailOnNonExistSrcImage) TEST_F(ImageVault, imageCloneFailOnAlreadyExistDestImage) { mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}}; - vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + vault.fetch_image(mp::FetchType::ImageOnly, default_query, stub_prepare, stub_monitor, std::nullopt, instance_dir); const std::string dest_name = "valley-pied-piper-clone"; const mp::Query second_query{dest_name, "xenial", false, "", mp::Query::Type::Alias}; @@ -248,7 +234,6 @@ TEST_F(ImageVault, imageCloneFailOnAlreadyExistDestImage) second_query, stub_prepare, stub_monitor, - false, std::nullopt, save_dir.filePath(QString::fromStdString(second_query.name))); @@ -265,13 +250,8 @@ TEST_F(ImageVault, calls_prepare) prepare_called = true; return source_image; }; - auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + auto vm_image = + vault.fetch_image(mp::FetchType::ImageOnly, default_query, prepare, stub_monitor, std::nullopt, instance_dir); EXPECT_TRUE(prepare_called); } @@ -284,20 +264,10 @@ TEST_F(ImageVault, records_instanced_images) ++prepare_called_count; return source_image; }; - auto vm_image1 = vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); - auto vm_image2 = vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + auto vm_image1 = + vault.fetch_image(mp::FetchType::ImageOnly, default_query, prepare, stub_monitor, std::nullopt, instance_dir); + auto vm_image2 = + vault.fetch_image(mp::FetchType::ImageOnly, default_query, prepare, stub_monitor, std::nullopt, instance_dir); EXPECT_THAT(url_downloader.downloaded_files.size(), Eq(1)); EXPECT_THAT(prepare_called_count, Eq(1)); @@ -313,13 +283,8 @@ TEST_F(ImageVault, caches_prepared_images) ++prepare_called_count; return source_image; }; - auto vm_image1 = vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + auto vm_image1 = + vault.fetch_image(mp::FetchType::ImageOnly, default_query, prepare, stub_monitor, std::nullopt, instance_dir); auto another_query = default_query; another_query.name = "valley-pied-piper-chat"; @@ -327,7 +292,6 @@ TEST_F(ImageVault, caches_prepared_images) another_query, prepare, stub_monitor, - false, std::nullopt, save_dir.filePath(QString::fromStdString(another_query.name))); @@ -355,7 +319,6 @@ TEST_F(ImageVault, remembers_instance_images) default_query, prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -364,7 +327,6 @@ TEST_F(ImageVault, remembers_instance_images) default_query, prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -390,7 +352,6 @@ TEST_F(ImageVault, remembers_prepared_images) default_query, prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -401,7 +362,6 @@ TEST_F(ImageVault, remembers_prepared_images) another_query, prepare, stub_monitor, - false, std::nullopt, save_dir.filePath(QString::fromStdString(another_query.name))); @@ -424,13 +384,8 @@ TEST_F(ImageVault, uses_image_from_prepare) }; mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}}; - auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + auto vm_image = + vault.fetch_image(mp::FetchType::ImageOnly, default_query, prepare, stub_monitor, std::nullopt, instance_dir); const auto image_data = mp::utils::contents_of(vm_image.image_path); EXPECT_THAT(image_data, StrEq(expected_data)); @@ -448,13 +403,8 @@ TEST_F(ImageVault, image_purged_expired) mpt::make_file_with_content(file_name); return {file_name, source_image.id, "", "", "", {}}; }; - auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + auto vm_image = + vault.fetch_image(mp::FetchType::ImageOnly, default_query, prepare, stub_monitor, std::nullopt, instance_dir); EXPECT_TRUE(QFileInfo::exists(file_name)); @@ -474,13 +424,8 @@ TEST_F(ImageVault, image_exists_not_expired) mpt::make_file_with_content(file_name); return {file_name, source_image.id, "", "", "", {}}; }; - auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + auto vm_image = + vault.fetch_image(mp::FetchType::ImageOnly, default_query, prepare, stub_monitor, std::nullopt, instance_dir); EXPECT_TRUE(QFileInfo::exists(file_name)); @@ -515,13 +460,8 @@ TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(file_based_fetch_copies_image_an query.release = file.url().toStdString(); query.query_type = mp::Query::Type::LocalFile; - auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + auto vm_image = + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir); EXPECT_TRUE(QFileInfo::exists(vm_image.image_path)); EXPECT_EQ(vm_image.id, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); @@ -535,14 +475,9 @@ TEST_F(ImageVault, invalid_custom_image_file_throws) query.release = "file://foo"; query.query_type = mp::Query::Type::LocalFile; - EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir), - std::runtime_error); + EXPECT_THROW( + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir), + std::runtime_error); } TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(custom_image_url_downloads)) @@ -553,7 +488,7 @@ TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(custom_image_url_downloads)) query.release = "http://www.foo.com/fake.img"; query.query_type = mp::Query::Type::HttpDownload; - vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, false, std::nullopt, instance_dir); + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir); EXPECT_THAT(url_downloader.downloaded_files.size(), Eq(1)); EXPECT_TRUE(url_downloader.downloaded_urls.contains(QString::fromStdString(query.release))); @@ -567,7 +502,6 @@ TEST_F(ImageVault, missing_downloaded_image_throws) default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir), mp::CreateImageException); @@ -581,7 +515,6 @@ TEST_F(ImageVault, hash_mismatch_throws) default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir), mp::CreateImageException); @@ -595,14 +528,9 @@ TEST_F(ImageVault, invalid_remote_throws) query.remote_name = "foo"; - EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir), - std::runtime_error); + EXPECT_THROW( + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir), + std::runtime_error); } TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(invalid_image_alias_throw)) @@ -613,14 +541,9 @@ TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(invalid_image_alias_throw)) query.release = "foo"; - EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir), - mp::CreateImageException); + EXPECT_THROW( + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir), + mp::CreateImageException); } TEST_F(ImageVault, valid_remote_and_alias_returns_valid_image_info) @@ -632,13 +555,9 @@ TEST_F(ImageVault, valid_remote_and_alias_returns_valid_image_info) query.remote_name = "release"; mp::VMImage image; - EXPECT_NO_THROW(image = vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir)); + EXPECT_NO_THROW( + image = + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir)); EXPECT_THAT(image.original_release, Eq("18.04 LTS")); EXPECT_THAT(image.id, Eq("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); @@ -653,13 +572,9 @@ TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(http_download_returns_expected_i mp::Query query{instance_name, image_url, false, "", mp::Query::Type::HttpDownload}; mp::VMImage image; - EXPECT_NO_THROW(image = vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir)); + EXPECT_NO_THROW( + image = + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir)); // Hash is based on image url EXPECT_THAT(image.id, Eq("7404f51c9b4f40312fa048a0ad36e07b74b718a2d3a5a08e8cca906c69059ddf")); @@ -669,13 +584,7 @@ TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(http_download_returns_expected_i TEST_F(ImageVault, image_update_creates_new_dir_and_removes_old) { mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}}; - vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + vault.fetch_image(mp::FetchType::ImageOnly, default_query, stub_prepare, stub_monitor, std::nullopt, instance_dir); auto original_file{url_downloader.downloaded_files[0]}; auto original_absolute_path{QFileInfo(original_file).absolutePath()}; @@ -710,7 +619,6 @@ TEST_F(ImageVault, aborted_download_throws) default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir), mp::AbortedDownloadException); @@ -728,7 +636,6 @@ TEST_F(ImageVault, minimum_image_size_returns_expected_size) default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -751,13 +658,8 @@ TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(file_based_minimum_size_returns_ query.release = file.url().toStdString(); query.query_type = mp::Query::Type::LocalFile; - auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + auto vm_image = + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir); const auto size = vault.minimum_image_size_for(vm_image.id); @@ -784,7 +686,6 @@ TEST_F(ImageVault, minimum_image_size_throws_when_qemuimg_info_crashes) default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -803,7 +704,6 @@ TEST_F(ImageVault, minimum_image_size_throws_when_qemuimg_info_cannot_find_the_i default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -822,7 +722,6 @@ TEST_F(ImageVault, minimum_image_size_throws_when_qemuimg_info_does_not_understa default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir); @@ -895,13 +794,7 @@ TEST_F(ImageVault, updateImagesLogsWarningOnUnsupportedImage) { mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(mpl::Level::warning); mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}}; - vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + vault.fetch_image(mp::FetchType::ImageOnly, default_query, stub_prepare, stub_monitor, std::nullopt, instance_dir); EXPECT_CALL(host, info_for(_)).WillOnce(Throw(mp::UnsupportedImageException(default_query.release))); @@ -919,13 +812,7 @@ TEST_F(ImageVault, updateImagesLogsWarningOnEmptyVault) { mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(mpl::Level::warning); mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}}; - vault.fetch_image(mp::FetchType::ImageOnly, - default_query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir); + vault.fetch_image(mp::FetchType::ImageOnly, default_query, stub_prepare, stub_monitor, std::nullopt, instance_dir); EXPECT_CALL(host, info_for(_)).WillOnce(Return(std::nullopt)); @@ -950,7 +837,6 @@ TEST_F(ImageVault, fetchLocalImageThrowsOnEmptyVault) default_query, stub_prepare, stub_monitor, - false, std::nullopt, instance_dir), mp::ImageNotFoundException); @@ -963,12 +849,7 @@ TEST_F(ImageVault, fetchRemoteImageThrowsOnMissingKernel) EXPECT_CALL(host, info_for(_)).WillOnce(Return(std::nullopt)); - EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly, - query, - stub_prepare, - stub_monitor, - false, - std::nullopt, - instance_dir), - mp::ImageNotFoundException); + EXPECT_THROW( + vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, std::nullopt, instance_dir), + mp::ImageNotFoundException); } diff --git a/tests/test_persistent_settings_handler.cpp b/tests/test_persistent_settings_handler.cpp index 0e073c9be8..cbef22760e 100644 --- a/tests/test_persistent_settings_handler.cpp +++ b/tests/test_persistent_settings_handler.cpp @@ -28,6 +28,7 @@ #include #include +#include namespace mp = multipass; namespace mpt = mp::test; diff --git a/tests/test_sftpserver.cpp b/tests/test_sftpserver.cpp index f271eeb5d3..e7bc8b1d6a 100644 --- a/tests/test_sftpserver.cpp +++ b/tests/test_sftpserver.cpp @@ -262,7 +262,8 @@ bool compare_permission(uint32_t ssh_permissions, const QFileInfo& file, Permiss break; } - return ((ssh_permissions & ssh_perm_mask) >> ssh_bitshift) == ((file.permissions() & qt_perm_mask) >> qt_bitshift); + return ((ssh_permissions & ssh_perm_mask) >> ssh_bitshift) == + ((static_cast(file.permissions()) & qt_perm_mask) >> qt_bitshift); } } // namespace diff --git a/tests/test_ubuntu_image_host.cpp b/tests/test_ubuntu_image_host.cpp index acc67c338a..154ec128b9 100644 --- a/tests/test_ubuntu_image_host.cpp +++ b/tests/test_ubuntu_image_host.cpp @@ -27,9 +27,7 @@ #include #include -#include #include -#include #include #include @@ -51,9 +49,6 @@ struct UbuntuImageHost : public testing::Test { UbuntuImageHost() { - EXPECT_CALL(mock_platform, is_remote_supported(_)).WillRepeatedly(Return(true)); - EXPECT_CALL(mock_platform, is_alias_supported(_, _)).WillRepeatedly(Return(true)); - EXPECT_CALL(mock_settings, get(Eq(mp::driver_key))).WillRepeatedly(Return("emu")); /* TODO parameterize driver (code branches for lxd) */ EXPECT_CALL(mock_settings, get(Eq(mp::mirror_key))).WillRepeatedly(Return("")); @@ -177,22 +172,6 @@ TEST_F(UbuntuImageHost, iterates_over_all_entries) EXPECT_THAT(ids.count("520224efaaf49b15a976b49c7ce7f2bd2e5b161470d684b37a838933595c0520"), Eq(1u)); } -TEST_F(UbuntuImageHost, unsupported_alias_iterates_over_expected_entries) -{ - mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader}; - host.update_manifests(false); - - std::unordered_set ids; - auto action = [&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); }; - - EXPECT_CALL(mock_platform, is_alias_supported(AnyOf("zesty", "17.04", "z"), _)).WillRepeatedly(Return(false)); - - host.for_each_entry_do(action); - - const size_t expected_entries{4}; - EXPECT_THAT(ids.size(), Eq(expected_entries)); -} - TEST_F(UbuntuImageHost, can_query_by_hash) { mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader}; @@ -327,19 +306,6 @@ TEST_F(UbuntuImageHost, all_images_for_daily_returns_all_matches) EXPECT_THAT(images.size(), Eq(expected_matches)); } -TEST_F(UbuntuImageHost, all_images_for_release_unsupported_alias_returns_three_matches) -{ - mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader}; - host.update_manifests(false); - - EXPECT_CALL(mock_platform, is_alias_supported(AnyOf("zesty", "17.04", "z"), _)).WillRepeatedly(Return(false)); - - auto images = host.all_images_for(release_remote_spec.first, false); - - const size_t expected_matches{3}; - EXPECT_EQ(images.size(), expected_matches); -} - TEST_F(UbuntuImageHost, supported_remotes_returns_expected_values) { mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader}; @@ -490,41 +456,3 @@ TEST_F(UbuntuImageHost, all_info_for_unsupported_image_throw) mp::UnsupportedImageException, mpt::match_what(StrEq(fmt::format("The {} release is no longer supported.", release)))); } - -TEST_F(UbuntuImageHost, all_info_for_unsupported_alias_throws) -{ - mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader}; - host.update_manifests(false); - - const std::string unsupported_alias{"daily"}; - EXPECT_CALL(mock_platform, is_alias_supported(unsupported_alias, _)).WillOnce(Return(false)); - - MP_EXPECT_THROW_THAT( - host.all_info_for(make_query(unsupported_alias, release_remote_spec.first)), mp::UnsupportedAliasException, - mpt::match_what(HasSubstr(fmt::format("\'{}\' is not a supported alias.", unsupported_alias)))); -} - -TEST_F(UbuntuImageHost, info_for_unsupported_remote_throws) -{ - mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader}; - host.update_manifests(false); - - const std::string unsupported_remote{"bar"}; - EXPECT_CALL(mock_platform, is_remote_supported(unsupported_remote)).WillRepeatedly(Return(false)); - - MP_EXPECT_THROW_THAT(host.info_for(make_query("xenial", unsupported_remote)), mp::UnsupportedRemoteException, - mpt::match_what(HasSubstr(fmt::format( - "Remote \'{}\' is not a supported remote for this platform.", unsupported_remote)))); -} - -TEST_F(UbuntuImageHost, info_for_no_remote_first_unsupported_returns_expected_info) -{ - mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader}; - host.update_manifests(false); - - EXPECT_CALL(mock_platform, is_remote_supported("release")).Times(AtLeast(1)).WillRepeatedly(Return(false)); - - auto info = host.info_for(make_query("artful", "")); - - EXPECT_EQ(info->id, "c09f123b9589c504fe39ec6e9ebe5188c67be7d1fc4fb80c969bf877f5a8333a"); -} diff --git a/tests/test_utils.cpp b/tests/test_utils.cpp index 7ac5bd8773..2c5eb4d879 100644 --- a/tests/test_utils.cpp +++ b/tests/test_utils.cpp @@ -452,7 +452,8 @@ TEST(Utils, trim_newline_works) TEST(Utils, trim_newline_assertion_works) { std::string s{"wrong"}; - ASSERT_DEBUG_DEATH(mp::utils::trim_newline(s), "[Aa]ssert"); + // https://google.github.io/googletest/advanced.html#regular-expression-syntax + ASSERT_DEBUG_DEATH(mp::utils::trim_newline(s), "\\wssert"); } TEST(Utils, escape_for_shell_actually_escapes) diff --git a/tests/virtualbox/CMakeLists.txt b/tests/virtualbox/CMakeLists.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/windows/CMakeLists.txt b/tests/windows/CMakeLists.txt new file mode 100644 index 0000000000..415de08951 --- /dev/null +++ b/tests/windows/CMakeLists.txt @@ -0,0 +1,7 @@ +target_sources(multipass_tests + PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/powershell_test_helper.cpp + ${CMAKE_CURRENT_LIST_DIR}/test_platform_win.cpp + ${CMAKE_CURRENT_LIST_DIR}/test_powershell.cpp + ${CMAKE_CURRENT_LIST_DIR}/test_smb_mount_handler.cpp +) diff --git a/tests/windows/powershell_test_helper.cpp b/tests/windows/powershell_test_helper.cpp new file mode 100644 index 0000000000..ffb1d67073 --- /dev/null +++ b/tests/windows/powershell_test_helper.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "powershell_test_helper.h" + +#include "tests/common.h" + +namespace mpt = multipass::test; + +void mpt::PowerShellTestHelper::mock_ps_exec(const std::optional& output, + const std::optional& output_err, + bool succeed) +{ + setup( + [output, output_err, succeed](auto* process) { + InSequence seq; + + if (output.has_value()) + { + auto emit_ready_read = [process] { emit process->ready_read_standard_output(); }; + EXPECT_CALL(*process, start).WillOnce(Invoke(emit_ready_read)); + EXPECT_CALL(*process, read_all_standard_output).WillOnce(Return(*output)); + } + + if (output_err.has_value()) + { + auto emit_ready_read_err = [process] { emit process->ready_read_standard_error(); }; + EXPECT_CALL(*process, start).WillOnce(Invoke(emit_ready_read_err)); + EXPECT_CALL(*process, read_all_standard_error).WillOnce(Return(*output_err)); + } + + EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(succeed)); + EXPECT_CALL(*process, process_id).WillOnce(Return(9999)); + }, + /* auto_exit = */ false); +} + +void mpt::PowerShellTestHelper::setup_mocked_run_sequence(std::vector runs) +{ + setup([this, runs_ = std::move(runs)](auto* process) { + InSequence seq; + for (const auto& run : runs_) + add_mocked_run(process, run); + }); +} + +void mpt::PowerShellTestHelper::setup(const MockProcessFactory::Callback& callback, bool auto_exit) +{ + factory_scope->register_callback([this, callback, auto_exit](MockProcess* process) { + setup_process(process, auto_exit); + if (callback) + callback(process); + }); +} + +bool mpt::PowerShellTestHelper::ps_write(multipass::PowerShell& ps, const QByteArray& data) +{ + return ps.write(data); +} + +QByteArray mpt::PowerShellTestHelper::get_status(bool succeed) const +{ + return succeed ? " True\n" : " False\n"; +} + +QByteArray mpt::PowerShellTestHelper::end_marker(bool succeed) const +{ + return QByteArray{"\n"}.append(output_end_marker.toUtf8()).append(get_status(succeed)); +} + +void mpt::PowerShellTestHelper::expect_writes(MockProcess* process, QByteArray cmdlet) const +{ + auto cmdlet_matcher = Truly([expect = std::move(cmdlet)](const QByteArray& got) { return got.contains(expect); }); + EXPECT_CALL(*process, write(cmdlet_matcher)).WillOnce(Return(written)); + + auto marker_matcher = Property(&QByteArray::toStdString, HasSubstr(output_end_marker.toStdString())); + EXPECT_CALL(*process, write(marker_matcher)).WillOnce(Return(written)); +} + +bool mpt::PowerShellTestHelper::was_ps_run() const +{ + return forked; +} + +void mpt::PowerShellTestHelper::setup_process(MockProcess* process, bool auto_exit) +{ + if (process->program() == psexe) + { + // succeed these by default + if (auto_exit) + { + EXPECT_CALL(*process, write(Eq(psexit))).WillOnce(Return(written)); + EXPECT_CALL(*process, wait_for_finished(_)).WillOnce(Return(true)); + } + + forked = true; + } +} + +void mpt::PowerShellTestHelper::add_mocked_run(MockProcess* process, const RunSpec& run) +{ + const auto& [cmdlet, output, result] = run; + expect_writes(process, QByteArray::fromStdString(cmdlet)); + + auto ps_output = QByteArray::fromStdString(output).append(end_marker(result)); + EXPECT_CALL(*process, read_all_standard_output).WillOnce(Return(ps_output)); +} diff --git a/tests/windows/powershell_test_helper.h b/tests/windows/powershell_test_helper.h new file mode 100644 index 0000000000..1ad7b88fec --- /dev/null +++ b/tests/windows/powershell_test_helper.h @@ -0,0 +1,84 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#ifndef MULTIPASS_POWERSHELL_TEST_HELPER_H +#define MULTIPASS_POWERSHELL_TEST_HELPER_H + +#include + +#include "tests/mock_logger.h" +#include "tests/mock_process_factory.h" + +#include + +#include +#include + +using namespace testing; + +namespace multipass::test +{ +class PowerShellTestHelper : private DisabledCopyMove +{ +public: + PowerShellTestHelper() = default; + virtual ~PowerShellTestHelper() = default; + + // Mocks powershell to have output in stdout, output_err in stderr, and return succeed. + // use std::nullopt to specify no stdout/stderr, "" is still some output. + // only the last call to this function has any effect at the moment the PS process is created + void mock_ps_exec(const std::optional& output, + const std::optional& output_err = std::nullopt, + bool succeed = true); + + struct RunSpec + { + std::string expect_cmdlet_substr; + std::string will_output = ""; + bool will_return = true; + }; + + // mock the specified sequence of runs + void setup_mocked_run_sequence(std::vector runs); + + // setup low-level expectations on the powershell process + void setup(const MockProcessFactory::Callback& callback = {}, bool auto_exit = true); + + // proxy to private PS::write method + bool ps_write(PowerShell& ps, const QByteArray& data); + + bool was_ps_run() const; + QByteArray get_status(bool succeed) const; + QByteArray end_marker(bool succeed) const; + void expect_writes(MockProcess* process, QByteArray cmdlet) const; + + inline static constexpr auto psexit = "Exit\n"; + inline static constexpr auto written = 1'000'000; + inline static const QString& output_end_marker = PowerShell::output_end_marker; + +private: + void setup_process(MockProcess* process, bool auto_exit); + void add_mocked_run(MockProcess* process, const RunSpec& run); + + bool forked = false; + std::unique_ptr factory_scope = MockProcessFactory::Inject(); + inline static constexpr auto psexe = "powershell.exe"; +}; + +} // namespace multipass::test + +#endif // MULTIPASS_POWERSHELL_TEST_HELPER_H diff --git a/tests/windows/test_platform_win.cpp b/tests/windows/test_platform_win.cpp new file mode 100644 index 0000000000..12310d5280 --- /dev/null +++ b/tests/windows/test_platform_win.cpp @@ -0,0 +1,680 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "tests/common.h" +#include "tests/mock_environment_helpers.h" +#include "tests/mock_file_ops.h" +#include "tests/mock_logger.h" +#include "tests/mock_settings.h" +#include "tests/mock_standard_paths.h" +#include "tests/mock_utils.h" +#include "tests/temp_dir.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +namespace mp = multipass; +namespace mpl = mp::logging; +namespace mpt = mp::test; +using namespace testing; + +namespace +{ + +auto expect_only_log(multipass::logging::Level lvl, const std::string& substr) +{ + auto logger_scope = mpt::MockLogger::inject(); + logger_scope.mock_logger->screen_logs(); + logger_scope.mock_logger->expect_log(lvl, substr); + return logger_scope; +} + +void mock_stdpaths_locate(const QString& ret) +{ + EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), + locate(_, Property(&QString::toStdString, EndsWith("settings.json")), _)) + .WillOnce(Return(ret)); +} + +auto guarded_fake_json(const char* contents) +{ + QTemporaryFile json_file; + EXPECT_TRUE(json_file.open()); // can't use gtest's asserts in non-void function + EXPECT_TRUE(json_file.exists()); // idem + + json_file.write(contents); + json_file.close(); + + auto filename = json_file.fileName(); + mock_stdpaths_locate(filename); + + json_file.setAutoRemove(false); // we need to release the file but keep it around, so that it can be overwritten + auto guard = + sg::make_scope_guard([filename = filename.toStdString()]() noexcept { // we have to remove it ourselves later on + std::error_code ec; + std::filesystem::remove(filename, ec); + }); + + return std::make_pair(filename, std::move(guard)); // needs to be moved into the pair first (NRVO does not apply) +} + +// ptr works around uncopyable QTemporaryFile +auto guarded_fake_json(const Json::Value& json) +{ + std::ostringstream oss; + oss << json; + const auto data = oss.str(); + + return guarded_fake_json(data.c_str()); +} + +Json::Value read_json(const QString& filename) +{ + std::ifstream ifs{filename.toStdString(), std::ifstream::binary}; + EXPECT_TRUE(ifs); // can't use gtest's asserts in non-void function + + Json::Value json; + EXPECT_NO_THROW(ifs >> json); // idem + + return json; +} + +Json::Value& setup_primary_profile(Json::Value& json) +{ + auto& ret = json["profiles"][0u]; + ret["guid"] = mp::winterm_profile_guid; + ret["cursorColor"] = "#FDFDFD"; + ret["foreground"] = "#FDFDFD"; + return ret; +} + +TEST(PlatformWin, test_interpretation_of_unknown_settings_not_supported) +{ + for (const auto k : {"unimaginable", "katxama", "katxatxa"}) + for (const auto v : {"no", "matter", "what"}) + EXPECT_THROW(mp::platform::interpret_setting(k, v), mp::InvalidSettingException); +} + +TEST(PlatformWin, winterm_in_extra_client_settings) +{ + auto extras = MP_PLATFORM.extra_client_settings(); + ASSERT_EQ(extras.size(), 1); + + auto& spec = **extras.begin(); + MP_EXPECT_THROW_THAT(spec.interpret("wrong"), + mp::InvalidSettingException, + mpt::match_what(HasSubstr(mp::winterm_key))); +} + +TEST(PlatformWin, no_extra_daemon_settings) +{ + EXPECT_THAT(MP_PLATFORM.extra_daemon_settings(), IsEmpty()); +} + +TEST(PlatformWin, test_default_driver) +{ + EXPECT_THAT(MP_PLATFORM.default_driver(), AnyOf("hyperv", "virtualbox")); +} + +TEST(PlatformWin, test_default_privileged_mounts) +{ + EXPECT_EQ(MP_PLATFORM.default_privileged_mounts(), "false"); +} + +TEST(PlatformWin, valid_winterm_setting_values) +{ + for (const auto x : {"none", "primary"}) + EXPECT_EQ(mp::platform::interpret_setting(mp::winterm_key, x), x); +} + +TEST(PlatformWin, winterm_setting_values_case_insensitive) +{ + for (const auto x : {"NoNe", "NONE", "nonE", "NonE"}) + EXPECT_EQ(mp::platform::interpret_setting(mp::winterm_key, x), "none"); + + for (const auto x : {"pRIMARY", "Primary", "pRimarY"}) + EXPECT_EQ(mp::platform::interpret_setting(mp::winterm_key, x), "primary"); +} + +TEST(PlatformWin, unsupported_winterm_setting_values_cause_exception) +{ + for (const auto x : {"Unsupported", "values", "1", "000", "false", "True", "", " "}) + MP_EXPECT_THROW_THAT( + mp::platform::interpret_setting(mp::winterm_key, x), + mp::InvalidSettingException, + Property(&mp::InvalidSettingException::what, + AllOf(HasSubstr(mp::winterm_key), HasSubstr(x), HasSubstr("none"), HasSubstr("primary")))); +} + +struct TestWinTermBase : public Test +{ + void mock_winterm_setting(const QString& ret) + { + EXPECT_CALL(mock_settings, get(Eq(mp::winterm_key))).WillOnce(Return(ret)); + } + + mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject(); + mpt::MockSettings& mock_settings = *mock_settings_injection.first; +}; + +struct TestWinTermSyncLesserLogging : public TestWinTermBase, public WithParamInterface> +{ +}; + +TEST_P(TestWinTermSyncLesserLogging, logging_on_no_file) +{ + const auto& [setting, lvl] = GetParam(); + + mock_winterm_setting(setting); + mock_stdpaths_locate(""); + auto mock_logger_guard = expect_only_log(lvl, "Could not find"); + + mp::platform::sync_winterm_profiles(); +} + +INSTANTIATE_TEST_SUITE_P(PlatformWin, + TestWinTermSyncLesserLogging, + Values(std::make_pair(QStringLiteral("none"), mpl::Level::debug), + std::make_pair(QStringLiteral("primary"), mpl::Level::warning))); + +struct TestWinTermSyncModerateLogging : public TestWinTermBase, + public WithParamInterface> +{ +}; + +TEST_P(TestWinTermSyncModerateLogging, logging_on_unreadable_settings) +{ + const auto& [setting, lvl] = GetParam(); + + mock_winterm_setting(setting); + mock_stdpaths_locate("C:\\unreadable\\settings.json"); + const auto mock_logger_guard = expect_only_log(lvl, "Could not read"); + + mp::platform::sync_winterm_profiles(); +} + +TEST_P(TestWinTermSyncModerateLogging, logging_on_unparseable_settings) +{ + const auto& [setting, lvl] = GetParam(); + mock_winterm_setting(setting); + + const auto [json_file_name, tmp_file_guard] = guarded_fake_json("~!@#$% rubbish ^&*()_+"); + const auto mock_logger_guard = expect_only_log(lvl, "Could not parse"); + + mp::platform::sync_winterm_profiles(); +} + +TEST_P(TestWinTermSyncModerateLogging, logging_on_unavailable_profiles) +{ + const auto& [setting, lvl] = GetParam(); + mock_winterm_setting(setting); + + const auto [json_file_name, tmp_file_guard] = guarded_fake_json("{ \"someNode\": \"someValue\" }"); + const auto mock_logger_guard = expect_only_log(lvl, "Could not find"); + + mp::platform::sync_winterm_profiles(); +} + +INSTANTIATE_TEST_SUITE_P(PlatformWin, + TestWinTermSyncModerateLogging, + Values(std::make_pair(QStringLiteral("none"), mpl::Level::info), + std::make_pair(QStringLiteral("primary"), mpl::Level::error))); + +struct TestWinTermSyncGreaterLogging : public TestWinTermBase, public WithParamInterface +{ +}; + +TEST_P(TestWinTermSyncGreaterLogging, logging_on_failure_to_overwrite) +{ + const auto& setting = GetParam(); + mock_winterm_setting(setting); + + Json::Value json; + auto& profile = setup_primary_profile(json); + profile["hidden"] = (setting != "none"); // make this the opposite of what the setting says, to require an update + + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + + std::ifstream handle{json_file_name.toStdString()}; // open the file, to provoke a failure in overwriting + const auto mock_logger_guard = expect_only_log(mpl::Level::error, "Could not update"); + + mp::platform::sync_winterm_profiles(); +} + +INSTANTIATE_TEST_SUITE_P(PlatformWin, + TestWinTermSyncGreaterLogging, + Values(QStringLiteral("none"), QStringLiteral("primary"))); + +struct TestWinTermSyncNoLeftovers : public TestWinTermBase, public WithParamInterface +{ +}; + +TEST_P(TestWinTermSyncNoLeftovers, no_leftover_files_on_overwriting) +{ + bool fail = GetParam(); + mock_winterm_setting("primary"); + + Json::Value json; + json["profiles"]; + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + + const auto json_file_info = QFileInfo{json_file_name}; + const auto file_list = json_file_info.dir().entryList(); + + std::ifstream handle; + auto logger_scope = mpt::MockLogger::inject(); + logger_scope.mock_logger->screen_logs(); + + if (fail) + { + handle.open(json_file_name.toStdString()); // block overwriting + EXPECT_CALL(*logger_scope.mock_logger, log(mpl::Level::error, _, _)); + } + + mp::platform::sync_winterm_profiles(); + + if (fail) + ASSERT_EQ(read_json(json_file_name), json); + else + ASSERT_NE(read_json(json_file_name), json); + + EXPECT_EQ(json_file_info.dir().entryList(), file_list); +} + +INSTANTIATE_TEST_SUITE_P(PlatformWin, TestWinTermSyncNoLeftovers, Values(true, false)); + +class TestWinTermSyncJson : public TestWinTermBase, public WithParamInterface +{ +public: + struct DressUpFlags + { + enum Value : unsigned char + { + None = 0, + ProfilesDict = 1 << 0, + ProfileBefore = 1 << 1, + ProfileAfter = 1 << 2, + CommentBefore = 1 << 3, + CommentInline = 1 << 4, + CommentAfter = 1 << 5, + StuffOutside = 1 << 6, + End = 1 << 7 // do not pass this - delimits the combination + }; + static constexpr unsigned char begin = Value::None; + static constexpr unsigned char end = Value::End; + }; + + void SetUp() override + { + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + } + + void dress_up(Json::Value& json, unsigned char flags) + { + // std::cout << "DEBUG json before: " << json << std::endl; + auto& profiles = json["profiles"]; + ASSERT_LE(profiles.size(), 1u); + + dress_with_comments(profiles, flags); + dress_with_extra_profiles(profiles, flags); + dress_with_dict(profiles, flags); + dress_with_stuff(json, flags); + // std::cout << "DEBUG json after: " << json << std::endl; + } + + const Json::Value& get_profiles(const Json::Value& json) + { + const auto& profiles = json["profiles"]; + if (profiles.isNull() || profiles.isArray() || !profiles.isMember("list")) + return profiles; + return profiles["list"]; + } + + Json::Value& edit_profiles(Json::Value& json) + { + return const_cast(get_profiles(json)); + } + + const Json::Value& get_primary_profile(const Json::Value& json) + { + const auto& profiles = get_profiles(json); + + auto it = std::find_if(profiles.begin(), profiles.end(), [](const auto& profile) { + return profile["guid"] == mp::winterm_profile_guid; + }); + + if (it == profiles.end()) + throw std::runtime_error{"Test error - could not find primary profile"}; + + return *it; + } + + Json::Value& edit_primary_profile(Json::Value& json) + { + return const_cast(get_primary_profile(json)); + } + +private: + void dress_with_comments(Json::Value& profiles, unsigned char flags) + { + if (flags & (DressUpFlags::CommentBefore | DressUpFlags::CommentInline | DressUpFlags::CommentAfter)) + { + auto& elem = profiles.size() ? profiles[0] : profiles; + const auto comment = std::string{"// a comment"}; + + for (const auto [flag, place] : {std::make_pair(DressUpFlags::CommentBefore, Json::commentBefore), + std::make_pair(DressUpFlags::CommentInline, Json::commentAfterOnSameLine), + std::make_pair(DressUpFlags::CommentAfter, Json::commentAfter)}) + if (flags & flag) + elem.setComment(comment, place); + } + } + + void dress_with_extra_profiles(Json::Value& profiles, unsigned char flags) + { + if (flags & (DressUpFlags::ProfileBefore | DressUpFlags::ProfileAfter)) + { + auto num_profiles = profiles.size(); + for (const auto [flag, distinctive] : {std::make_pair(DressUpFlags::ProfileBefore, "aaa"), + std::make_pair(DressUpFlags::ProfileAfter, "zzz")}) + if (flags & flag) + { + profiles[num_profiles]["guid"] = fmt::format("fake_id_{}", distinctive); + profiles[num_profiles]["command"] = fmt::format("FAKEEEE {}", distinctive); + + if (flag == DressUpFlags::ProfileBefore && num_profiles) + profiles[0u].swap(profiles[num_profiles]); + + ++num_profiles; + } + } + } + + void dress_with_dict(Json::Value& profiles, unsigned char flags) + { + if (flags & DressUpFlags::ProfilesDict) + { + Json::Value profiles_dict; + profiles_dict["list"] = profiles; + profiles_dict["defaults"]["var"] = "val"; + profiles_dict["defaults"]["foo"] = "bar"; + profiles.swap(profiles_dict); + } + } + + void dress_with_stuff(Json::Value& json, unsigned char flags) + { + if (flags & DressUpFlags::StuffOutside) + json["stuff"]["a"]["b"]["c"] = "asdf"; + } + + mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(); +}; + +TEST_P(TestWinTermSyncJson, winterm_sync_keeps_visible_profile_if_setting_primary) +{ + mock_winterm_setting("primary"); + + Json::Value json; + auto& profile = setup_primary_profile(json); + profile["hidden"] = false; + + dress_up(json, GetParam()); + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + const auto timestamp = QFileInfo{json_file_name}.lastModified(); + + mp::platform::sync_winterm_profiles(); + + EXPECT_EQ(QFileInfo{json_file_name}.lastModified(), timestamp); + EXPECT_EQ(json, read_json(json_file_name)); +} + +TEST_P(TestWinTermSyncJson, winterm_sync_enables_hidden_profile_if_setting_primary) +{ + mock_winterm_setting("primary"); + + Json::Value json; + auto& profile = setup_primary_profile(json); + profile["hidden"] = true; + + dress_up(json, GetParam()); + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + + mp::platform::sync_winterm_profiles(); + + edit_primary_profile(json)["hidden"] = false; + EXPECT_EQ(json, read_json(json_file_name)); +} + +TEST_P(TestWinTermSyncJson, winterm_sync_keeps_profile_without_hidden_flag_if_setting_primary) +{ + mock_winterm_setting("primary"); + + Json::Value json; + setup_primary_profile(json); + + dress_up(json, GetParam()); + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + const auto timestamp = QFileInfo{json_file_name}.lastModified(); + + mp::platform::sync_winterm_profiles(); + + EXPECT_EQ(QFileInfo{json_file_name}.lastModified(), timestamp); + EXPECT_EQ(json, read_json(json_file_name)); +} + +TEST_P(TestWinTermSyncJson, winterm_sync_adds_missing_profile_if_setting_primary) +{ + mock_winterm_setting("primary"); + + Json::Value json_in; + dress_up(json_in, GetParam()); + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json_in); + + mp::platform::sync_winterm_profiles(); + const auto json_out = read_json(json_file_name); + + Json::Value primary_profile; + ASSERT_NO_THROW(primary_profile = get_primary_profile(json_out)); + EXPECT_EQ(primary_profile["name"], "Multipass"); + EXPECT_THAT(primary_profile["commandline"].asString(), HasSubstr(mp::client_name)); + EXPECT_THAT(primary_profile["fontFace"].asString(), HasSubstr("Ubuntu")); + EXPECT_THAT(primary_profile["icon"].asString(), EndsWith(".ico")); + EXPECT_TRUE(primary_profile.isMember("background")); + + auto json_proof = json_out; // copy json_out so we can keep it const (to ensure indexing doesn't change it above) + edit_profiles(json_proof) = get_profiles(json_in); + EXPECT_EQ(json_proof, json_in); // confirm the rest of the json is the same +} + +TEST_P(TestWinTermSyncJson, winterm_sync_keeps_missing_profile_if_setting_none) +{ + mock_winterm_setting("none"); + + Json::Value json; + dress_up(json, GetParam()); + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + const auto timestamp = QFileInfo{json_file_name}.lastModified(); + + mp::platform::sync_winterm_profiles(); + + EXPECT_EQ(QFileInfo{json_file_name}.lastModified(), timestamp); + EXPECT_EQ(json, read_json(json_file_name)); +} + +TEST_P(TestWinTermSyncJson, winterm_sync_keeps_hidden_profile_if_setting_none) +{ + mock_winterm_setting("none"); + + Json::Value json; + auto& profile = setup_primary_profile(json); + profile["hidden"] = true; + + dress_up(json, GetParam()); + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + const auto timestamp = QFileInfo{json_file_name}.lastModified(); + + mp::platform::sync_winterm_profiles(); + + EXPECT_EQ(QFileInfo{json_file_name}.lastModified(), timestamp); + EXPECT_EQ(json, read_json(json_file_name)); +} + +TEST_P(TestWinTermSyncJson, winterm_sync_disables_visible_profile_if_setting_none) +{ + mock_winterm_setting("none"); + + Json::Value json; + auto& profile = setup_primary_profile(json); + profile["hidden"] = false; + + dress_up(json, GetParam()); + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + + mp::platform::sync_winterm_profiles(); + + edit_primary_profile(json)["hidden"] = true; + EXPECT_EQ(json, read_json(json_file_name)); +} + +TEST_P(TestWinTermSyncJson, winterm_sync_disables_profile_without_hidden_flag_if_setting_none) +{ + mock_winterm_setting("none"); + + Json::Value json; + setup_primary_profile(json); + + dress_up(json, GetParam()); + const auto [json_file_name, tmp_file_guard] = guarded_fake_json(json); + + mp::platform::sync_winterm_profiles(); + + edit_primary_profile(json)["hidden"] = true; + EXPECT_EQ(json, read_json(json_file_name)); +} + +INSTANTIATE_TEST_SUITE_P(PlatformWin, + TestWinTermSyncJson, + Range(TestWinTermSyncJson::DressUpFlags::begin, TestWinTermSyncJson::DressUpFlags::end)); + +TEST(PlatformWin, create_alias_script_works) +{ + const mpt::TempDir tmp_dir; + + EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::HomeLocation)) + .WillOnce(Return(tmp_dir.path())); + + EXPECT_NO_THROW(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command"})); + + QFile checked_script(tmp_dir.path() + "/AppData/local/multipass/bin/alias_name.bat"); + checked_script.open(QFile::ReadOnly); + + std::string script_line = checked_script.readLine().toStdString(); + EXPECT_THAT(script_line, HasSubstr("@")); + EXPECT_THAT(script_line, HasSubstr(" alias_name -- %*\n")); + EXPECT_TRUE(checked_script.atEnd()); +} + +TEST(PlatformWin, create_alias_script_overwrites) +{ + auto [mock_utils, guard1] = mpt::MockUtils::inject(); + auto [mock_file_ops, guard2] = mpt::MockFileOps::inject(); + + EXPECT_CALL(*mock_utils, make_file_with_content(_, _, true)).Times(1); + + EXPECT_NO_THROW(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "other_command"})); +} + +TEST(PlatformWin, create_alias_script_throws_if_cannot_create_path) +{ + auto [mock_file_ops, guard] = mpt::MockFileOps::inject(); + + EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(false)); + + MP_EXPECT_THROW_THAT(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command"}), + std::runtime_error, + mpt::match_what(HasSubstr("failed to create dir '"))); +} + +TEST(PlatformWin, create_alias_script_throws_if_cannot_write_script) +{ + auto [mock_file_ops, guard] = mpt::MockFileOps::inject(); + + EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(true)); + EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true)); + EXPECT_CALL(*mock_file_ops, write(A(), _, _)).WillOnce(Return(747)); + + MP_EXPECT_THROW_THAT(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command"}), + std::runtime_error, + mpt::match_what(HasSubstr("failed to write to file '"))); +} + +TEST(PlatformWin, remove_alias_script_works) +{ + const mpt::TempDir tmp_dir; + QFile script_file(tmp_dir.path() + "/AppData/local/multipass/bin/alias_name.bat"); + + EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::HomeLocation)) + .WillOnce(Return(tmp_dir.path())); + + MP_UTILS.make_file_with_content(script_file.fileName().toStdString(), "script content\n"); + + EXPECT_NO_THROW(MP_PLATFORM.remove_alias_script("alias_name")); + + EXPECT_FALSE(script_file.exists()); +} + +TEST(PlatformWin, remove_alias_script_throws_if_cannot_remove_script) +{ + const mpt::TempDir tmp_dir; + QFile script_file(tmp_dir.path() + "/AppData/local/multipass/bin/alias_name.bat"); + + EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::HomeLocation)) + .WillOnce(Return(tmp_dir.path())); + + MP_EXPECT_THROW_THAT(MP_PLATFORM.remove_alias_script("alias_name"), + std::runtime_error, + mpt::match_what(StrEq("error removing alias script"))); +} + +TEST(PlatformWin, get_cpus_returns_greater_than_zero) +{ + EXPECT_GT(MP_PLATFORM.get_cpus(), 0); +} + +TEST(PlatformWin, get_total_ram_returns_greater_than_zero) +{ + EXPECT_GT(MP_PLATFORM.get_total_ram(), 0LL); +} + +} // namespace diff --git a/tests/windows/test_powershell.cpp b/tests/windows/test_powershell.cpp new file mode 100644 index 0000000000..56cfb26484 --- /dev/null +++ b/tests/windows/test_powershell.cpp @@ -0,0 +1,393 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "powershell_test_helper.h" + +#include "tests/common.h" +#include "tests/mock_logger.h" +#include "tests/mock_process_factory.h" + +#include + +#include + +#include +#include + +namespace mp = multipass; +namespace mpl = multipass::logging; +namespace mpt = multipass::test; +using namespace testing; + +struct PowerShellTest : public Test +{ + void TearDown() override + { + ASSERT_TRUE(ps_helper.was_ps_run()); + } + + mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(); + mpt::PowerShellTestHelper ps_helper; +}; + +TEST_F(PowerShellTest, creates_ps_process) +{ + logger_scope.mock_logger->screen_logs(mpl::Level::error); + ps_helper.setup([](auto* process) { EXPECT_CALL(*process, start()).Times(1); }); + + mp::PowerShell ps{"test"}; +} + +TEST_F(PowerShellTest, exits_ps_process) +{ + logger_scope.mock_logger->screen_logs(mpl::Level::info); + ps_helper.setup( + [](auto* process) { + EXPECT_CALL(*process, write(Eq(mpt::PowerShellTestHelper::psexit))) + .WillOnce(Return(mpt::PowerShellTestHelper::written)); + EXPECT_CALL(*process, wait_for_finished(_)).WillOnce(Return(true)); + }, + /* auto_exit = */ false); + + mp::PowerShell ps{"test"}; +} + +TEST_F(PowerShellTest, handles_failure_to_write_on_exit) +{ + auto& logger = *logger_scope.mock_logger; + logger.screen_logs(mpl::Level::error); + logger.expect_log(mpl::Level::warning, "Failed to exit"); + + ps_helper.setup( + [](auto* process) { + EXPECT_CALL(*process, write(Eq(mpt::PowerShellTestHelper::psexit))).WillOnce(Return(-1)); + EXPECT_CALL(*process, kill); + }, + /* auto_exit = */ false); + + mp::PowerShell ps{"test"}; +} + +TEST_F(PowerShellTest, handles_failure_to_finish_on_exit) +{ + static constexpr auto err = "timeout"; + auto& logger = *logger_scope.mock_logger; + logger.screen_logs(mpl::Level::error); + + auto msg_matcher = AllOf(HasSubstr("Failed to exit"), HasSubstr(err)); + EXPECT_CALL(logger, log(mpl::Level::warning, _, msg_matcher)); + + ps_helper.setup( + [](auto* process) { + EXPECT_CALL(*process, write(Eq(mpt::PowerShellTestHelper::psexit))) + .WillOnce(Return(mpt::PowerShellTestHelper::written)); + EXPECT_CALL(*process, wait_for_finished(_)).WillOnce(Return(false)); + EXPECT_CALL(*process, error_string).WillOnce(Return(err)); + EXPECT_CALL(*process, kill); + }, + /* auto_exit = */ false); + + mp::PowerShell ps{"test"}; +} + +TEST_F(PowerShellTest, uses_name_in_logs) +{ + auto& logger = *logger_scope.mock_logger; + static constexpr auto name = "Shevek"; + + logger.screen_logs(); + EXPECT_CALL(logger, log(_, StrEq(name), _)).Times(AtLeast(1)); + ps_helper.setup(); + + mp::PowerShell ps{name}; +} + +TEST_F(PowerShellTest, write_silent_on_success) +{ + static constexpr auto data = "Abbenay"; + ps_helper.setup([](auto* process) { EXPECT_CALL(*process, write(Eq(data))).WillOnce(Return(std::strlen(data))); }); + + mp::PowerShell ps{"Bedap"}; + + logger_scope.mock_logger->screen_logs(); + ASSERT_TRUE(ps_helper.ps_write(ps, data)); +} + +TEST_F(PowerShellTest, write_logs_on_failure) +{ + static constexpr auto data = "Nio Esseia"; + ps_helper.setup([](auto* process) { EXPECT_CALL(*process, write(Eq(data))).WillOnce(Return(-1)); }); + + mp::PowerShell ps{"Takver"}; + + auto& logger = *logger_scope.mock_logger; + logger.screen_logs(); + logger.expect_log(mpl::Level::warning, "Failed to send"); + ASSERT_FALSE(ps_helper.ps_write(ps, data)); +} + +TEST_F(PowerShellTest, write_logs_writen_bytes_on_failure) +{ + static constexpr auto data = "Anarres"; + static constexpr auto part = 3; + ps_helper.setup([](auto* process) { EXPECT_CALL(*process, write(Eq(data))).WillOnce(Return(part)); }); + + mp::PowerShell ps{"Palat"}; + + auto& logger = *logger_scope.mock_logger; + logger.screen_logs(); + logger.expect_log(mpl::Level::warning, fmt::format("{} bytes", part)); + ASSERT_FALSE(ps_helper.ps_write(ps, data)); +} + +TEST_F(PowerShellTest, run_writes_and_logs_cmd) +{ + static constexpr auto cmdlet = "some cmd and args"; + auto& logger = *logger_scope.mock_logger; + logger.screen_logs(mpl::Level::error); + logger.expect_log(mpl::Level::debug, cmdlet); + + ps_helper.setup([](auto* process) { + EXPECT_CALL(*process, write(Eq(QByteArray{cmdlet}.append('\n')))) + .WillOnce(Return(-1)); // short-circuit the attempt + }); + + mp::PowerShell ps{"Tirin"}; + ASSERT_FALSE(ps.run(QString{cmdlet}.split(' '))); +} + +struct TestPSStatusAndOutput : public PowerShellTest, public WithParamInterface +{ + QByteArray get_status() + { + return ps_helper.get_status(GetParam()); + } + + QByteArray end_marker() + { + return ps_helper.end_marker(GetParam()); + } + + void expect_writes(mpt::MockProcess* process) + { + return ps_helper.expect_writes(process, cmdlet); + } + + std::pair run() + { + mp::PowerShell ps{"Gvarab"}; + QString output; + QString output_err; + EXPECT_EQ(ps.run(QString{cmdlet}.split(' '), &output, &output_err), GetParam()); + + return {output, output_err}; + } + + inline static constexpr auto cmdlet = "gimme data"; +}; + +TEST_P(TestPSStatusAndOutput, run_returns_cmdlet_status_and_output) +{ + static constexpr auto data = "here's data"; + auto& logger = *logger_scope.mock_logger; + logger.screen_logs(mpl::Level::warning); + logger.expect_log(mpl::Level::debug, fmt::format("{}", GetParam())); + + ps_helper.setup([this](auto* process) { + expect_writes(process); + EXPECT_CALL(*process, read_all_standard_output).WillOnce(Return(QByteArray{data}.append(end_marker()))); + }); + + auto [out, err] = run(); + EXPECT_TRUE(err.isEmpty()); + ASSERT_EQ(out, data); +} + +TEST_P(TestPSStatusAndOutput, run_handles_trickling_output) +{ + static constexpr auto datum1 = "blah"; + static constexpr auto datum2 = "bleh"; + static constexpr auto datum3 = "blih"; + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + + ps_helper.setup([this](auto* process) { + expect_writes(process); + EXPECT_CALL(*process, read_all_standard_output) + .WillOnce(Return("")) + .WillOnce(Return(datum1)) + .WillOnce(Return("")) + .WillOnce(Return(datum2)) + .WillOnce(Return(datum3)) + .WillOnce(Return("")) + .WillOnce(Return("")) + .WillOnce(Return(end_marker())); + }); + + auto [out, err] = run(); + EXPECT_TRUE(err.isEmpty()); + ASSERT_EQ(out, QString{datum1} + datum2 + datum3); +}; + +auto halves(const QString& str) +{ + auto total = str.size(); + auto half = total / 2; + + return std::make_pair(str.left(half).toUtf8(), str.right(total - half).toUtf8()); +}; + +TEST_P(TestPSStatusAndOutput, run_handles_split_end_marker) +{ + static constexpr auto data = "lots of info"; + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + + ps_helper.setup([this](auto* process) { + const auto marker_halves = halves(ps_helper.output_end_marker); + const auto status_halves = halves(get_status()); + + expect_writes(process); + EXPECT_CALL(*process, read_all_standard_output) + .WillOnce(Return(QByteArray{data}.append('\n'))) + .WillOnce(Return(marker_halves.first)) + .WillOnce(Return(marker_halves.second)) + .WillOnce(Return(status_halves.first)) + .WillOnce(Return(status_halves.second)); + }); + + auto [out, err] = run(); + EXPECT_TRUE(err.isEmpty()); + ASSERT_EQ(out, QString{data}); +} + +INSTANTIATE_TEST_SUITE_P(PowerShellTest, TestPSStatusAndOutput, Values(true, false)); + +TEST_F(PowerShellTest, exec_runs_given_cmd) +{ + static constexpr auto cmdlet = "make me a sandwich"; + const auto args = QString{cmdlet}.split(' '); + + auto& logger = *logger_scope.mock_logger; + const auto log_matcher = ContainsRegex(args.join(".*").toStdString()); + logger.screen_logs(mpl::Level::warning); + EXPECT_CALL(logger, log(_, _, log_matcher)); + + ps_helper.setup( + [&args](auto* process) { + EXPECT_EQ(process->arguments(), args); + EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(true)); + }, + /* auto_exit = */ false); + mp::PowerShell::exec(args, "Mitis"); +} + +TEST_F(PowerShellTest, exec_succeeds_when_no_timeout_and_process_successful) +{ + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + ps_helper.setup( + [](auto* process) { + InSequence seq; + EXPECT_CALL(*process, start); + EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(true)); + EXPECT_CALL(*process, process_state).WillOnce(Return(mp::ProcessState{0, std::nullopt})); + }, + /* auto_exit = */ false); + + EXPECT_TRUE(mp::PowerShell::exec({}, "Efor")); +} + +TEST_F(PowerShellTest, exec_fails_when_timeout) +{ + auto& logger = *logger_scope.mock_logger; + logger.screen_logs(mpl::Level::warning); + + static constexpr auto msg = "timeout"; + logger.expect_log(mpl::Level::warning, msg); + + ps_helper.setup( + [](auto* process) { + InSequence seq; + + EXPECT_CALL(*process, start); + EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(false)); + EXPECT_CALL(*process, process_id).WillOnce(Return(123)); + EXPECT_CALL(*process, error_string).WillOnce(Return(msg)); + }, + /* auto_exit = */ false); + + EXPECT_FALSE(mp::PowerShell::exec({}, "Sabul")); +} + +TEST_F(PowerShellTest, exec_fails_when_cmd_returns_bad_exit_code) +{ + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + + ps_helper.setup( + [](auto* process) { + InSequence seq; + + EXPECT_CALL(*process, start); + EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(true)); + EXPECT_CALL(*process, process_state).WillOnce(Return(mp::ProcessState{-1, std::nullopt})); + }, + /* auto_exit = */ false); + + EXPECT_FALSE(mp::PowerShell::exec({}, "Rulag")); +} + +TEST_F(PowerShellTest, exec_returns_cmd_output) +{ + static constexpr auto datum1 = "bloh"; + static constexpr auto datum2 = "bluh"; + const auto cmdlet = QStringList{"sudo", "make", "me", "a", "sandwich"}; + + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + + ps_helper.setup( + [](auto* process) { + InSequence seq; + auto emit_ready_read = [process] { emit process->ready_read_standard_output(); }; + + EXPECT_CALL(*process, start).WillOnce(Invoke(emit_ready_read)); + EXPECT_CALL(*process, read_all_standard_output) + .WillOnce(DoAll(Invoke(emit_ready_read), Return(datum2))) // the invoke needs to be 1st + .WillOnce(Return(datum1)); // which results in the last return happening 1st + EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(true)); + }, + /* auto_exit = */ false); + + QString output; + QString output_err; + mp::PowerShell::exec(cmdlet, "Gimar", &output, &output_err); + EXPECT_TRUE(output_err.isEmpty()); + EXPECT_EQ(output, QString{datum1} + datum2); +} + +TEST_F(PowerShellTest, exec_returns_cmd_error_output) +{ + static constexpr auto msg = "A horrible chill runs down your spine..."; + const auto cmdlet = QStringList{"sudo", "make", "me", "an", "error"}; + + logger_scope.mock_logger->screen_logs(mpl::Level::warning); + logger_scope.mock_logger->expect_log(mpl::Level::warning, "stderr"); + + ps_helper.mock_ps_exec(std::nullopt, msg); + + QString output{}, output_err{}; + mp::PowerShell::exec(cmdlet, "Tiamat", &output, &output_err); + EXPECT_TRUE(output.isEmpty()); + EXPECT_EQ(output_err, msg); +} diff --git a/tests/windows/test_smb_mount_handler.cpp b/tests/windows/test_smb_mount_handler.cpp new file mode 100644 index 0000000000..3d9c7bca20 --- /dev/null +++ b/tests/windows/test_smb_mount_handler.cpp @@ -0,0 +1,529 @@ +/* + * Copyright (C) Canonical, Ltd. + * + * 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; version 3. + * + * 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 . + * + */ + +#include "tests/common.h" +#include "tests/mock_aes.h" +#include "tests/mock_file_ops.h" +#include "tests/mock_logger.h" +#include "tests/mock_platform.h" +#include "tests/mock_server_reader_writer.h" +#include "tests/mock_sftp_client.h" +#include "tests/mock_sftp_utils.h" +#include "tests/mock_ssh_process_exit_status.h" +#include "tests/mock_ssh_test_fixture.h" +#include "tests/mock_utils.h" +#include "tests/mock_virtual_machine.h" +#include "tests/stub_ssh_key_provider.h" +#include "tests/windows/powershell_test_helper.h" + +#include "smb_mount_handler.h" +#include +#include + +#include + +namespace mp = multipass; +namespace mpt = multipass::test; +namespace mpu = multipass::utils; + +using namespace testing; + +namespace +{ + +struct SshCommandOutput +{ + SshCommandOutput(const std::string& output = "", int exit_code = 0) : output{output}, exit_code{exit_code} + { + } + + std::string output; + int exit_code; +}; + +typedef std::unordered_map SshCommandOutputs; + +struct MockSmbManager : public mp::SmbManager +{ + MOCK_METHOD(bool, share_exists, (const QString& share_name), (const, override)); + MOCK_METHOD(void, + create_share, + (const QString& share_name, const QString& source, const QString& user), + (const, override)); + MOCK_METHOD(void, remove_share, (const QString& share_name), (const, override)); +}; + +struct SmbMountHandlerTest : public ::Test +{ + using RunSpec = mpt::PowerShellTestHelper::RunSpec; + + SmbMountHandlerTest() + { + EXPECT_CALL(file_ops, status) + .WillOnce(Return(mp::fs::file_status{mp::fs::file_type::directory, mp::fs::perms::all})); + EXPECT_CALL(utils, make_dir(_, QString{"enc-keys"}, _)).WillOnce(Return("enc-keys")); + EXPECT_CALL(platform, get_username).WillOnce(Return(username)); + ON_CALL(utils, contents_of).WillByDefault(Return("irrelevant")); + ON_CALL(utils, make_file_with_content(_, _)).WillByDefault(Return()); + EXPECT_CALL(utils, make_uuid(std::make_optional(target))).WillOnce(Return(target_uuid)); + EXPECT_CALL(utils, make_uuid(std::make_optional(username.toStdString()))).WillOnce(Return(username_uuid)); + EXPECT_CALL(logger, log).WillRepeatedly(Return()); + logger.expect_log(mpl::Level::info, + fmt::format("Initializing native mount {} => {} in '{}'", source, target, vm.vm_name)); + + MP_DELEGATE_MOCK_CALLS_ON_BASE(utils, run_in_ssh_session, mp::Utils); + } + + // the returned lambda will modify `output` so that it can be used to mock ssh_channel_read_timeout + auto mocked_ssh_channel_request_exec(std::string& output) + { + return [&](ssh_channel, const char* command) { + if (const auto it = ssh_outputs.find(command); it != ssh_outputs.end()) + { + output = it->second.output; + exit_status.set_exit_status(it->second.exit_code); + } + else + { + ADD_FAILURE() << "unexpected command: " << command; + } + + return SSH_OK; + }; + } + + static auto mocked_ssh_channel_read_timeout(const std::string& output) + { + return [&, copied = 0u](auto, void* dest, uint32_t count, auto...) mutable { + auto n = std::min(static_cast(count), output.size() - copied); + std::copy_n(output.begin() + copied, n, static_cast(dest)); + n ? copied += n : copied = 0; + return n; + }; + } + + std::function set_password = [this](mp::MountRequest* request) { + request->set_password(password); + return true; + }; + + mpt::MockSSHTestFixture ssh_test_fixture; + mpt::StubSSHKeyProvider key_provider; + mpt::MockServerReaderWriter server; + mpt::ExitStatusMock exit_status; + + NiceMock vm{"my_instance"}; + std::string source{"source"}, target{"target"}; + QString target_uuid{"d02a0ba3-2170-46ac-9445-1943a0fe82e6"}; + mp::id_mappings gid_mappings{{1, 2}}, uid_mappings{{5, 6}}; + mp::VMMount mount{source, gid_mappings, uid_mappings, mp::VMMount::MountType::Native}; + + mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(mpl::Level::debug); + mpt::MockLogger& logger = *logger_scope.mock_logger; + mpt::MockFileOps::GuardedMock mock_file_ops_guard = mpt::MockFileOps::inject(); + mpt::MockFileOps& file_ops = *mock_file_ops_guard.first; + mpt::MockSFTPUtils::GuardedMock mock_sftp_utils_guard = mpt::MockSFTPUtils::inject(); + mpt::MockSFTPUtils& sftp_utils = *mock_sftp_utils_guard.first; + mpt::MockUtils::GuardedMock mock_utils_guard = mpt::MockUtils::inject(); + mpt::MockUtils& utils = *mock_utils_guard.first; + mpt::MockPlatform::GuardedMock mock_platform_guard = mpt::MockPlatform::inject(); + mpt::MockPlatform& platform = *mock_platform_guard.first; + mpt::MockAES::GuardedMock mock_aes_guard = mpt::MockAES::inject(); + mpt::MockAES& aes = *mock_aes_guard.first; + std::unique_ptr sftp_client = std::make_unique(); + MockSmbManager smb_manager{}; + + QString username{"username"}; + QString username_uuid{"531b4c6f-6090-4b4c-b585-760d18db05e0"}; + std::string password{"password"}; + QString local_cred_dir{"/some/path"}; + std::string remote_cred_file{"/tmp/.smb_credentials"}; + std::string enc_key{"key"}; + std::string smb_share_name = + QString("%1_%2:%3") + .arg(target_uuid, QString::fromStdString(vm.vm_name), QString::fromStdString(target)) + .left(80) + .toStdString(); + + std::string dpkg_command{"dpkg-query --show --showformat='${db:Status-Status}' cifs-utils"}; + std::string install_cifs_command{"sudo apt-get update && sudo apt-get install -y cifs-utils"}; + std::string mkdir_command{"mkdir -p " + target}; + std::string rm_command{"sudo rm " + remote_cred_file}; + std::string umount_command{fmt::format("if mountpoint -q {0}; then sudo umount {0}; else true; fi", target)}; + std::string mount_command{fmt::format("sudo mount -t cifs //{}/{} {} -o credentials={},uid=$(id -u),gid=$(id -g)", + QHostInfo::localHostName(), + smb_share_name, + target, + remote_cred_file)}; + std::string findmnt_command{ + fmt::format("findmnt --type cifs | grep '{} //{}/{}'", target, QHostInfo::localHostName(), smb_share_name)}; + + SshCommandOutputs ssh_outputs{ + {dpkg_command, {"installed"}}, + {install_cifs_command, {}}, + {mkdir_command, {}}, + {rm_command, {}}, + {umount_command, {}}, + {mount_command, {}}, + {findmnt_command, {}}, + }; +}; +} // namespace + +TEST_F(SmbMountHandlerTest, success) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + EXPECT_CALL(*sftp_client, from_cin).WillOnce(Return()); + EXPECT_CALL(sftp_utils, make_SFTPClient).WillOnce(Return(std::move(sftp_client))); + + EXPECT_CALL(smb_manager, share_exists).WillOnce(Return(true)); + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + handler.activate(&server); +} + +TEST_F(SmbMountHandlerTest, generate_key) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(false)); + logger.expect_log(mpl::Level::info, "Successfully generated new encryption key"); + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + EXPECT_CALL(*sftp_client, from_cin).WillOnce(Return()); + EXPECT_CALL(sftp_utils, make_SFTPClient).WillOnce(Return(std::move(sftp_client))); + + EXPECT_CALL(smb_manager, share_exists).WillOnce(Return(true)); + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + handler.activate(&server); +} + +TEST_F(SmbMountHandlerTest, installs_cifs) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + + ssh_outputs[dpkg_command].output = "not installed"; + EXPECT_CALL(server, Write(Property(&mp::MountReply::reply_message, "Enabling support for mounting"), _)) + .WillOnce(Return(true)); + logger.expect_log(mpl::Level::info, fmt::format("Installing cifs-utils in '{}'", vm.vm_name)); + + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + EXPECT_CALL(*sftp_client, from_cin).WillOnce(Return()); + EXPECT_CALL(sftp_utils, make_SFTPClient).WillOnce(Return(std::move(sftp_client))); + + EXPECT_CALL(smb_manager, share_exists).WillOnce(Return(true)); + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + handler.activate(&server); +} + +TEST_F(SmbMountHandlerTest, fail_install_cifs) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + + auto install_error = "error reason"; + ssh_outputs[dpkg_command].output = "not installed"; + ssh_outputs[install_cifs_command] = {install_error, 1}; + EXPECT_CALL(server, Write(Property(&mp::MountReply::reply_message, "Enabling support for mounting"), _)) + .WillOnce(Return(true)); + logger.expect_log(mpl::Level::info, fmt::format("Installing cifs-utils in '{}'", vm.vm_name)); + logger.expect_log(mpl::Level::warning, + fmt::format("Failed to install 'cifs-utils', error message: '{}'", install_error)); + + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + MP_EXPECT_THROW_THAT(handler.activate(&server), + std::runtime_error, + mpt::match_what(StrEq("Failed to install cifs-utils"))); +} + +TEST_F(SmbMountHandlerTest, request_and_receive_creds) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return("")); + + EXPECT_CALL(server, Write(Property(&mp::MountReply::password_requested, true), _)).WillOnce(Return(true)); + EXPECT_CALL(server, Read).WillOnce(set_password); + EXPECT_CALL(aes, encrypt).WillOnce(Return("encrypted")); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + EXPECT_CALL(*sftp_client, from_cin).WillOnce(Return()); + EXPECT_CALL(sftp_utils, make_SFTPClient).WillOnce(Return(std::move(sftp_client))); + + EXPECT_CALL(smb_manager, share_exists).WillOnce(Return(true)); + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + handler.activate(&server); +} + +TEST_F(SmbMountHandlerTest, fail_without_client) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return("")); + + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + MP_EXPECT_THROW_THAT(handler.activate(static_cast(nullptr)), + std::runtime_error, + mpt::match_what(StrEq("Cannot get password without client connection"))); +} + +TEST_F(SmbMountHandlerTest, fail_request_creds) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return("")); + + EXPECT_CALL(server, Write(Property(&mp::MountReply::password_requested, true), _)).WillOnce(Return(false)); + + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + MP_EXPECT_THROW_THAT(handler.activate(&server), + std::runtime_error, + mpt::match_what(StrEq("Cannot request password from client. Aborting..."))); +} + +TEST_F(SmbMountHandlerTest, fail_receive_creds) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return("")); + + EXPECT_CALL(server, Write(Property(&mp::MountReply::password_requested, true), _)).WillOnce(Return(true)); + EXPECT_CALL(server, Read).WillOnce(Return(false)); + + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + MP_EXPECT_THROW_THAT(handler.activate(&server), + std::runtime_error, + mpt::match_what(StrEq("Cannot get password from client. Aborting..."))); +} + +TEST_F(SmbMountHandlerTest, fail_empty_password) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return("")); + + EXPECT_CALL(server, Write(Property(&mp::MountReply::password_requested, true), _)).WillOnce(Return(true)); + password.clear(); + EXPECT_CALL(server, Read).WillOnce(set_password); + + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + MP_EXPECT_THROW_THAT(handler.activate(&server), + std::runtime_error, + mpt::match_what(StrEq("A password is required for SMB mounts."))); +} + +TEST_F(SmbMountHandlerTest, fail_create_smb_share) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + const auto error = fmt::format("failed creating SMB share for \"{}\"", source); + EXPECT_CALL(smb_manager, create_share).WillOnce(Throw(std::runtime_error{error})); + + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + MP_EXPECT_THROW_THAT(handler.activate(&server), std::runtime_error, mpt::match_what(error)); +} + +TEST_F(SmbMountHandlerTest, fail_mkdir_target) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + auto mkdir_error = "error reason"; + ssh_outputs[mkdir_command] = {mkdir_error, 1}; + + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + MP_EXPECT_THROW_THAT( + handler.activate(&server), + std::runtime_error, + mpt::match_what(fmt::format("Cannot create \"{}\" in instance '{}': {}", target, vm.vm_name, mkdir_error))); +} + +TEST_F(SmbMountHandlerTest, fail_mount_command) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + EXPECT_CALL(*sftp_client, from_cin).WillOnce(Return()); + EXPECT_CALL(sftp_utils, make_SFTPClient).WillOnce(Return(std::move(sftp_client))); + + auto mount_error = "error reason"; + ssh_outputs[mount_command] = {mount_error, 1}; + + EXPECT_CALL(file_ops, remove(A())).WillRepeatedly(Return(true)); + + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + MP_EXPECT_THROW_THAT(handler.activate(&server), + std::runtime_error, + mpt::match_what(fmt::format("Error: {}", mount_error))); +} + +TEST_F(SmbMountHandlerTest, fail_remove_creds_file) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + EXPECT_CALL(*sftp_client, from_cin).WillOnce(Return()); + EXPECT_CALL(sftp_utils, make_SFTPClient).WillOnce(Return(std::move(sftp_client))); + + auto rm_error = "error reason"; + ssh_outputs[rm_command] = {rm_error, 1}; + logger.expect_log(mpl::Level::warning, + fmt::format("Failed deleting credentials file in \'{}\': {}", vm.vm_name, rm_error)); + + EXPECT_CALL(smb_manager, share_exists).WillOnce(Return(true)); + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + EXPECT_NO_THROW(handler.activate(&server)); +} + +TEST_F(SmbMountHandlerTest, stop_force_fail_umount_command) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + EXPECT_CALL(*sftp_client, from_cin).WillOnce(Return()); + EXPECT_CALL(sftp_utils, make_SFTPClient).WillOnce(Return(std::move(sftp_client))); + + auto umount_error = "error reason"; + ssh_outputs[umount_command] = {umount_error, 1}; + logger.expect_log( + mpl::Level::warning, + fmt::format("Failed to gracefully stop mount \"{}\" in instance '{}': {}", target, vm.vm_name, umount_error)); + + EXPECT_CALL(smb_manager, share_exists).WillOnce(Return(true)); + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + handler.activate(&server); + EXPECT_NO_THROW(handler.deactivate(/*force=*/true)); +} + +TEST_F(SmbMountHandlerTest, stop_non_force_fail_umount_command) +{ + std::string ssh_command_output; + REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output)); + REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output)); + + EXPECT_CALL(file_ops, exists(A())).WillOnce(Return(true)); + EXPECT_CALL(aes, decrypt).WillOnce(Return(fmt::format("password={}", password))); + + EXPECT_CALL(smb_manager, create_share).WillOnce(Return()); + + EXPECT_CALL(*sftp_client, from_cin).WillOnce(Return()); + EXPECT_CALL(sftp_utils, make_SFTPClient).WillOnce(Return(std::move(sftp_client))); + + auto umount_error = "error reason"; + ssh_outputs[umount_command] = {umount_error, 1}; + + EXPECT_CALL(smb_manager, share_exists).WillRepeatedly(Return(true)); + EXPECT_CALL(smb_manager, remove_share).WillOnce(Return()); + + mp::SmbMountHandler handler{&vm, &key_provider, target, mount, local_cred_dir, smb_manager}; + handler.activate(&server); + MP_EXPECT_THROW_THAT(handler.deactivate(/*force=*/false), std::runtime_error, mpt::match_what(StrEq(umount_error))); +}