[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: stalwartlabs\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: stalwartlabs\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\nlfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry\ncustom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "content": "name: I think I found a bug\ndescription: File a bug report issue\ntitle: \"[bug]: \"\nlabels: [\"bug\"]\nassignees:\n  - mdecimus\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Thanks for taking the time to fill out this bug report! Use this form only for reporting bugs. If you have a question or problem, please use the [Q&A discussion](https://github.com/stalwartlabs/jmap-server/discussions/new?category=q-a).\n  - type: textarea\n    id: what-happened\n    attributes:\n      label: What happened?\n      description: Also tell us, what did you expect to happen?\n      placeholder: Tell us what you see!\n      value: \"A bug happened!\"\n    validations:\n      required: true\n  - type: textarea\n    id: reproduction\n    attributes:\n      label: How can we reproduce the problem?\n      description: Please provide detailed steps for reproducing the problem.\n      placeholder: Tell us how to reproduce the problem!\n      value: \"I can reproduce the problem by doing the following steps:\"\n    validations:\n      required: true\n  - type: dropdown\n    id: version\n    attributes:\n      label: Version\n      description: What version of our software are you running?\n      options:\n        - v0.5.x\n        - v0.4.x\n        - v0.3.0 or lower\n    validations:\n      required: true\n  - type: dropdown\n    id: db\n    attributes:\n      label: What database are you using?\n      options:\n        - RocksDB\n        - FoundationDB\n        - PostgreSQL\n        - mySQL\n        - SQLite\n  - type: dropdown\n    id: blob\n    attributes:\n      label: What blob storage are you using?\n      options:\n        - RocksDB\n        - FoundationDB\n        - PostgreSQL\n        - mySQL\n        - SQLite\n        - Filesystem\n        - S3-compatible\n  - type: dropdown\n    id: directory\n    attributes:\n      label: Where is your directory located?\n      options:\n        - Internal\n        - SQL\n        - LDAP\n  - type: dropdown\n    id: os\n    attributes:\n      label: What operating system are you using?\n      options:\n        - Linux\n        - Docker\n        - MacOS\n        - Windows\n  - type: textarea\n    id: logs\n    attributes:\n      label: Relevant log output\n      description: Please copy and paste any relevant log output, set logging level to `trace` if you can't find any relevant errors in the log.\n      render: shell\n  - type: checkboxes\n    id: terms\n    attributes:\n      label: Code of Conduct\n      description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/stalwartlabs/.github/blob/main/CODE_OF_CONDUCT.md)\n      options:\n        - label: I agree to follow this project's Code of Conduct\n          required: true\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: I have a question or problem\n    url: https://stalw.art/docs/faq\n    about: Read the FAQ\n  - name: I have a question or problem not covered in the FAQ\n    url: https://github.com/stalwartlabs/jmap-server/discussions/new?category=q-a\n    about: Open a Q&A discussion\n  - name: Join Stalwart's Discord\n    url: https://discord.gg/aVQr3jF8jd\n    about: Join our Discord server for help, discussions and release announcements.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.yml",
    "content": "name: I have a feature request\ndescription: File a feature request issue\ntitle: \"[enhancement]: \"\nlabels: [\"enhancement\"]\nassignees:\n  - mdecimus\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Thanks for taking the time to fill out this feature request form! Use this form only for requesting new features. If you have a question or problem, please use the [Q&A discussion](https://github.com/stalwartlabs/jmap-server/discussions/new?category=q-a).\n  - type: textarea\n    id: request\n    attributes:\n      label: Which feature or improvement would you like to request?\n      description: Write a clear and concise description of what you want to happen.\n      placeholder: \"I'd like to see this feature:\"\n      value: \"I'd like to see this feature:\"\n    validations:\n      required: true\n\n  - type: textarea\n    id: problem-related\n    attributes:\n      label: Is your feature request related to a problem?\n      description: Write a clear and concise description of what the problem is.\n      placeholder: Tell us what the problem is!\n      value: \"I'm always frustrated when...\"\n  - type: checkboxes\n    id: terms\n    attributes:\n      label: Code of Conduct\n      description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/stalwartlabs/.github/blob/main/CODE_OF_CONDUCT.md)\n      options:\n        - label: I agree to follow this project's Code of Conduct\n          required: true\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: Build\n\non:\n  workflow_dispatch:\n  pull_request:\n  push:\n    tags:\n      - \"v*.*.*\"\n\nenv:\n  REGISTRY_IMAGE: stalwartlabs/jmap-server\n\njobs:\n  build:\n    name: Building for ${{ matrix.target }} on ${{ matrix.host_os }}\n    runs-on: ${{ matrix.host_os }}\n    if: '!cancelled()'\n    strategy: \n      matrix:\n        include:\n          - target: x86_64-unknown-linux-gnu\n            host_os: ubuntu-20.04\n          - target: x86_64-apple-darwin\n            host_os: macos-latest\n          - target: x86_64-pc-windows-msvc\n            host_os: windows-2022\n          #- target: aarch64-unknown-linux-gnu\n          #  host_os: ubuntu-20.04\n          #- target: x86_64-unknown-linux-musl\n          #  host_os: ubuntu-20.04\n          #- target: aarch64-unknown-linux-musl\n          #  host_os: ubuntu-20.04\n          #- target: aarch64-apple-darwin\n          #  host_os: macos-latest\n          #- target: aarch64-pc-windows-msvc\n          #  host_os: windows-2022\n          #- target: aarch64-pc-windows-msvc\n          #  host_os: windows-2022\n          #- target: arm-unknown-linux-musleabihf\n          #  host_os: ubuntu-20.04\n          #- target: arm-unknown-linux-gnueabihf\n          #  host_os: ubuntu-20.04\n          #- target: armv7-unknown-linux-musleabihf\n          #  host_os: ubuntu-20.04\n          #- target: armv7-unknown-linux-gnueabihf\n          #  host_os: ubuntu-20.04\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v2\n        with:\n          persist-credentials: false\n          submodules: recursive\n\n      - name: Install dependencies (Linux)\n        if: ${{ contains(matrix.host_os, 'ubuntu') }}\n        run: |\n          sudo apt-get update -y\n          sudo apt-get install -yq protobuf-compiler wget\n          wget https://github.com/apple/foundationdb/releases/download/7.1.0/foundationdb-clients_7.1.0-1_amd64.deb\n          sudo dpkg -i --force-architecture foundationdb-clients_7.1.0-1_amd64.deb\n\n      - name: Install dependencies (MacOs)\n        if: ${{ contains(matrix.host_os, 'macos') }}\n        run: |\n          brew install protobuf\n          brew install wget\n          wget https://github.com/apple/foundationdb/releases/download/7.1.32/FoundationDB-7.1.32_x86_64.pkg\n          sudo installer -allowUntrusted -dumplog -pkg FoundationDB-7.1.32_x86_64.pkg -target /\n\n      - name: Install dependencies (Windows)\n        if: ${{ contains(matrix.host_os, 'windows') }}\n        uses: arduino/setup-protoc@v1\n\n      - name: Install Rust\n        uses: actions-rs/toolchain@v1\n        with:\n          override: true\n          target: ${{ matrix.target }}\n          toolchain: stable\n          \n      - name: Rust Cache\n        uses: Swatinem/rust-cache@v2\n        with:\n          key: ${{ matrix.host_os }}-${{ matrix.target }}-jmap          \n\n      - name: Building binary (Unix version)\n        if: ${{ !contains(matrix.host_os, 'windows') }}\n        run: |\n          cargo build --target=${{ matrix.target }} --no-default-features --features foundationdb --release\n          cd target/${{ matrix.target }}/release && tar czvf ../../../stalwart-jmap-foundationdb-${{ matrix.target }}.tar.gz stalwart-jmap && cd -\n          cargo build --target=${{ matrix.target }} --release\n          cd target/${{ matrix.target }}/release && tar czvf ../../../stalwart-jmap-${{ matrix.target }}.tar.gz stalwart-jmap && cd -\n\n      - name: Building binary (Windows version)\n        if: ${{ contains(matrix.host_os, 'windows') }}\n        run: |\n          cargo build --target=${{ matrix.target }} --release\n          cd target/${{ matrix.target }}/release\n          7z a ../../../stalwart-jmap-${{ matrix.target }}.zip stalwart-jmap.exe\n          cd -\n\n      - name: Publish Release\n        if: startsWith(github.ref, 'refs/tags/')\n        uses: softprops/action-gh-release@v1\n        with:\n            files: 'stalwart-*'\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n  cross_build:\n    runs-on: ubuntu-latest\n    name: Building for ${{ matrix.target }} on ${{ matrix.distro }}\n    if: '!cancelled()'\n\n    strategy:\n      matrix:\n        include:\n          - arch: aarch64\n            distro: ubuntu20.04\n            target: aarch64-unknown-linux-gnu\n    steps:\n      - uses: actions/checkout@v3\n        with:\n          submodules: recursive\n\n      - uses: uraimo/run-on-arch-action@v2\n        name: Build artifact\n        id: build\n        with:\n          arch: ${{ matrix.arch }}\n          distro: ${{ matrix.distro }}\n\n          # Not required, but speeds up builds\n          githubToken: ${{ github.token }}\n\n          # Create an artifacts directory\n          setup: |\n            mkdir -p \"${PWD}/artifacts\"\n\n          # Mount the artifacts directory as /artifacts in the container\n          dockerRunArgs: |\n            --volume \"${PWD}/artifacts:/artifacts\"\n\n          # Pass some environment variables to the container\n          env: | \n            target: ${{ matrix.target }}\n\n          # The shell to run commands with in the container\n          shell: /bin/sh\n\n          install: |\n            apt-get update -yq\n            apt-get install -yq build-essential cmake protobuf-compiler wget curl\n            curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal\n\n          run: |\n            export PATH=\"$HOME/.cargo/bin:$PATH\"\n            cargo build --target=${target} --release\n            cd target/${target}/release\n            tar czvf /artifacts/stalwart-jmap-${target}.tar.gz stalwart-jmap\n            cd -\n\n      - name: Move packages\n        run: |\n          mv ${PWD}/artifacts/* .\n\n      - name: Publish Release\n        if: startsWith(github.ref, 'refs/tags/')\n        uses: softprops/action-gh-release@v1\n        with:\n            files: 'stalwart-*'\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n  build_docker:\n    needs:\n      - build\n      - cross_build\n    name: Build Docker image for ${{ matrix.platform }}\n    runs-on: ubuntu-latest\n    if: '!cancelled()'\n    strategy:\n      fail-fast: false\n      matrix:\n        platform:\n          - linux/amd64\n          - linux/arm64\n    steps:\n      -\n        name: Prepare\n        run: |\n          platform=${{ matrix.platform }}\n          echo \"PLATFORM_PAIR=${platform//\\//-}\" >> $GITHUB_ENV\n      -\n        name: Checkout\n        uses: actions/checkout@v3\n        with:\n          submodules: recursive\n      -\n        name: Docker meta\n        id: meta\n        uses: docker/metadata-action@v4\n        with:\n          images: ${{ env.REGISTRY_IMAGE }}\n          tags: |\n            type=schedule\n            type=ref,event=branch\n            type=ref,event=pr\n            type=semver,pattern={{version}}\n            type=semver,pattern={{major}}.{{minor}}\n            type=semver,pattern={{major}}\n            type=sha\n      -\n        name: Set up QEMU\n        uses: docker/setup-qemu-action@v2\n      -\n        name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v2\n      -\n        name: Login to Docker Hub\n        uses: docker/login-action@v2\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n      -\n        name: Build and push by digest\n        id: build\n        uses: docker/build-push-action@v4\n        with:\n          context: .\n          platforms: ${{ matrix.platform }}\n          labels: ${{ steps.meta.outputs.labels }}\n          outputs: type=image,name=${{ env.REGISTRY_IMAGE }},push-by-digest=true,name-canonical=true,push=true\n          #cache-from: type=registry,ref=${{ env.REGISTRY_IMAGE }}:buildcache-${{ env.PLATFORM_PAIR }}\n          #cache-to: type=registry,ref=s${{ env.REGISTRY_IMAGE }}:buildcache-${{ env.PLATFORM_PAIR }},mode=max\n          cache-from: type=gha,scope=build-${{ env.PLATFORM_PAIR }}\n          cache-to: type=gha,scope=build-${{ env.PLATFORM_PAIR }}\n      -\n        name: Export digest\n        run: |\n          mkdir -p /tmp/digests\n          digest=\"${{ steps.build.outputs.digest }}\"\n          touch \"/tmp/digests/${digest#sha256:}\"\n      -\n        name: Upload digest\n        uses: actions/upload-artifact@v3\n        with:\n          name: digests\n          path: /tmp/digests/*\n          if-no-files-found: error\n          retention-days: 1\n  \n  merge_docker:\n    name: Merge and push Docker manifest\n    runs-on: ubuntu-latest\n    needs:\n      - build_docker\n    steps:\n      -\n        name: Download digests\n        uses: actions/download-artifact@v3\n        with:\n          name: digests\n          path: /tmp/digests\n      -\n        name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v2\n      -\n        name: Docker meta\n        id: meta\n        uses: docker/metadata-action@v4\n        with:\n          images: ${{ env.REGISTRY_IMAGE }}\n      -\n        name: Login to Docker Hub\n        uses: docker/login-action@v2\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n      -\n        name: Create manifest list and push\n        working-directory: /tmp/digests\n        run: |\n          docker buildx imagetools create $(jq -cr '.tags | map(\"-t \" + .) | join(\" \")' <<< \"$DOCKER_METADATA_OUTPUT_JSON\") \\\n            $(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *)\n      -\n        name: Inspect image\n        run: |\n          docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.meta.outputs.version }}\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\n/stalwart-jmap\n_ignore\n.cargo\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"main\"]\n\tpath = main\n\turl = https://github.com/stalwartlabs/mail-server\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change Log\n\nAll notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).\n\n## [0.6.0] - 2024-02-14\n\nThis version introduces breaking changes in the configuration file. Please read the [UPGRADING.md](UPGRADING.md) file for more information on how to upgrade from previous versions.\n\n## Added\n- Distributed and fault-tolerant SMTP message queues.\n- Distributed rate-limiting and fail2ban.\n- Expressions in configuration files.\n\n### Changed\n\n### Fixed\n- Do not include `STATUS` in IMAP `NOOP` responses (#234).\n- Allow multiple SMTP `HELO` commands.\n- Redirect OAuth using a `301` instead of a `307` code.\n\n## [0.5.0] - 2023-12-27\n\nThis version requires a database migration and introduces breaking changes in the configuration file. Please read the [UPGRADING.md](https://github.com/stalwartlabs/mail-server/blob/main/UPGRADING.md) file for more information.\n\n## Added\n- Performance enhancements:\n  - Messages are parsed only once and their offsets stored in the database, which avoids having to parse them on every `FETCH` request.\n  - Background full-text indexing.\n  - Optimization of database access functions.\n- Storage layer improvements:\n  - In addition to `FoundationDB` and `SQLite`, now it is also possible to use `RocksDB`, `PostgreSQL` and `mySQL` as a storage backend.\n  - Blobs can now be stored in any of the supported data stores, it is no longer limited to the file system or S3/MinIO. \n  - Full-text searching con now be done internally or delegated to `ElasticSearch`.\n  - Spam databases can now be stored in any of the supported data stores or `Redis`. It is no longer necessary to have an SQL server to use the spam filter.\n- Internal directory: \n  - User account, groups and mailing lists can now be managed directly from Stalwart without the need of an external LDAP or SQL directory.\n  - HTTP API to manage users, groups, domains and mailing lists.\n- LDAP bind authentication, to support some LDAP servers such as `lldap` which do not expose the userPassword attribute.\n- Messages marked a spam by the spam filter can now be automatically moved to the account's `Junk Mail` folder.\n- Automatic creation of JMAP identities.\n\n### Changed\n\n### Fixed\n- Spamhaus DNSBL return codes.\n- CLI tool reports authentication errors rather than a parsing error.\n\n## [0.4.0] - 2023-10-25\n\nThis version introduces some breaking changes in the configuration file. Please read the [UPGRADING.md](UPGRADING.md) file for more information.\n\n## Added\n- Built-in Spam and Phishing filter.\n- Scheduled queries on some directory types.\n- In-memory maps and lists containing glob or regex patterns.\n- Remote retrieval of in-memory list/maps with fallback mechanisms.\n- Macros and support for including files from TOML config files.\n\n### Changed\n- `config.toml` is now split in multiple TOML files for better organization.\n- **BREAKING:** Configuration key prefix `jmap.sieve` (JMAP Sieve Interpreter) has been renamed to `sieve.untrusted`.\n- **BREAKING:** Configuration key prefix `sieve` (SMTP Sieve Interpreter) has been renamed to `sieve.trusted`.\n\n### Fixed\n\n## [0.3.8] - 2023-09-19\n\n## Added\n- Journal logging support\n\n### Changed\n- Replaced `rpgp` with `sequoia-pgp` due to rpgp bug.\n\n### Fixed\n\n## [0.3.7] - 2023-09-05\n\n## Added\n- Option to allow unencrypted SMTP AUTH (#72)\n- Support for `rcpt-domain` key in `rcpt.relay` SMTP rule evaluation.\n\n### Changed\n \n### Fixed\n- SMTP strategy `Ipv6thenIpv4` returns only IPv6 addresses (#70)\n- Milter `DATA` command is sent after headers which causes ClamAV to hang.\n- Sieve `redirect` of unmodified messages does not work.\n\n## [0.3.6] - 2023-08-29\n\n## Added\n- Arithmetic and logical expression evaluation in Sieve scripts.\n- Support for storing query results in Sieve variables.\n- Results of SPF, DKIM, ARC, DMARC and IPREV checks available as environment variables in Sieve scripts.\n- Configurable protocol flags for Milter filters.\n- Fall-back to plain text when `STARTTLS` fails and `starttls` is set to `optional`.\n\n### Changed\n \n### Fixed\n- Do not panic when `hash = 0` in reports. (#60)\n- JMAP Session resource returns `EmailSubmission` capabilities using arrays rather than objects.\n- ManageSieve `PUTSCRIPT` should replace existing scripts.\n\n## [0.3.5] - 2023-08-18\n\n## Added\n- TCP listener option `nodelay`.\n \n### Changed\n \n### Fixed\n- SMTP: Allow disabling `STARTTLS`.\n- JMAP: Support for `OPTIONS` HTTP method.\n\n## [0.3.4] - 2023-08-09\n\n## Added\n- JMAP: Support for setting custom HTTP response headers (#52)\n \n### Changed\n \n### Fixed\n- JMAP/IMAP: Successful authentication requests should not count when rate limiting\n- IMAP: Case insensitive Inbox selection\n- IMAP: Automatically create Inbox for group accounts\n\n## [0.3.3] - 2023-08-02\n\n### Added\n- Encryption at rest with **S/MIME** or **OpenPGP**.\n- Support for referencing context variables from dynamic values.\n \n### Changed\n \n### Fixed\n- Support for PKCS8v1 ED25519 keys (#20).\n- Automatic retry for import/export blob downloads (#14)\n\n## [0.3.2] - 2023-07-28\n\n### Added\n- Sender and recipient address rewriting using regular expressions and sieve scripts.\n- Subaddressing and catch-all addresses using regular expressions (#10).\n- Dynamic variables in SMTP rules.\n \n### Changed\n- Added CLI to Docker container (#19).\n \n### Fixed\n- Workaround for a bug in `sqlx` that caused SQL time-outs (#15).\n- Support for ED25519 certificates in PEM files (#20). \n- Better handling of concurrent IMAP UID map modifications (#17).\n- LDAP domain lookups from SMTP rules.\n\n## [0.3.1] - 2023-07-22\n\n### Added\n- Milter filter support.\n- Match IP address type using /0 mask (#16).\n \n### Changed\n \n### Fixed\n- Support for OpenLDAP password hashing schemes between curly brackets (#8). \n- Add CA certificates to Docker runtime (#5).\n\n## [0.3.0] - 2023-07-16\n\n### Added\n- **LDAP** and **SQL** authentication.\n- **subaddressing** and **catch-all** addresses.\n- **S3-compatible** storage.\n\n### Changed\n- Merged the `stalwart-jmap`, `stalwart-imap` and `stalwart-smtp` repositories into\n  `stalwart-mail`.\n- Removed clustering module and replaced it with a **FoundationDB** backend option.\n- Integrated Stalwart SMTP into Stalwart JMAP.\n- Rewritten JMAP protocol parser.\n- Rewritten store backend.\n- Rewritten IMAP server to have direct access to the message store (no more IMAP proxy).\n- Replaced `actix` with `hyper`.\n \n### Fixed\n\n## [0.2.0] - 2022-10-31\n\n### Added\n- JMAP for Sieve support.\n\n### Changed\n \n### Fixed\n- Faster parsing of e-mail messages.\n\n## [0.1.0] - 2022-09-17\n\nInitial release.\n\n"
  },
  {
    "path": "CNAME",
    "content": "jmap.stalw.art"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nWhen contributing to this repository, please first discuss the change you wish to make via issue,\nemail, or any other method with the owners of this repository before making a change. \n\nPlease note we have a code of conduct, please follow it in all your interactions with the project.\n\n## Any contributions you make will be under AGPL\n\nThis software is licensed under the Affero General Public License (AGPL). Any contributions made to \nthis project will be under this license. Before any contributions can be made, contributors are \nrequired to sign a Contributor License Agreement (CLA). The purpose of the agreement is to clarify \nand document the rights granted by contributors to us.\n\n## Pull Request Process\n\n1. Ensure any install or build dependencies are removed before the end of the layer when doing a \n   build.\n2. Update the README.md with details of changes to the interface, this includes new environment \n   variables, exposed ports, useful file locations and container parameters.\n3. Increase the version numbers in any examples files and the README.md to the new version that this\n   Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).\n4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you \n   do not have permission to do that, you may request the second reviewer to merge it for you.\n\n## Code of Conduct\n\nWe as members, contributors, and leaders pledge to make participation in our community a harassment-free \nexperience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex \ncharacteristics, gender identity and expression, level of experience, education, socio-economic status, \nnationality, personal appearance, race, religion, or sexual identity and orientation.\nWe pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, \nand healthy community.\n\nYou can read the full Code of Conduct [here](https://github.com/stalwartlabs/.github/blob/main/CODE_OF_CONDUCT.md).\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"stalwart-jmap\"\ndescription = \"Stalwart JMAP Server\"\nauthors = [ \"Stalwart Labs Ltd. <hello@stalw.art>\"]\nrepository = \"https://github.com/stalwartlabs/jmap-server\"\nhomepage = \"https://stalw.art/jmap\"\nkeywords = [\"jmap\", \"email\", \"mail\", \"server\"]\ncategories = [\"email\"]\nlicense = \"AGPL-3.0-only\"\nversion = \"0.6.0\"\nedition = \"2021\"\nresolver = \"2\"\n\n[[bin]]\nname = \"stalwart-jmap\"\npath = \"src/main.rs\"\n\n[dependencies]\nstore = { path = \"main/crates/store\" }\njmap = { path = \"main/crates/jmap\" }\njmap_proto = { path = \"main/crates/jmap-proto\" }\nsmtp = { path = \"main/crates/smtp\", features = [\"local_delivery\"] }\ndirectory = { path = \"main/crates/directory\" }\nutils = { path = \"main/crates/utils\" }\ntokio = { version = \"1.23\", features = [\"full\"] }\ntracing = \"0.1\"\n\n[target.'cfg(not(target_env = \"msvc\"))'.dependencies]\njemallocator = \"0.5.0\"\n\n[features]\n#default = [\"sqlite\", \"foundationdb\", \"postgres\", \"mysql\", \"rocks\", \"elastic\", \"s3\", \"redis\"]\ndefault = [\"sqlite\", \"postgres\", \"mysql\", \"rocks\", \"elastic\", \"s3\", \"redis\"]\nsqlite = [\"store/sqlite\"]\nfoundationdb = [\"store/foundation\"]\npostgres = [\"store/postgres\"]\nmysql = [\"store/mysql\"]\nrocks = [\"store/rocks\"]\nelastic = [\"store/elastic\"]\ns3 = [\"store/s3\"]\nredis = [\"store/redis\"]\ntest_mode = []\n\n[workspace]\nmembers = [\n    \"main/crates/jmap\",\n    \"main/crates/jmap-proto\",\n    \"main/crates/smtp\",\n    \"main/crates/store\",\n    \"main/crates/directory\",\n    \"main/crates/utils\",\n    \"main/crates/install\",\n    \"main/tests\",\n]\n\n[profile.dev]\nopt-level = 0\ndebug = 1\ncodegen-units = 4\nlto = false\nincremental = true\npanic = 'unwind'\ndebug-assertions = true\noverflow-checks = false\nrpath = false\n\n[profile.release]\nopt-level = 3\ndebug = false\ncodegen-units = 1\nlto = true\nincremental = false\npanic = 'unwind'\ndebug-assertions = false\noverflow-checks = false\nrpath = false\n#strip = true\n\n[profile.test]\nopt-level = 0\ndebug = 1\n#codegen-units = 16\nlto = false\nincremental = true\ndebug-assertions = true\noverflow-checks = true\nrpath = false\n\n[profile.bench]\nopt-level = 3\ndebug = false\ncodegen-units = 1\nlto = true\nincremental = false\ndebug-assertions = false\noverflow-checks = false\nrpath = false\n\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM debian:bullseye-slim \n\nRUN apt-get update -y && apt-get install -yq ca-certificates curl\n\nCOPY main/resources/docker/configure.sh /usr/local/bin/configure.sh\nCOPY main/resources/docker/entrypoint.sh /usr/local/bin/entrypoint.sh\n\nRUN sed -i -e 's/__C__/jmap/g' /usr/local/bin/configure.sh && \\\n    sed -i -e 's/__R__/jmap-server/g' /usr/local/bin/configure.sh && \\\n    sed -i -e 's/__N__/jmap/g' /usr/local/bin/configure.sh && \\\n    sed -i -e 's/__B__/stalwart-jmap/g' /usr/local/bin/entrypoint.sh\n\nRUN chmod a+rx /usr/local/bin/*.sh\n\nRUN /usr/local/bin/configure.sh --download\n\nRUN useradd stalwart-mail -s /sbin/nologin -M\nRUN mkdir -p /opt/stalwart-mail\nRUN chown stalwart-mail:stalwart-mail /opt/stalwart-mail\n\nVOLUME [ \"/opt/stalwart-mail\" ]\n\nEXPOSE\t8080 25 587 465 143 993 4190\n\nENTRYPOINT [\"/bin/sh\", \"/usr/local/bin/entrypoint.sh\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "# ⚠️ Repository Archived ⚠️\n\n**This repository has been archived and is no longer maintained.**\n\nDevelopment for the JMAP server has been moved to the [Stalwart Mail Server repository](https://github.com/stalwartlabs/mail-server), where ongoing updates and improvements will take place.\n\nThank you for your interest and contributions!\n\n--- \n\n**Stalwart JMAP** is an open-source JSON Meta Application Protocol server designed to be secure, fast, robust and scalable.\nJMAP is a modern protocol for synchronising data such as mail, calendars, or contacts that makes much more efficient use of network resources.\n\nKey features:\n\n- **JMAP** full compliance:\n  - JMAP Core ([RFC 8620](https://datatracker.ietf.org/doc/html/rfc8620))\n  - JMAP Mail ([RFC 8621](https://datatracker.ietf.org/doc/html/rfc8621))\n  - JMAP over WebSocket ([RFC 8887](https://datatracker.ietf.org/doc/html/rfc8887))\n  - JMAP for Sieve Scripts ([DRAFT-SIEVE-13](https://www.ietf.org/archive/id/draft-ietf-jmap-sieve-13.html)).\n- **Flexible and scalable**:\n  - Pluggable storage backends with **RocksDB**, **FoundationDB**, **PostgreSQL**, **mySQL**, **SQLite**, **S3-Compatible**, **Redis** and **ElasticSearch** support.\n  - **Internal**, **LDAP** and **SQL** database authentication.\n  - Built-in [SMTP](https://github.com/stalwartlabs/smtp-server) server for local delivery and JMAP Email Submissions.\n  - Full-text search available in 17 languages.\n  - Disk quotas.\n  - Sieve scripting language with support for all [registered extensions](https://www.iana.org/assignments/sieve-extensions/sieve-extensions.xhtml).\n  - Email aliases, mailing lists, subaddressing and catch-all addresses support.\n  - Integration with **OpenTelemetry** to enable monitoring, tracing, and performance analysis.\n- **Secure and robust**:\n  - Encryption at rest with **S/MIME** or **OpenPGP**.\n  - Built-in Spam and Phishing filter.\n  - OAuth 2.0 [authorization code](https://www.rfc-editor.org/rfc/rfc8628) and [device authorization](https://www.rfc-editor.org/rfc/rfc8628) flows.\n  - Access Control Lists (ACLs).\n  - Rate limiting.\n - Memory safe (thanks to Rust).\n\n## Get Started\n\nInstall Stalwart JMAP Server on your server by following the instructions for your platform:\n\n- [Linux / MacOS](https://stalw.art/docs/install/linux)\n- [Windows](https://stalw.art/docs/install/windows)\n- [Docker](https://stalw.art/docs/install/docker)\n\nAll documentation is available at [stalw.art/docs/get-started](https://stalw.art/docs/get-started).\n\n> **Note**\n> If you need a more comprehensive solution that includes support for IMAP (Internet Message Access Protocol), you should consider installing the [Stalwart Mail Server](https://github.com/stalwartlabs/mail-server) instead.\n\n## Support\n\nIf you are having problems running Stalwart JMAP, you found a bug or just have a question,\ndo not hesitate to reach us on [Github Discussions](https://github.com/stalwartlabs/jmap-server/discussions),\n[Reddit](https://www.reddit.com/r/stalwartlabs) or [Discord](https://discord.gg/jtgtCNj66U).\nAdditionally you may become a sponsor to obtain priority support from Stalwart Labs Ltd.\n\n## Funding\n\nPart of the development of this project was funded through the [NGI0 Entrust Fund](https://nlnet.nl/entrust), a fund established by [NLnet](https://nlnet.nl/) with financial support from the European Commission's [Next Generation Internet](https://ngi.eu/) programme, under the aegis of DG Communications Networks, Content and Technology under grant agreement No 101069594.\n\nIf you find the project useful you can help by [becoming a sponsor](https://liberapay.com/stalwartlabs). Thank you!\n\n## License\n\nLicensed under the terms of the [GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.en.html) as published by\nthe Free Software Foundation, either version 3 of the License, or (at your option) any later version.\nSee [LICENSE](LICENSE) for more details.\n\nYou can be released from the requirements of the AGPLv3 license by purchasing\na commercial license. Please contact licensing@stalw.art for more details.\n  \n## Copyright\n\nCopyright (C) 2023, Stalwart Labs Ltd.\n"
  },
  {
    "path": "src/main.rs",
    "content": "/*\n * Copyright (c) 2023 Stalwart Labs Ltd.\n *\n * This file is part of the Stalwart JMAP Server.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n * in the LICENSE file at the top-level directory of this distribution.\n * You should have received a copy of the GNU Affero General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * You can be released from the requirements of the AGPLv3 license by\n * purchasing a commercial license. Please contact licensing@stalw.art\n * for more details.\n*/\n\nuse std::time::Duration;\n\nuse directory::core::config::ConfigDirectory;\nuse jmap::{api::JmapSessionManager, services::IPC_CHANNEL_BUFFER, JMAP};\nuse smtp::core::{SmtpSessionManager, SMTP};\nuse store::config::ConfigStore;\nuse tokio::sync::mpsc;\nuse utils::{\n    config::{Config, ServerProtocol},\n    enable_tracing, wait_for_shutdown, UnwrapFailure,\n};\n\n#[cfg(not(target_env = \"msvc\"))]\nuse jemallocator::Jemalloc;\n\n#[cfg(not(target_env = \"msvc\"))]\n#[global_allocator]\nstatic GLOBAL: Jemalloc = Jemalloc;\n\n#[tokio::main]\nasync fn main() -> std::io::Result<()> {\n    let mut config = Config::init();\n    // Enable tracing\n    let _tracer = enable_tracing(\n        &config,\n        &format!(\n            \"Starting Stalwart JMAP Server v{}...\",\n            env!(\"CARGO_PKG_VERSION\"),\n        ),\n    )\n    .failed(\"Failed to enable tracing\");\n\n    // Bind ports and drop privileges\n    let mut servers = config.parse_servers().failed(\"Invalid configuration\");\n    servers.bind(&config);\n\n    // Parse stores\n    let stores = config.parse_stores().await.failed(\"Invalid configuration\");\n    let data_store = stores\n        .get_store(&config, \"storage.data\")\n        .failed(\"Invalid configuration\");\n\n    // Update configuration\n    config.update(data_store.config_list(\"\").await.failed(\"Storage error\"));\n\n    // Parse directories\n    let directory = config\n        .parse_directory(&stores, data_store)\n        .await\n        .failed(\"Invalid configuration\");\n    let schedulers = config\n        .parse_purge_schedules(\n            &stores,\n            config.value(\"storage.data\"),\n            config.value(\"storage.blob\"),\n        )\n        .await\n        .failed(\"Invalid configuration\");\n\n    // Init servers\n    let (delivery_tx, delivery_rx) = mpsc::channel(IPC_CHANNEL_BUFFER);\n    let smtp = SMTP::init(&config, &servers, &stores, &directory, delivery_tx)\n        .await\n        .failed(\"Invalid configuration file\");\n    let jmap = JMAP::init(\n        &config,\n        &stores,\n        &directory,\n        &mut servers,\n        delivery_rx,\n        smtp.clone(),\n    )\n    .await\n    .failed(\"Invalid configuration file\");\n\n    // Spawn servers\n    let (shutdown_tx, shutdown_rx) = servers.spawn(|server, shutdown_rx| {\n        match &server.protocol {\n            ServerProtocol::Smtp | ServerProtocol::Lmtp => {\n                server.spawn(SmtpSessionManager::new(smtp.clone()), shutdown_rx)\n            }\n            ServerProtocol::Http => {\n                tracing::debug!(\"Ignoring HTTP server listener, using JMAP port instead.\");\n            }\n            ServerProtocol::Jmap => {\n                server.spawn(JmapSessionManager::new(jmap.clone()), shutdown_rx)\n            }\n            ServerProtocol::Imap => {\n                tracing::debug!(\n                    \"Ignoring IMAP server listener, not supported by JMAP-only release.\"\n                );\n            }\n            ServerProtocol::ManageSieve => {\n                tracing::debug!(\n                    \"Ignoring ManageSieve server listener, not supported by JMAP-only release.\"\n                );\n            }\n        };\n    });\n\n    // Spawn purge schedulers\n    for scheduler in schedulers {\n        scheduler.spawn(shutdown_rx.clone());\n    }\n\n    // Wait for shutdown signal\n    wait_for_shutdown(&format!(\n        \"Shutting down Stalwart JMAP Server v{}...\",\n        env!(\"CARGO_PKG_VERSION\")\n    ))\n    .await;\n\n    // Stop services\n    let _ = shutdown_tx.send(true);\n\n    // Wait for services to finish\n    tokio::time::sleep(Duration::from_secs(1)).await;\n\n    Ok(())\n}\n"
  }
]