Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
system:homeautomation:home-assistant
python-zeroconf
python-zeroconf-0.132.2.obscpio
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File python-zeroconf-0.132.2.obscpio of Package python-zeroconf
07070100000000000081A40000000000000000000000016619D4CC0000005C000000000000000000000000000000000000002400000000python-zeroconf-0.132.2/.coveragerc[report] exclude_lines = pragma: no cover if TYPE_CHECKING: if sys.version_info 07070100000001000081A40000000000000000000000016619D4CC00000043000000000000000000000000000000000000002000000000python-zeroconf-0.132.2/.flake8[flake8] exclude = docs max-line-length = 180 extend-ignore = E203 07070100000002000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002000000000python-zeroconf-0.132.2/.github07070100000003000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002A00000000python-zeroconf-0.132.2/.github/workflows07070100000004000081A40000000000000000000000016619D4CC000014E3000000000000000000000000000000000000003100000000python-zeroconf-0.132.2/.github/workflows/ci.ymlname: CI on: push: branches: - master pull_request: concurrency: group: ${{ github.head_ref || github.run_id }} cancel-in-progress: true jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v3 with: python-version: "3.9" - uses: pre-commit/action@v2.0.3 # Make sure commit messages follow the conventional commits convention: # https://www.conventionalcommits.org commitlint: name: Lint Commit Messages runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - uses: wagoid/commitlint-github-action@v5 test: strategy: fail-fast: false matrix: python-version: - "3.8" - "3.9" - "3.10" - "3.11" - "3.12" - "pypy-3.8" - "pypy-3.9" os: - ubuntu-latest - macos-latest - windows-latest extension: - "skip_cython" - "use_cython" exclude: - os: macos-latest extension: use_cython - os: windows-latest extension: use_cython - os: windows-latest python-version: "pypy-3.8" - os: windows-latest python-version: "pypy-3.9" - os: macos-latest python-version: "pypy-3.8" - os: macos-latest python-version: "pypy-3.9" runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - name: Install poetry run: pipx install poetry - name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} cache: "poetry" - name: Install Dependencies no cython if: ${{ matrix.extension == 'skip_cython' }} env: SKIP_CYTHON: 1 run: poetry install --only=main,dev - name: Install Dependencies with cython if: ${{ matrix.extension != 'skip_cython' }} env: REQUIRE_CYTHON: 1 run: poetry install --only=main,dev - name: Test with Pytest run: poetry run pytest --durations=20 --timeout=60 -v --cov=zeroconf --cov-branch --cov-report xml --cov-report html --cov-report term-missing tests - name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: token: ${{ secrets.CODECOV_TOKEN }} release: runs-on: ubuntu-latest environment: release if: github.ref == 'refs/heads/master' needs: - test - lint - commitlint steps: - uses: actions/checkout@v3 with: fetch-depth: 0 # Run semantic release: # - Update CHANGELOG.md # - Update version in code # - Create git tag # - Create GitHub release # - Publish to PyPI - name: Python Semantic Release uses: relekang/python-semantic-release@v7.34.6 # env: # REPOSITORY_URL: https://test.pypi.org/legacy/ # TWINE_REPOSITORY_URL: https://test.pypi.org/legacy/ with: github_token: ${{ secrets.GITHUB_TOKEN }} pypi_token: ${{ secrets.PYPI_TOKEN }} build_wheels: needs: [release] name: Build wheels on ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-20.04, windows-2019, macOS-11] steps: - uses: actions/checkout@v3 with: fetch-depth: 0 ref: "master" # Used to host cibuildwheel - name: Set up Python uses: actions/setup-python@v4 - name: Install python-semantic-release run: pipx install python-semantic-release==7.34.6 - name: Get Release Tag id: release_tag shell: bash run: | echo "::set-output name=newest_release_tag::$(semantic-release print-version --current)" - uses: actions/checkout@v3 with: ref: "${{ steps.release_tag.outputs.newest_release_tag }}" fetch-depth: 0 - name: Set up QEMU if: runner.os == 'Linux' uses: docker/setup-qemu-action@v3 with: platforms: arm64 - name: Build wheels uses: pypa/cibuildwheel@v2.17.0 # to supply options, put them in 'env', like: env: CIBW_SKIP: cp36-* cp37-* pp36-* pp37-* *p38-*_aarch64 *p39-*_aarch64 *p310-*_aarch64 pp*_aarch64 *musllinux*_aarch64 CIBW_BEFORE_ALL_LINUX: apt-get install -y gcc || yum install -y gcc || apk add gcc CIBW_ARCHS_LINUX: auto aarch64 CIBW_BUILD_VERBOSITY: 3 REQUIRE_CYTHON: 1 - uses: actions/upload-artifact@v3 with: path: ./wheelhouse/*.whl upload_pypi: needs: [build_wheels] runs-on: ubuntu-latest environment: release steps: - uses: actions/download-artifact@v3 with: # unpacks default artifact into dist/ # if `name: artifact` is omitted, the action will create extra parent dir name: artifact path: dist - uses: pypa/gh-action-pypi-publish@v1.5.0 with: user: __token__ password: ${{ secrets.PYPI_TOKEN }} # To test: repository_url: https://test.pypi.org/legacy/ 07070100000005000081A40000000000000000000000016619D4CC0000009A000000000000000000000000000000000000002300000000python-zeroconf-0.132.2/.gitignorebuild/ *.pyc *.pyo Thumbs.db .DS_Store .project .pydevproject .settings .idea .vslick .cache .mypy_cache/ docs/_build/ .vscode /dist/ /zeroconf.egg-info/ 07070100000006000081A40000000000000000000000016619D4CC00000661000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/.pre-commit-config.yaml# See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks exclude: "CHANGELOG.md" default_stages: [commit] ci: autofix_commit_msg: "chore(pre-commit.ci): auto fixes" autoupdate_commit_msg: "chore(pre-commit.ci): pre-commit autoupdate" repos: - repo: https://github.com/commitizen-tools/commitizen rev: v2.32.4 hooks: - id: commitizen stages: [commit-msg] - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: debug-statements - id: check-builtin-literals - id: check-case-conflict - id: check-docstring-first - id: check-json - id: check-toml - id: check-xml - id: check-yaml - id: detect-private-key - id: end-of-file-fixer - id: trailing-whitespace - id: debug-statements - repo: https://github.com/pre-commit/mirrors-prettier rev: v2.7.1 hooks: - id: prettier args: ["--tab-width", "2"] - repo: https://github.com/asottile/pyupgrade rev: v2.37.3 hooks: - id: pyupgrade args: [--py37-plus] - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/psf/black rev: 22.8.0 hooks: - id: black # - repo: https://github.com/codespell-project/codespell # rev: v2.2.1 # hooks: # - id: codespell - repo: https://github.com/PyCQA/flake8 rev: 5.0.4 hooks: - id: flake8 - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.931 hooks: - id: mypy additional_dependencies: [] 07070100000007000081A40000000000000000000000016619D4CC00014EED000000000000000000000000000000000000002500000000python-zeroconf-0.132.2/CHANGELOG.md# Changelog <!--next-version-placeholder--> ## v0.132.2 (2024-04-13) ### Fix * Update references to minimum-supported python version of 3.8 ([#1369](https://github.com/python-zeroconf/python-zeroconf/issues/1369)) ([`599524a`](https://github.com/python-zeroconf/python-zeroconf/commit/599524a5ce1e4c1731519dd89377c2a852e59935)) * Bump cibuildwheel to fix wheel builds ([#1371](https://github.com/python-zeroconf/python-zeroconf/issues/1371)) ([`83e4ce3`](https://github.com/python-zeroconf/python-zeroconf/commit/83e4ce3e31ddd4ae9aec2f8c9d84d7a93f8be210)) ## v0.132.1 (2024-04-12) ### Fix * Set change during iteration when dispatching listeners ([#1370](https://github.com/python-zeroconf/python-zeroconf/issues/1370)) ([`e9f8aa5`](https://github.com/python-zeroconf/python-zeroconf/commit/e9f8aa5741ae2d490c33a562b459f0af1014dbb0)) ## v0.132.0 (2024-04-01) ### Feature * Make async_get_service_info available on the Zeroconf object ([#1366](https://github.com/python-zeroconf/python-zeroconf/issues/1366)) ([`c4c2dee`](https://github.com/python-zeroconf/python-zeroconf/commit/c4c2deeb05279ddbb0eba1330c7ae58795fea001)) * Drop python 3.7 support ([#1359](https://github.com/python-zeroconf/python-zeroconf/issues/1359)) ([`4877829`](https://github.com/python-zeroconf/python-zeroconf/commit/4877829e6442de5426db152d11827b1ba85dbf59)) ### Fix * Avoid including scope_id in IPv6Address object if its zero ([#1367](https://github.com/python-zeroconf/python-zeroconf/issues/1367)) ([`edc4a55`](https://github.com/python-zeroconf/python-zeroconf/commit/edc4a556819956c238a11332052000dcbcb07e3d)) ## v0.131.0 (2023-12-19) ### Feature * Small speed up to constructing outgoing packets ([#1354](https://github.com/python-zeroconf/python-zeroconf/issues/1354)) ([`517d7d0`](https://github.com/python-zeroconf/python-zeroconf/commit/517d7d00ca7738c770077738125aec0e4824c000)) * Speed up processing incoming packets ([#1352](https://github.com/python-zeroconf/python-zeroconf/issues/1352)) ([`6c15325`](https://github.com/python-zeroconf/python-zeroconf/commit/6c153258a995cf9459a6f23267b7e379b5e2550f)) * Speed up the query handler ([#1350](https://github.com/python-zeroconf/python-zeroconf/issues/1350)) ([`9eac0a1`](https://github.com/python-zeroconf/python-zeroconf/commit/9eac0a122f28a7a4fa76cbfdda21d9a3571d7abb)) ## v0.130.0 (2023-12-16) ### Feature * Make ServiceInfo aware of question history ([#1348](https://github.com/python-zeroconf/python-zeroconf/issues/1348)) ([`b9aae1d`](https://github.com/python-zeroconf/python-zeroconf/commit/b9aae1de07bf1491e873bc314f8a1d7996127ad3)) * Small speed up to ServiceInfo construction ([#1346](https://github.com/python-zeroconf/python-zeroconf/issues/1346)) ([`b329d99`](https://github.com/python-zeroconf/python-zeroconf/commit/b329d99917bb731b4c70bf20c7c010eeb85ad9fd)) * Significantly improve efficiency of the ServiceBrowser scheduler ([#1335](https://github.com/python-zeroconf/python-zeroconf/issues/1335)) ([`c65d869`](https://github.com/python-zeroconf/python-zeroconf/commit/c65d869aec731b803484871e9d242a984f9f5848)) * Small speed up to processing incoming records ([#1345](https://github.com/python-zeroconf/python-zeroconf/issues/1345)) ([`7de655b`](https://github.com/python-zeroconf/python-zeroconf/commit/7de655b6f05012f20a3671e0bcdd44a1913d7b52)) * Small performance improvement for converting time ([#1342](https://github.com/python-zeroconf/python-zeroconf/issues/1342)) ([`73d3ab9`](https://github.com/python-zeroconf/python-zeroconf/commit/73d3ab90dd3b59caab771235dd6dbedf05bfe0b3)) * Small performance improvement for ServiceInfo asking questions ([#1341](https://github.com/python-zeroconf/python-zeroconf/issues/1341)) ([`810a309`](https://github.com/python-zeroconf/python-zeroconf/commit/810a3093c5a9411ee97740b468bd706bdf4a95de)) * Small performance improvement constructing outgoing questions ([#1340](https://github.com/python-zeroconf/python-zeroconf/issues/1340)) ([`157185f`](https://github.com/python-zeroconf/python-zeroconf/commit/157185f28bf1e83e6811e2a5cd1fa9b38966f780)) ### Fix * Scheduling race with the QueryScheduler ([#1347](https://github.com/python-zeroconf/python-zeroconf/issues/1347)) ([`cf40470`](https://github.com/python-zeroconf/python-zeroconf/commit/cf40470b89f918d3c24d7889d3536f3ffa44846c)) * Ensure question history suppresses duplicates ([#1338](https://github.com/python-zeroconf/python-zeroconf/issues/1338)) ([`6f23656`](https://github.com/python-zeroconf/python-zeroconf/commit/6f23656576daa04e3de44e100f3ddd60ee4c560d)) * Microsecond precision loss in the query handler ([#1339](https://github.com/python-zeroconf/python-zeroconf/issues/1339)) ([`6560fad`](https://github.com/python-zeroconf/python-zeroconf/commit/6560fad584e0d392962c9a9248759f17c416620e)) * Ensure IPv6 scoped address construction uses the string cache ([#1336](https://github.com/python-zeroconf/python-zeroconf/issues/1336)) ([`f78a196`](https://github.com/python-zeroconf/python-zeroconf/commit/f78a196db632c4fe017a34f1af8a58903c15a575)) ## v0.129.0 (2023-12-13) ### Feature * Add decoded_properties method to ServiceInfo ([#1332](https://github.com/python-zeroconf/python-zeroconf/issues/1332)) ([`9b595a1`](https://github.com/python-zeroconf/python-zeroconf/commit/9b595a1dcacf109c699953219d70fe36296c7318)) * Ensure ServiceInfo.properties always returns bytes ([#1333](https://github.com/python-zeroconf/python-zeroconf/issues/1333)) ([`d29553a`](https://github.com/python-zeroconf/python-zeroconf/commit/d29553ab7de6b7af70769ddb804fe2aaf492f320)) * Cache is_unspecified for zeroconf ip address objects ([#1331](https://github.com/python-zeroconf/python-zeroconf/issues/1331)) ([`a1c84dc`](https://github.com/python-zeroconf/python-zeroconf/commit/a1c84dc6adeebd155faec1a647c0f70d70de2945)) ### Technically breaking change * `ServiceInfo.properties` always returns a dictionary with type `dict[bytes, bytes | None]` instead of a mix `str` and `bytes`. It was only possible to get a mixed dictionary if it was manually passed in when `ServiceInfo` was constructed. ## v0.128.5 (2023-12-13) ### Fix * Performance regression with ServiceInfo IPv6Addresses ([#1330](https://github.com/python-zeroconf/python-zeroconf/issues/1330)) ([`e2f9f81`](https://github.com/python-zeroconf/python-zeroconf/commit/e2f9f81dbc54c3dd527eeb3298897d63f99d33f4)) ## v0.128.4 (2023-12-10) ### Fix * Re-expose ServiceInfo._set_properties for backwards compat ([#1327](https://github.com/python-zeroconf/python-zeroconf/issues/1327)) ([`39c4005`](https://github.com/python-zeroconf/python-zeroconf/commit/39c40051d7a63bdc63a3e2dfa20bd944fee4e761)) ## v0.128.3 (2023-12-10) ### Fix * Correct nsec record writing ([#1326](https://github.com/python-zeroconf/python-zeroconf/issues/1326)) ([`cd7a16a`](https://github.com/python-zeroconf/python-zeroconf/commit/cd7a16a32c37b2f7a2e90d3c749525a5393bad57)) ## v0.128.2 (2023-12-10) ### Fix * Timestamps missing double precision ([#1324](https://github.com/python-zeroconf/python-zeroconf/issues/1324)) ([`ecea4e4`](https://github.com/python-zeroconf/python-zeroconf/commit/ecea4e4217892ca8cf763074ac3e5d1b898acd21)) * Match cython version for dev deps to build deps ([#1325](https://github.com/python-zeroconf/python-zeroconf/issues/1325)) ([`a0dac46`](https://github.com/python-zeroconf/python-zeroconf/commit/a0dac46c01202b3d5a0823ac1928fc1d75332522)) ## v0.128.1 (2023-12-10) ### Fix * Correct handling of IPv6 addresses with scope_id in ServiceInfo ([#1322](https://github.com/python-zeroconf/python-zeroconf/issues/1322)) ([`1682991`](https://github.com/python-zeroconf/python-zeroconf/commit/1682991b985b1f7b2bf0cff1a7eb7793070e7cb1)) ## v0.128.0 (2023-12-02) ### Feature * Speed up unpacking TXT record data in ServiceInfo ([#1318](https://github.com/python-zeroconf/python-zeroconf/issues/1318)) ([`a200842`](https://github.com/python-zeroconf/python-zeroconf/commit/a20084281e66bdb9c37183a5eb992435f5b866ac)) ## v0.127.0 (2023-11-15) ### Feature * Small speed up to writing outgoing packets ([#1316](https://github.com/python-zeroconf/python-zeroconf/issues/1316)) ([`cd28476`](https://github.com/python-zeroconf/python-zeroconf/commit/cd28476f6b0a6c2c733273fb24ddaac6c7bbdf65)) * Speed up incoming packet reader ([#1314](https://github.com/python-zeroconf/python-zeroconf/issues/1314)) ([`0d60b61`](https://github.com/python-zeroconf/python-zeroconf/commit/0d60b61538a5d4b6f44b2369333b6e916a0a55b4)) * Small speed up to processing incoming dns records ([#1315](https://github.com/python-zeroconf/python-zeroconf/issues/1315)) ([`bfe4c24`](https://github.com/python-zeroconf/python-zeroconf/commit/bfe4c24881a7259713425df5ab00ffe487518841)) ## v0.126.0 (2023-11-13) ### Feature * Speed up outgoing packet writer ([#1313](https://github.com/python-zeroconf/python-zeroconf/issues/1313)) ([`55cf4cc`](https://github.com/python-zeroconf/python-zeroconf/commit/55cf4ccdff886a136db4e2133d3e6cdd001a8bd6)) * Speed up writing name compression for outgoing packets ([#1312](https://github.com/python-zeroconf/python-zeroconf/issues/1312)) ([`9caeabb`](https://github.com/python-zeroconf/python-zeroconf/commit/9caeabb6d4659a25ea1251c1ee7bb824e05f3d8b)) ## v0.125.0 (2023-11-12) ### Feature * Speed up service browser queries when browsing many types ([#1311](https://github.com/python-zeroconf/python-zeroconf/issues/1311)) ([`d192d33`](https://github.com/python-zeroconf/python-zeroconf/commit/d192d33b1f05aa95a89965e86210aec086673a17)) ## v0.124.0 (2023-11-12) ### Feature * Avoid decoding known answers if we have no answers to give ([#1308](https://github.com/python-zeroconf/python-zeroconf/issues/1308)) ([`605dc9c`](https://github.com/python-zeroconf/python-zeroconf/commit/605dc9ccd843a535802031f051b3d93310186ad1)) * Small speed up to process incoming packets ([#1309](https://github.com/python-zeroconf/python-zeroconf/issues/1309)) ([`56ef908`](https://github.com/python-zeroconf/python-zeroconf/commit/56ef90865189c01d2207abcc5e2efe3a7a022fa1)) ## v0.123.0 (2023-11-12) ### Feature * Speed up instances only used to lookup answers ([#1307](https://github.com/python-zeroconf/python-zeroconf/issues/1307)) ([`0701b8a`](https://github.com/python-zeroconf/python-zeroconf/commit/0701b8ab6009891cbaddaa1d17116d31fd1b2f78)) ## v0.122.3 (2023-11-09) ### Fix * Do not build musllinux aarch64 wheels to reduce release time ([#1306](https://github.com/python-zeroconf/python-zeroconf/issues/1306)) ([`79aafb0`](https://github.com/python-zeroconf/python-zeroconf/commit/79aafb0acf7ca6b17976be7ede748008deada27b)) ## v0.122.2 (2023-11-09) ### Fix * Do not build aarch64 wheels for PyPy ([#1305](https://github.com/python-zeroconf/python-zeroconf/issues/1305)) ([`7e884db`](https://github.com/python-zeroconf/python-zeroconf/commit/7e884db4d958459e64257aba860dba2450db0687)) ## v0.122.1 (2023-11-09) ### Fix * Skip wheel builds for eol python and older python with aarch64 ([#1304](https://github.com/python-zeroconf/python-zeroconf/issues/1304)) ([`6c8f5a5`](https://github.com/python-zeroconf/python-zeroconf/commit/6c8f5a5dec2072aa6a8f889c5d8a4623ab392234)) ## v0.122.0 (2023-11-08) ### Feature * Build aarch64 wheels ([#1302](https://github.com/python-zeroconf/python-zeroconf/issues/1302)) ([`4fe58e2`](https://github.com/python-zeroconf/python-zeroconf/commit/4fe58e2edc6da64a8ece0e2b16ec9ebfc5b3cd83)) ## v0.121.0 (2023-11-08) ### Feature * Speed up record updates ([#1301](https://github.com/python-zeroconf/python-zeroconf/issues/1301)) ([`d2af6a0`](https://github.com/python-zeroconf/python-zeroconf/commit/d2af6a0978f5abe4f8bb70d3e29d9836d0fd77c4)) ## v0.120.0 (2023-11-05) ### Feature * Speed up incoming packet processing with a memory view ([#1290](https://github.com/python-zeroconf/python-zeroconf/issues/1290)) ([`f1f0a25`](https://github.com/python-zeroconf/python-zeroconf/commit/f1f0a2504afd4d29bc6b7cf715cd3cb81b9049f7)) * Speed up decoding labels from incoming data ([#1291](https://github.com/python-zeroconf/python-zeroconf/issues/1291)) ([`c37ead4`](https://github.com/python-zeroconf/python-zeroconf/commit/c37ead4d7000607e81706a97b4cdffd80cf8cf99)) * Speed up ServiceBrowsers with a pxd for the signal interface ([#1289](https://github.com/python-zeroconf/python-zeroconf/issues/1289)) ([`8a17f20`](https://github.com/python-zeroconf/python-zeroconf/commit/8a17f2053a89db4beca9e8c1de4640faf27726b4)) ## v0.119.0 (2023-10-18) ### Feature * Update cibuildwheel to build wheels on latest cython final release ([#1285](https://github.com/python-zeroconf/python-zeroconf/issues/1285)) ([`e8c9083`](https://github.com/python-zeroconf/python-zeroconf/commit/e8c9083bb118764a85b12fac9055152a2f62a212)) ## v0.118.1 (2023-10-18) ### Fix * Reduce size of wheels by excluding generated .c files ([#1284](https://github.com/python-zeroconf/python-zeroconf/issues/1284)) ([`b6afa4b`](https://github.com/python-zeroconf/python-zeroconf/commit/b6afa4b2775a1fdb090145eccdc5711c98e7147a)) ## v0.118.0 (2023-10-14) ### Feature * Small improvements to ServiceBrowser performance ([#1283](https://github.com/python-zeroconf/python-zeroconf/issues/1283)) ([`0fc031b`](https://github.com/python-zeroconf/python-zeroconf/commit/0fc031b1e7bf1766d5a1d39d70d300b86e36715e)) ## v0.117.0 (2023-10-14) ### Feature * Small cleanups to incoming data handlers ([#1282](https://github.com/python-zeroconf/python-zeroconf/issues/1282)) ([`4f4bd9f`](https://github.com/python-zeroconf/python-zeroconf/commit/4f4bd9ff7c1e575046e5ea213d9b8c91ac7a24a9)) ## v0.116.0 (2023-10-13) ### Feature * Reduce type checking overhead at run time ([#1281](https://github.com/python-zeroconf/python-zeroconf/issues/1281)) ([`8f30099`](https://github.com/python-zeroconf/python-zeroconf/commit/8f300996e5bd4316b2237f0502791dd0d6a855fe)) ## v0.115.2 (2023-10-05) ### Fix * Ensure ServiceInfo cache is cleared when adding to the registry ([#1279](https://github.com/python-zeroconf/python-zeroconf/issues/1279)) ([`2060eb2`](https://github.com/python-zeroconf/python-zeroconf/commit/2060eb2cc43489c34bea08924c3f40b875d5a498)) ## v0.115.1 (2023-10-01) ### Fix * Add missing python definition for addresses_by_version ([#1278](https://github.com/python-zeroconf/python-zeroconf/issues/1278)) ([`52ee02b`](https://github.com/python-zeroconf/python-zeroconf/commit/52ee02b16860e344c402124f4b2e2869536ec839)) ## v0.115.0 (2023-09-26) ### Feature * Speed up outgoing multicast queue ([#1277](https://github.com/python-zeroconf/python-zeroconf/issues/1277)) ([`a13fd49`](https://github.com/python-zeroconf/python-zeroconf/commit/a13fd49d77474fd5858de809e48cbab1ccf89173)) ## v0.114.0 (2023-09-25) ### Feature * Speed up responding to queries ([#1275](https://github.com/python-zeroconf/python-zeroconf/issues/1275)) ([`3c6b18c`](https://github.com/python-zeroconf/python-zeroconf/commit/3c6b18cdf4c94773ad6f4497df98feb337939ee9)) ## v0.113.0 (2023-09-24) ### Feature * Improve performance of loading records from cache in ServiceInfo ([#1274](https://github.com/python-zeroconf/python-zeroconf/issues/1274)) ([`6257d49`](https://github.com/python-zeroconf/python-zeroconf/commit/6257d49952e02107f800f4ad4894716508edfcda)) ## v0.112.0 (2023-09-14) ### Feature * Improve AsyncServiceBrowser performance ([#1273](https://github.com/python-zeroconf/python-zeroconf/issues/1273)) ([`0c88ecf`](https://github.com/python-zeroconf/python-zeroconf/commit/0c88ecf5ef6b9b256f991e7a630048de640999a6)) ## v0.111.0 (2023-09-14) ### Feature * Speed up question and answer internals ([#1272](https://github.com/python-zeroconf/python-zeroconf/issues/1272)) ([`d24722b`](https://github.com/python-zeroconf/python-zeroconf/commit/d24722bfa4201d48ab482d35b0ef004f070ada80)) ## v0.110.0 (2023-09-14) ### Feature * Small speed ups to ServiceBrowser ([#1271](https://github.com/python-zeroconf/python-zeroconf/issues/1271)) ([`22c433d`](https://github.com/python-zeroconf/python-zeroconf/commit/22c433ddaea3049ac49933325ba938fd87a529c0)) ## v0.109.0 (2023-09-14) ### Feature * Speed up ServiceBrowsers with a cython pxd ([#1270](https://github.com/python-zeroconf/python-zeroconf/issues/1270)) ([`4837876`](https://github.com/python-zeroconf/python-zeroconf/commit/48378769c3887b5746ca00de30067a4c0851765c)) ## v0.108.0 (2023-09-11) ### Feature * Improve performance of constructing outgoing queries ([#1267](https://github.com/python-zeroconf/python-zeroconf/issues/1267)) ([`00c439a`](https://github.com/python-zeroconf/python-zeroconf/commit/00c439a6400b7850ef9fdd75bc8d82d4e64b1da0)) ## v0.107.0 (2023-09-11) ### Feature * Speed up responding to queries ([#1266](https://github.com/python-zeroconf/python-zeroconf/issues/1266)) ([`24a0a00`](https://github.com/python-zeroconf/python-zeroconf/commit/24a0a00b3e457979e279a2eeadc8fad2ab09e125)) ## v0.106.0 (2023-09-11) ### Feature * Speed up answering questions ([#1265](https://github.com/python-zeroconf/python-zeroconf/issues/1265)) ([`37bfaf2`](https://github.com/python-zeroconf/python-zeroconf/commit/37bfaf2f630358e8c68652f3b3120931a6f94910)) ## v0.105.0 (2023-09-10) ### Feature * Speed up ServiceInfo with a cython pxd ([#1264](https://github.com/python-zeroconf/python-zeroconf/issues/1264)) ([`7ca690a`](https://github.com/python-zeroconf/python-zeroconf/commit/7ca690ac3fa75e7474d3412944bbd5056cb313dd)) ## v0.104.0 (2023-09-10) ### Feature * Speed up generating answers ([#1262](https://github.com/python-zeroconf/python-zeroconf/issues/1262)) ([`50a8f06`](https://github.com/python-zeroconf/python-zeroconf/commit/50a8f066b6ab90bc9e3300f81cf9332550b720df)) ## v0.103.0 (2023-09-09) ### Feature * Avoid calling get_running_loop when resolving ServiceInfo ([#1261](https://github.com/python-zeroconf/python-zeroconf/issues/1261)) ([`33a2714`](https://github.com/python-zeroconf/python-zeroconf/commit/33a2714cadff96edf016b869cc63b0661d16ef2c)) ## v0.102.0 (2023-09-07) ### Feature * Significantly speed up writing outgoing dns records ([#1260](https://github.com/python-zeroconf/python-zeroconf/issues/1260)) ([`bf2f366`](https://github.com/python-zeroconf/python-zeroconf/commit/bf2f3660a1f341e50ab0ae586dfbacbc5ddcc077)) ## v0.101.0 (2023-09-07) ### Feature * Speed up writing outgoing dns records ([#1259](https://github.com/python-zeroconf/python-zeroconf/issues/1259)) ([`248655f`](https://github.com/python-zeroconf/python-zeroconf/commit/248655f0276223b089373c70ec13a0385dfaa4d6)) ## v0.100.0 (2023-09-07) ### Feature * Small speed up to writing outgoing dns records ([#1258](https://github.com/python-zeroconf/python-zeroconf/issues/1258)) ([`1ed6bd2`](https://github.com/python-zeroconf/python-zeroconf/commit/1ed6bd2ec4db0612b71384f923ffff1efd3ce878)) ## v0.99.0 (2023-09-06) ### Feature * Reduce IP Address parsing overhead in ServiceInfo ([#1257](https://github.com/python-zeroconf/python-zeroconf/issues/1257)) ([`83d0b7f`](https://github.com/python-zeroconf/python-zeroconf/commit/83d0b7fda2eb09c9c6e18b85f329d1ddc701e3fb)) ## v0.98.0 (2023-09-06) ### Feature * Speed up decoding incoming packets ([#1256](https://github.com/python-zeroconf/python-zeroconf/issues/1256)) ([`ac081cf`](https://github.com/python-zeroconf/python-zeroconf/commit/ac081cf00addde1ceea2c076f73905fdb293de3a)) ## v0.97.0 (2023-09-03) ### Feature * Speed up answering queries ([#1255](https://github.com/python-zeroconf/python-zeroconf/issues/1255)) ([`2d3aed3`](https://github.com/python-zeroconf/python-zeroconf/commit/2d3aed36e24c73013fcf4acc90803fc1737d0917)) ## v0.96.0 (2023-09-03) ### Feature * Optimize DNSCache.get_by_details ([#1254](https://github.com/python-zeroconf/python-zeroconf/issues/1254)) ([`ce59787`](https://github.com/python-zeroconf/python-zeroconf/commit/ce59787a170781ffdaa22425018d288b395ac081)) ## v0.95.0 (2023-09-03) ### Feature * Speed up adding and removing RecordUpdateListeners ([#1253](https://github.com/python-zeroconf/python-zeroconf/issues/1253)) ([`22e4a29`](https://github.com/python-zeroconf/python-zeroconf/commit/22e4a296d440b3038c0ff5ed6fc8878304ec4937)) ## v0.94.0 (2023-09-03) ### Feature * Optimize cache implementation ([#1252](https://github.com/python-zeroconf/python-zeroconf/issues/1252)) ([`8d3ec79`](https://github.com/python-zeroconf/python-zeroconf/commit/8d3ec792277aaf7ef790318b5b35ab00839ca3b3)) ## v0.93.1 (2023-09-03) ### Fix * No change re-release due to unrecoverable failed CI run ([#1251](https://github.com/python-zeroconf/python-zeroconf/issues/1251)) ([`730921b`](https://github.com/python-zeroconf/python-zeroconf/commit/730921b155dfb9c62251c8c643b1302e807aff3b)) ## v0.93.0 (2023-09-02) ### Feature * Reduce overhead to answer questions ([#1250](https://github.com/python-zeroconf/python-zeroconf/issues/1250)) ([`7cb8da0`](https://github.com/python-zeroconf/python-zeroconf/commit/7cb8da0c6c5c944588009fe36012c1197c422668)) ## v0.92.0 (2023-09-02) ### Feature * Cache construction of records used to answer queries from the service registry ([#1243](https://github.com/python-zeroconf/python-zeroconf/issues/1243)) ([`0890f62`](https://github.com/python-zeroconf/python-zeroconf/commit/0890f628dbbd577fb77d3e6f2e267052b2b2b515)) ## v0.91.1 (2023-09-02) ### Fix * Remove useless calls in ServiceInfo ([#1248](https://github.com/python-zeroconf/python-zeroconf/issues/1248)) ([`4e40fae`](https://github.com/python-zeroconf/python-zeroconf/commit/4e40fae20bf50b4608e28fad4a360c4ed48ac86b)) ## v0.91.0 (2023-09-02) ### Feature * Reduce overhead to process incoming updates by avoiding the handle_response shim ([#1247](https://github.com/python-zeroconf/python-zeroconf/issues/1247)) ([`5e31f0a`](https://github.com/python-zeroconf/python-zeroconf/commit/5e31f0afe4c341fbdbbbe50348a829ea553cbda0)) ## v0.90.0 (2023-09-02) ### Feature * Avoid python float conversion in listener hot path ([#1245](https://github.com/python-zeroconf/python-zeroconf/issues/1245)) ([`816ad4d`](https://github.com/python-zeroconf/python-zeroconf/commit/816ad4dceb3859bad4bb136bdb1d1ee2daa0bf5a)) ## v0.89.0 (2023-09-02) ### Feature * Reduce overhead to process incoming questions ([#1244](https://github.com/python-zeroconf/python-zeroconf/issues/1244)) ([`18b65d1`](https://github.com/python-zeroconf/python-zeroconf/commit/18b65d1c75622869b0c29258215d3db3ae520d6c)) ## v0.88.0 (2023-08-29) ### Feature * Speed up RecordManager with additional cython defs ([#1242](https://github.com/python-zeroconf/python-zeroconf/issues/1242)) ([`5a76fc5`](https://github.com/python-zeroconf/python-zeroconf/commit/5a76fc5ff74f2941ffbf7570e45390f35e0b7e01)) ## v0.87.0 (2023-08-29) ### Feature * Improve performance by adding cython pxd for RecordManager ([#1241](https://github.com/python-zeroconf/python-zeroconf/issues/1241)) ([`a7dad3d`](https://github.com/python-zeroconf/python-zeroconf/commit/a7dad3d9743586f352e21eea1e129c6875f9a713)) ## v0.86.0 (2023-08-28) ### Feature * Build wheels for cpython 3.12 ([#1239](https://github.com/python-zeroconf/python-zeroconf/issues/1239)) ([`58bc154`](https://github.com/python-zeroconf/python-zeroconf/commit/58bc154f55b06b4ddfc4a141592488abe76f062a)) * Use server_key when processing DNSService records ([#1238](https://github.com/python-zeroconf/python-zeroconf/issues/1238)) ([`cc8feb1`](https://github.com/python-zeroconf/python-zeroconf/commit/cc8feb110fefc3fb714fd482a52f16e2b620e8c4)) ## v0.85.0 (2023-08-27) ### Feature * Simplify code to unpack properties ([#1237](https://github.com/python-zeroconf/python-zeroconf/issues/1237)) ([`68d9998`](https://github.com/python-zeroconf/python-zeroconf/commit/68d99985a0e9d2c72ff670b2e2af92271a6fe934)) ## v0.84.0 (2023-08-27) ### Feature * Context managers in ServiceBrowser and AsyncServiceBrowser ([#1233](https://github.com/python-zeroconf/python-zeroconf/issues/1233)) ([`bd8d846`](https://github.com/python-zeroconf/python-zeroconf/commit/bd8d8467dec2a39a0b525043ea1051259100fded)) ## v0.83.1 (2023-08-27) ### Fix * Rebuild wheels with cython 3.0.2 ([#1236](https://github.com/python-zeroconf/python-zeroconf/issues/1236)) ([`dd637fb`](https://github.com/python-zeroconf/python-zeroconf/commit/dd637fb2e5a87ba283750e69d116e124bef54e7c)) ## v0.83.0 (2023-08-26) ### Feature * Speed up question and answer history with a cython pxd ([#1234](https://github.com/python-zeroconf/python-zeroconf/issues/1234)) ([`703ecb2`](https://github.com/python-zeroconf/python-zeroconf/commit/703ecb2901b2150fb72fac3deed61d7302561298)) ## v0.82.1 (2023-08-22) ### Fix * Build failures with older cython 0.29 series ([#1232](https://github.com/python-zeroconf/python-zeroconf/issues/1232)) ([`30c3ad9`](https://github.com/python-zeroconf/python-zeroconf/commit/30c3ad9d1bc6b589e1ca6675fea21907ebcd1ced)) ## v0.82.0 (2023-08-22) ### Feature * Optimize processing of records in RecordUpdateListener subclasses ([#1231](https://github.com/python-zeroconf/python-zeroconf/issues/1231)) ([`3e89294`](https://github.com/python-zeroconf/python-zeroconf/commit/3e89294ea0ecee1122e1c1ffdc78925add8ca40e)) ## v0.81.0 (2023-08-22) ### Feature * Speed up the service registry with a cython pxd ([#1226](https://github.com/python-zeroconf/python-zeroconf/issues/1226)) ([`47d3c7a`](https://github.com/python-zeroconf/python-zeroconf/commit/47d3c7ad4bc5f2247631c3ad5e6b6156d45a0a4e)) * Optimizing sending answers to questions ([#1227](https://github.com/python-zeroconf/python-zeroconf/issues/1227)) ([`cd7b56b`](https://github.com/python-zeroconf/python-zeroconf/commit/cd7b56b2aa0c8ee429da430e9a36abd515512011)) ## v0.80.0 (2023-08-15) ### Feature * Optimize unpacking properties in ServiceInfo ([#1225](https://github.com/python-zeroconf/python-zeroconf/issues/1225)) ([`1492e41`](https://github.com/python-zeroconf/python-zeroconf/commit/1492e41b3d5cba5598cc9dd6bd2bc7d238f13555)) ## v0.79.0 (2023-08-14) ### Feature * Refactor notify implementation to reduce overhead of adding and removing listeners ([#1224](https://github.com/python-zeroconf/python-zeroconf/issues/1224)) ([`ceb92cf`](https://github.com/python-zeroconf/python-zeroconf/commit/ceb92cfe42d885dbb38cee7aaeebf685d97627a9)) ## v0.78.0 (2023-08-14) ### Feature * Add cython pxd file for _listener.py to improve incoming message processing performance ([#1221](https://github.com/python-zeroconf/python-zeroconf/issues/1221)) ([`f459856`](https://github.com/python-zeroconf/python-zeroconf/commit/f459856a0a61b8afa8a541926d7e15d51f8e4aea)) ## v0.77.0 (2023-08-14) ### Feature * Cythonize _listener.py to improve incoming message processing performance ([#1220](https://github.com/python-zeroconf/python-zeroconf/issues/1220)) ([`9efde8c`](https://github.com/python-zeroconf/python-zeroconf/commit/9efde8c8c1ed14c5d3c162f185b49212fcfcb5c9)) ## v0.76.0 (2023-08-14) ### Feature * Improve performance responding to queries ([#1217](https://github.com/python-zeroconf/python-zeroconf/issues/1217)) ([`69b33be`](https://github.com/python-zeroconf/python-zeroconf/commit/69b33be3b2f9d4a27ef5154cae94afca048efffa)) ## v0.75.0 (2023-08-13) ### Feature * Expose flag to disable strict name checking in service registration ([#1215](https://github.com/python-zeroconf/python-zeroconf/issues/1215)) ([`5df8a57`](https://github.com/python-zeroconf/python-zeroconf/commit/5df8a57a14d59687a3c22ea8ee063e265031e278)) * Speed up processing incoming records ([#1216](https://github.com/python-zeroconf/python-zeroconf/issues/1216)) ([`aff625d`](https://github.com/python-zeroconf/python-zeroconf/commit/aff625dc6a5e816dad519644c4adac4f96980c04)) ## v0.74.0 (2023-08-04) ### Feature * Speed up unpacking text records in ServiceInfo ([#1212](https://github.com/python-zeroconf/python-zeroconf/issues/1212)) ([`99a6f98`](https://github.com/python-zeroconf/python-zeroconf/commit/99a6f98e44a1287ba537eabb852b1b69923402f0)) ### Fix * Remove typing on reset_ttl for cython compat ([#1213](https://github.com/python-zeroconf/python-zeroconf/issues/1213)) ([`0094e26`](https://github.com/python-zeroconf/python-zeroconf/commit/0094e2684344c6b7edd7948924f093f1b4c19901)) ## v0.73.0 (2023-08-03) ### Feature * Add a cache to service_type_name ([#1211](https://github.com/python-zeroconf/python-zeroconf/issues/1211)) ([`53a694f`](https://github.com/python-zeroconf/python-zeroconf/commit/53a694f60e675ae0560e727be6b721b401c2b68f)) ## v0.72.3 (2023-08-03) ### Fix * Revert adding typing to DNSRecord.suppressed_by ([#1210](https://github.com/python-zeroconf/python-zeroconf/issues/1210)) ([`3dba5ae`](https://github.com/python-zeroconf/python-zeroconf/commit/3dba5ae0c0e9473b7b20fd6fc79fa1a3b298dc5a)) ## v0.72.2 (2023-08-03) ### Fix * Revert DNSIncoming cimport in _dns.pxd ([#1209](https://github.com/python-zeroconf/python-zeroconf/issues/1209)) ([`5f14b6d`](https://github.com/python-zeroconf/python-zeroconf/commit/5f14b6dc687b3a0716d0ca7f61ccf1e93dfe5fa1)) ## v0.72.1 (2023-08-03) ### Fix * Race with InvalidStateError when async_request times out ([#1208](https://github.com/python-zeroconf/python-zeroconf/issues/1208)) ([`2233b6b`](https://github.com/python-zeroconf/python-zeroconf/commit/2233b6bc4ceeee5524d2ee88ecae8234173feb5f)) ## v0.72.0 (2023-08-02) ### Feature * Speed up processing incoming records ([#1206](https://github.com/python-zeroconf/python-zeroconf/issues/1206)) ([`126849c`](https://github.com/python-zeroconf/python-zeroconf/commit/126849c92be8cec9253fba9faa591029d992fcc3)) ## v0.71.5 (2023-08-02) ### Fix * Improve performance of ServiceInfo.async_request ([#1205](https://github.com/python-zeroconf/python-zeroconf/issues/1205)) ([`8019a73`](https://github.com/python-zeroconf/python-zeroconf/commit/8019a73c952f2fc4c88d849aab970fafedb316d8)) ## v0.71.4 (2023-07-24) ### Fix * Cleanup naming from previous refactoring in ServiceInfo ([#1202](https://github.com/python-zeroconf/python-zeroconf/issues/1202)) ([`b272d75`](https://github.com/python-zeroconf/python-zeroconf/commit/b272d75abd982f3be1f4b20f683cac38011cc6f4)) ## v0.71.3 (2023-07-23) ### Fix * Pin python-semantic-release to fix release process ([#1200](https://github.com/python-zeroconf/python-zeroconf/issues/1200)) ([`c145a23`](https://github.com/python-zeroconf/python-zeroconf/commit/c145a238d768aa17c3aebe120c20a46bfbec6b99)) ## v0.71.2 (2023-07-23) ### Fix * No change re-release to fix wheel builds ([#1199](https://github.com/python-zeroconf/python-zeroconf/issues/1199)) ([`8c3a4c8`](https://github.com/python-zeroconf/python-zeroconf/commit/8c3a4c80c221bea7401c12e1c6a525e75b7ffea2)) ## v0.71.1 (2023-07-23) ### Fix * Add missing if TYPE_CHECKING guard to generate_service_query ([#1198](https://github.com/python-zeroconf/python-zeroconf/issues/1198)) ([`ac53adf`](https://github.com/python-zeroconf/python-zeroconf/commit/ac53adf7e71db14c1a0f9adbfd1d74033df36898)) ## v0.71.0 (2023-07-08) ### Feature * Improve incoming data processing performance ([#1194](https://github.com/python-zeroconf/python-zeroconf/issues/1194)) ([`a56c776`](https://github.com/python-zeroconf/python-zeroconf/commit/a56c776008ef86f99db78f5997e45a57551be725)) ## v0.70.0 (2023-07-02) ### Feature * Add support for sending to a specific `addr` and `port` with `ServiceInfo.async_request` and `ServiceInfo.request` ([#1192](https://github.com/python-zeroconf/python-zeroconf/issues/1192)) ([`405f547`](https://github.com/python-zeroconf/python-zeroconf/commit/405f54762d3f61e97de9c1787e837e953de31412)) ## v0.69.0 (2023-06-18) ### Feature * Cython3 support ([#1190](https://github.com/python-zeroconf/python-zeroconf/issues/1190)) ([`8ae8ba1`](https://github.com/python-zeroconf/python-zeroconf/commit/8ae8ba1af324b0c8c2da3bd12c264a5c0f3dcc3d)) * Reorder incoming data handler to reduce overhead ([#1189](https://github.com/python-zeroconf/python-zeroconf/issues/1189)) ([`32756ff`](https://github.com/python-zeroconf/python-zeroconf/commit/32756ff113f675b7a9cf16d3c0ab840ba733e5e4)) ## v0.68.1 (2023-06-18) ### Fix * Reduce debug logging overhead by adding missing checks to datagram_received ([#1188](https://github.com/python-zeroconf/python-zeroconf/issues/1188)) ([`ac5c50a`](https://github.com/python-zeroconf/python-zeroconf/commit/ac5c50afc70aaa33fcd20bf02222ff4f0c596fa3)) ## v0.68.0 (2023-06-17) ### Feature * Reduce overhead to handle queries and responses ([#1184](https://github.com/python-zeroconf/python-zeroconf/issues/1184)) ([`81126b7`](https://github.com/python-zeroconf/python-zeroconf/commit/81126b7600f94848ef8c58b70bac0c6ab993c6ae)) ## v0.67.0 (2023-06-17) ### Feature * Speed up answering incoming questions ([#1186](https://github.com/python-zeroconf/python-zeroconf/issues/1186)) ([`8f37665`](https://github.com/python-zeroconf/python-zeroconf/commit/8f376658d2a3bef0353646e6fddfda15626b73a9)) ## v0.66.0 (2023-06-13) ### Feature * Optimize construction of outgoing dns records ([#1182](https://github.com/python-zeroconf/python-zeroconf/issues/1182)) ([`fc0341f`](https://github.com/python-zeroconf/python-zeroconf/commit/fc0341f281cdb71428c0f1cf90c12d34cbb4acae)) ## v0.65.0 (2023-06-13) ### Feature * Reduce overhead to enumerate ip addresses in ServiceInfo ([#1181](https://github.com/python-zeroconf/python-zeroconf/issues/1181)) ([`6a85cbf`](https://github.com/python-zeroconf/python-zeroconf/commit/6a85cbf2b872cb0abd184c2dd728d9ae3eb8115c)) ## v0.64.1 (2023-06-05) ### Fix * Small internal typing cleanups ([#1180](https://github.com/python-zeroconf/python-zeroconf/issues/1180)) ([`f03e511`](https://github.com/python-zeroconf/python-zeroconf/commit/f03e511f7aae72c5ccd4f7514d89e168847bd7a2)) ## v0.64.0 (2023-06-05) ### Feature * Speed up processing incoming records ([#1179](https://github.com/python-zeroconf/python-zeroconf/issues/1179)) ([`d919316`](https://github.com/python-zeroconf/python-zeroconf/commit/d9193160b05beeca3755e19fd377ba13fe37b071)) ### Fix * Always answer QU questions when the exact same packet is received from different sources in sequence ([#1178](https://github.com/python-zeroconf/python-zeroconf/issues/1178)) ([`74d7ba1`](https://github.com/python-zeroconf/python-zeroconf/commit/74d7ba1aeeae56be087ee8142ee6ca1219744baa)) ## v0.63.0 (2023-05-25) ### Feature * Small speed up to fetch dns addresses from ServiceInfo ([#1176](https://github.com/python-zeroconf/python-zeroconf/issues/1176)) ([`4deaa6e`](https://github.com/python-zeroconf/python-zeroconf/commit/4deaa6ed7c9161db55bf16ec068ab7260bbd4976)) * Speed up the service registry ([#1174](https://github.com/python-zeroconf/python-zeroconf/issues/1174)) ([`360ceb2`](https://github.com/python-zeroconf/python-zeroconf/commit/360ceb2548c4c4974ff798aac43a6fff9803ea0e)) * Improve dns cache performance ([#1172](https://github.com/python-zeroconf/python-zeroconf/issues/1172)) ([`bb496a1`](https://github.com/python-zeroconf/python-zeroconf/commit/bb496a1dd5fa3562c0412cb064d14639a542592e)) ## v0.62.0 (2023-05-04) ### Feature * Improve performance of ServiceBrowser outgoing query scheduler ([#1170](https://github.com/python-zeroconf/python-zeroconf/issues/1170)) ([`963d022`](https://github.com/python-zeroconf/python-zeroconf/commit/963d022ef82b615540fa7521d164a98a6c6f5209)) ## v0.61.0 (2023-05-03) ### Feature * Speed up parsing NSEC records ([#1169](https://github.com/python-zeroconf/python-zeroconf/issues/1169)) ([`06fa94d`](https://github.com/python-zeroconf/python-zeroconf/commit/06fa94d87b4f0451cb475a921ce1d8e9562e0f26)) ## v0.60.0 (2023-05-01) ### Feature * Speed up processing incoming data ([#1167](https://github.com/python-zeroconf/python-zeroconf/issues/1167)) ([`fbaaf7b`](https://github.com/python-zeroconf/python-zeroconf/commit/fbaaf7bb6ff985bdabb85feb6cba144f12d4f1d6)) ## v0.59.0 (2023-05-01) ### Feature * Speed up decoding dns questions when processing incoming data ([#1168](https://github.com/python-zeroconf/python-zeroconf/issues/1168)) ([`f927190`](https://github.com/python-zeroconf/python-zeroconf/commit/f927190cb24f70fd7c825c6e12151fcc0daf3973)) ## v0.58.2 (2023-04-26) ### Fix * Re-release to rebuild failed wheels ([#1165](https://github.com/python-zeroconf/python-zeroconf/issues/1165)) ([`4986271`](https://github.com/python-zeroconf/python-zeroconf/commit/498627166a4976f1d9d8cd1f3654b0d50272d266)) ## v0.58.1 (2023-04-26) ### Fix * Reduce cast calls in service browser ([#1164](https://github.com/python-zeroconf/python-zeroconf/issues/1164)) ([`c0d65ae`](https://github.com/python-zeroconf/python-zeroconf/commit/c0d65aeae7037a18ed1149336f5e7bdb8b2dd8cf)) ## v0.58.0 (2023-04-23) ### Feature * Speed up incoming parser ([#1163](https://github.com/python-zeroconf/python-zeroconf/issues/1163)) ([`4626399`](https://github.com/python-zeroconf/python-zeroconf/commit/46263999c0c7ea5176885f1eadd2c8498834b70e)) ## v0.57.0 (2023-04-23) ### Feature * Speed up incoming data parser ([#1161](https://github.com/python-zeroconf/python-zeroconf/issues/1161)) ([`cb4c3b2`](https://github.com/python-zeroconf/python-zeroconf/commit/cb4c3b2b80ca3b88b8de6e87062a45e03e8805a6)) ## v0.56.0 (2023-04-07) ### Feature * Reduce denial of service protection overhead ([#1157](https://github.com/python-zeroconf/python-zeroconf/issues/1157)) ([`2c2f26a`](https://github.com/python-zeroconf/python-zeroconf/commit/2c2f26a87d0aac81a77205b06bc9ba499caa2321)) ## v0.55.0 (2023-04-07) ### Feature * Improve performance of processing incoming records ([#1155](https://github.com/python-zeroconf/python-zeroconf/issues/1155)) ([`b65e279`](https://github.com/python-zeroconf/python-zeroconf/commit/b65e2792751c44e0fafe9ad3a55dadc5d8ee9d46)) ## v0.54.0 (2023-04-03) ### Feature * Avoid waking async_request when record updates are not relevant ([#1153](https://github.com/python-zeroconf/python-zeroconf/issues/1153)) ([`a3f970c`](https://github.com/python-zeroconf/python-zeroconf/commit/a3f970c7f66067cf2c302c49ed6ad8286f19b679)) ## v0.53.1 (2023-04-03) ### Fix * Addresses incorrect after server name change ([#1154](https://github.com/python-zeroconf/python-zeroconf/issues/1154)) ([`41ea06a`](https://github.com/python-zeroconf/python-zeroconf/commit/41ea06a0192c0d186e678009285759eb37d880d5)) ## v0.53.0 (2023-04-02) ### Feature * Improve ServiceBrowser performance by removing OrderedDict ([#1148](https://github.com/python-zeroconf/python-zeroconf/issues/1148)) ([`9a16be5`](https://github.com/python-zeroconf/python-zeroconf/commit/9a16be56a9f69a5d0f7cde13dc1337b6d93c1433)) ### Fix * Make parsed_scoped_addresses return addresses in the same order as all other methods ([#1150](https://github.com/python-zeroconf/python-zeroconf/issues/1150)) ([`9b6adcf`](https://github.com/python-zeroconf/python-zeroconf/commit/9b6adcf5c04a469632ee866c32f5898c5cbf810a)) ### Technically breaking change * IP Addresses returned from `ServiceInfo.parsed_addresses` are now stringified using the python `ipaddress` library which may format them differently than `socket.inet_ntop` depending on the operating system. It is recommended to use `ServiceInfo.ip_addresses_by_version` instead going forward as it offers a stronger guarantee since it returns `ipaddress` objects. ## v0.52.0 (2023-04-02) ### Feature * Small cleanups to cache cleanup interval ([#1146](https://github.com/python-zeroconf/python-zeroconf/issues/1146)) ([`b434b60`](https://github.com/python-zeroconf/python-zeroconf/commit/b434b60f14ebe8f114b7b19bb4f54081c8ae0173)) * Add ip_addresses_by_version to ServiceInfo ([#1145](https://github.com/python-zeroconf/python-zeroconf/issues/1145)) ([`524494e`](https://github.com/python-zeroconf/python-zeroconf/commit/524494edd49bd049726b19ae8ac8f6eea69a3943)) * Speed up processing records in the ServiceBrowser ([#1143](https://github.com/python-zeroconf/python-zeroconf/issues/1143)) ([`6a327d0`](https://github.com/python-zeroconf/python-zeroconf/commit/6a327d00ffb81de55b7c5b599893c789996680c1)) * Speed up matching types in the ServiceBrowser ([#1144](https://github.com/python-zeroconf/python-zeroconf/issues/1144)) ([`68871c3`](https://github.com/python-zeroconf/python-zeroconf/commit/68871c3b5569e41740a66b7d3d7fa5cc41514ea5)) * Include tests and docs in sdist archives ([#1142](https://github.com/python-zeroconf/python-zeroconf/issues/1142)) ([`da10a3b`](https://github.com/python-zeroconf/python-zeroconf/commit/da10a3b2827cee0719d3bb9152ae897f061c6e2e)) ## v0.51.0 (2023-04-01) ### Feature * Improve performance of constructing ServiceInfo ([#1141](https://github.com/python-zeroconf/python-zeroconf/issues/1141)) ([`36d5b45`](https://github.com/python-zeroconf/python-zeroconf/commit/36d5b45a4ece1dca902e9c3c79b5a63b8d9ae41f)) ## v0.50.0 (2023-04-01) ### Feature * Small speed up to handler dispatch ([#1140](https://github.com/python-zeroconf/python-zeroconf/issues/1140)) ([`5bd1b6e`](https://github.com/python-zeroconf/python-zeroconf/commit/5bd1b6e7b4dd796069461c737ded956305096307)) ## v0.49.0 (2023-04-01) ### Feature * Speed up processing incoming records ([#1139](https://github.com/python-zeroconf/python-zeroconf/issues/1139)) ([`7246a34`](https://github.com/python-zeroconf/python-zeroconf/commit/7246a344b6c0543871b40715c95c9435db4c7f81)) ## v0.48.0 (2023-04-01) ### Feature * Reduce overhead to send responses ([#1135](https://github.com/python-zeroconf/python-zeroconf/issues/1135)) ([`c4077dd`](https://github.com/python-zeroconf/python-zeroconf/commit/c4077dde6dfde9e2598eb63daa03c36063a3e7b0)) ## v0.47.4 (2023-03-20) ### Fix * Correct duplicate record entries in windows wheels by updating poetry-core ([#1134](https://github.com/python-zeroconf/python-zeroconf/issues/1134)) ([`a43055d`](https://github.com/python-zeroconf/python-zeroconf/commit/a43055d3fa258cd762c3e9394b01f8bdcb24f97e)) ## v0.47.3 (2023-02-14) ### Fix * Hold a strong reference to the query sender start task ([#1128](https://github.com/python-zeroconf/python-zeroconf/issues/1128)) ([`808c3b2`](https://github.com/python-zeroconf/python-zeroconf/commit/808c3b2194a7f499a469a9893102d328ccee83db)) ## v0.47.2 (2023-02-14) ### Fix * Missing c extensions with newer poetry ([#1129](https://github.com/python-zeroconf/python-zeroconf/issues/1129)) ([`44d7fc6`](https://github.com/python-zeroconf/python-zeroconf/commit/44d7fc6483485102f60c91d591d0d697872f8865)) ## v0.47.1 (2022-12-24) ### Fix * The equality checks for DNSPointer and DNSService should be case insensitive ([#1122](https://github.com/python-zeroconf/python-zeroconf/issues/1122)) ([`48ae77f`](https://github.com/python-zeroconf/python-zeroconf/commit/48ae77f026a96e2ca475b0ff80cb6d22207ce52f)) ## v0.47.0 (2022-12-22) ### Feature * Optimize equality checks for DNS records ([#1120](https://github.com/python-zeroconf/python-zeroconf/issues/1120)) ([`3a25ff7`](https://github.com/python-zeroconf/python-zeroconf/commit/3a25ff74bea83cd7d50888ce1ebfd7650d704bfa)) ## v0.46.0 (2022-12-21) ### Feature * Optimize the dns cache ([#1119](https://github.com/python-zeroconf/python-zeroconf/issues/1119)) ([`e80fcef`](https://github.com/python-zeroconf/python-zeroconf/commit/e80fcef967024f8e846e44b464a82a25f5550edf)) ## v0.45.0 (2022-12-20) ### Feature * Optimize construction of outgoing packets ([#1118](https://github.com/python-zeroconf/python-zeroconf/issues/1118)) ([`81e186d`](https://github.com/python-zeroconf/python-zeroconf/commit/81e186d365c018381f9b486a4dbe4e2e4b8bacbf)) ## v0.44.0 (2022-12-18) ### Feature * Optimize dns objects by adding pxd files ([#1113](https://github.com/python-zeroconf/python-zeroconf/issues/1113)) ([`919d4d8`](https://github.com/python-zeroconf/python-zeroconf/commit/919d4d875747b4fa68e25bccd5aae7f304d8a36d)) ## v0.43.0 (2022-12-18) ### Feature * Optimize incoming parser by reducing call stack ([#1116](https://github.com/python-zeroconf/python-zeroconf/issues/1116)) ([`11f3f0e`](https://github.com/python-zeroconf/python-zeroconf/commit/11f3f0e699e00c1ee3d6d8ab5e30f62525510589)) ## v0.42.0 (2022-12-18) ### Feature * Optimize incoming parser by using unpack_from ([#1115](https://github.com/python-zeroconf/python-zeroconf/issues/1115)) ([`a7d50ba`](https://github.com/python-zeroconf/python-zeroconf/commit/a7d50baab362eadd2d292df08a39de6836b41ea7)) ## v0.41.0 (2022-12-18) ### Feature * Optimize incoming parser by adding pxd files ([#1111](https://github.com/python-zeroconf/python-zeroconf/issues/1111)) ([`26efeb0`](https://github.com/python-zeroconf/python-zeroconf/commit/26efeb09783050266242542228f34eb4dd83e30c)) ## v0.40.1 (2022-12-18) ### Fix * Fix project name in pyproject.toml ([#1112](https://github.com/python-zeroconf/python-zeroconf/issues/1112)) ([`a330f62`](https://github.com/python-zeroconf/python-zeroconf/commit/a330f62040475257c4a983044e1675aeb95e030a)) ## v0.40.0 (2022-12-17) ### Feature * Drop async_timeout requirement for python 3.11+ ([#1107](https://github.com/python-zeroconf/python-zeroconf/issues/1107)) ([`1f4224e`](https://github.com/python-zeroconf/python-zeroconf/commit/1f4224ef122299235013cb81b501f8ff9a30dea1)) # 0.39.5 - This is a stub version to initialize python-semantic-release This version will not be published # 0.39.4 - Fix IP changes being missed by ServiceInfo (\#1102) @bdraco # 0.39.3 - Fix port changes not being seen by ServiceInfo (\#1100) @bdraco # 0.39.2 - Performance improvements for parsing incoming packet data (\#1095) (\#1097) @bdraco # 0.39.1 - Performance improvements for constructing outgoing packet data (\#1090) @bdraco # 0.39.0 Technically backwards incompatible: - Switch to using async\_timeout for timeouts (\#1081) @bdraco Significantly reduces the number of asyncio tasks that are created when using <span class="title-ref">ServiceInfo</span> or <span class="title-ref">AsyncServiceInfo</span> # 0.38.7 - Performance improvements for parsing incoming packet data (\#1076) @bdraco # 0.38.6 - Performance improvements for fetching ServiceInfo (\#1068) @bdraco # 0.38.5 - Fix ServiceBrowsers not getting ServiceStateChange.Removed callbacks on PTR record expire (\#1064) @bdraco ServiceBrowsers were only getting a <span class="title-ref">ServiceStateChange.Removed</span> callback when the record was sent with a TTL of 0. ServiceBrowsers now correctly get a <span class="title-ref">ServiceStateChange.Removed</span> callback when the record expires as well. - Fix missing minimum version of python 3.7 (\#1060) @stevencrader # 0.38.4 - Fix IP Address updates when hostname is uppercase (\#1057) @bdraco ServiceBrowsers would not callback updates when the ip address changed if the hostname contained uppercase characters # 0.38.3 Version bump only, no changes from 0.38.2 # 0.38.2 - Make decode errors more helpful in finding the source of the bad data (\#1052) @bdraco # 0.38.1 - Improve performance of query scheduler (\#1043) @bdraco - Avoid linear type searches in ServiceBrowsers (\#1044) @bdraco # 0.38.0 - Handle Service types that end with another service type (\#1041) @apworks1 Backwards incompatible: - Dropped Python 3.6 support (\#1009) @bdraco # 0.37.0 Technically backwards incompatible: - Adding a listener that does not inherit from RecordUpdateListener now logs an error (\#1034) @bdraco - The NotRunningException exception is now thrown when Zeroconf is not running (\#1033) @bdraco Before this change the consumer would get a timeout or an EventLoopBlocked exception when calling <span class="title-ref">ServiceInfo.\*request</span> when the instance had already been shutdown or had failed to startup. - The EventLoopBlocked exception is now thrown when a coroutine times out (\#1032) @bdraco Previously <span class="title-ref">concurrent.futures.TimeoutError</span> would have been raised instead. This is never expected to happen during normal operation. # 0.36.13 - Unavailable interfaces are now skipped during socket bind (\#1028) @bdraco - Downgraded incoming corrupt packet logging to debug (\#1029) @bdraco Warning about network traffic we have no control over is confusing to users as they think there is something wrong with zeroconf # 0.36.12 - Prevented service lookups from deadlocking if time abruptly moves backwards (\#1006) @bdraco The typical reason time moves backwards is via an ntp update # 0.36.11 No functional changes from 0.36.10. This release corrects an error in the README.rst file that prevented the build from uploading to PyPI # 0.36.10 - scope\_id is now stripped from IPv6 addresses if given (\#1020) @StevenLooman cpython 3.9 allows a suffix %scope\_id in IPv6Address. This caused an error with the existing code if it was not stripped - Optimized decoding labels from incoming packets (\#1019) @bdraco # 0.36.9 - Ensure ServiceInfo orders newest addresses first (\#1012) @bdraco This change effectively restored the behavior before 1s cache flush expire behavior described in rfc6762 section 10.2 was added for callers that rely on this. # 0.36.8 - Fixed ServiceBrowser infinite loop when zeroconf is closed before it is canceled (\#1008) @bdraco # 0.36.7 - Improved performance of responding to queries (\#994) (\#996) (\#997) @bdraco - Improved log message when receiving an invalid or corrupt packet (\#998) @bdraco # 0.36.6 - Improved performance of sending outgoing packets (\#990) @bdraco # 0.36.5 - Reduced memory usage for incoming and outgoing packets (\#987) @bdraco # 0.36.4 - Improved performance of constructing outgoing packets (\#978) (\#979) @bdraco - Deferred parsing of incoming packets when it can be avoided (\#983) @bdraco # 0.36.3 - Improved performance of parsing incoming packets (\#975) @bdraco # 0.36.2 - Include NSEC records for non-existent types when responding with addresses (\#972) (\#971) @bdraco Implements RFC6762 sec 6.2 (<http://datatracker.ietf.org/doc/html/rfc6762#section-6.2>) # 0.36.1 - Skip goodbye packets for addresses when there is another service registered with the same name (\#968) @bdraco If a ServiceInfo that used the same server name as another ServiceInfo was unregistered, goodbye packets would be sent for the addresses and would cause the other service to be seen as offline. - Fixed equality and hash for dns records with the unique bit (\#969) @bdraco These records should have the same hash and equality since the unique bit (cache flush bit) is not considered when adding or removing the records from the cache. # 0.36.0 Technically backwards incompatible: - Fill incomplete IPv6 tuples to avoid WinError on windows (\#965) @lokesh2019 Fixed \#932 # 0.35.1 - Only reschedule types if the send next time changes (\#958) @bdraco When the PTR response was seen again, the timer was being canceled and rescheduled even if the timer was for the same time. While this did not cause any breakage, it is quite inefficient. - Cache DNS record and question hashes (\#960) @bdraco The hash was being recalculated every time the object was being used in a set or dict. Since the hashes are effectively immutable, we only calculate them once now. # 0.35.0 - Reduced chance of accidental synchronization of ServiceInfo requests (\#955) @bdraco - Sort aggregated responses to increase chance of name compression (\#954) @bdraco Technically backwards incompatible: - Send unicast replies on the same socket the query was received (\#952) @bdraco When replying to a QU question, we do not know if the sending host is reachable from all of the sending sockets. We now avoid this problem by replying via the receiving socket. This was the existing behavior when <span class="title-ref">InterfaceChoice.Default</span> is set. This change extends the unicast relay behavior to used with <span class="title-ref">InterfaceChoice.Default</span> to apply when <span class="title-ref">InterfaceChoice.All</span> or interfaces are explicitly passed when instantiating a <span class="title-ref">Zeroconf</span> instance. Fixes \#951 # 0.34.3 - Fix sending immediate multicast responses (\#949) @bdraco # 0.34.2 - Coalesce aggregated multicast answers (\#945) @bdraco When the random delay is shorter than the last scheduled response, answers are now added to the same outgoing time group. This reduces traffic when we already know we will be sending a group of answers inside the random delay window described in datatracker.ietf.org/doc/html/rfc6762\#section-6.3 - Ensure ServiceInfo requests can be answered inside the default timeout with network protection (\#946) @bdraco Adjust the time windows to ensure responses that have triggered the protection against against excessive packet flooding due to software bugs or malicious attack described in RFC6762 section 6 can respond in under 1350ms to ensure ServiceInfo can ask two questions within the default timeout of 3000ms # 0.34.1 - Ensure multicast aggregation sends responses within 620ms (\#942) @bdraco Responses that trigger the protection against against excessive packet flooding due to software bugs or malicious attack described in RFC6762 section 6 could cause the multicast aggregation response to be delayed longer than 620ms (The maximum random delay of 120ms and 500ms additional for aggregation). Only responses that trigger the protection are delayed longer than 620ms # 0.34.0 - Implemented Multicast Response Aggregation (\#940) @bdraco Responses are now aggregated when possible per rules in RFC6762 section 6.4 Responses that trigger the protection against against excessive packet flooding due to software bugs or malicious attack described in RFC6762 section 6 are delayed instead of discarding as it was causing responders that implement Passive Observation Of Failures (POOF) to evict the records. Probe responses are now always sent immediately as there were cases where they would fail to be answered in time to defend a name. # 0.33.4 - Ensure zeroconf can be loaded when the system disables IPv6 (\#933) @che0 # 0.33.3 - Added support for forward dns compression pointers (\#934) @bdraco - Provide sockname when logging a protocol error (\#935) @bdraco # 0.33.2 - Handle duplicate goodbye answers in the same packet (\#928) @bdraco Solves an exception being thrown when we tried to remove the known answer from the cache when the second goodbye answer in the same packet was processed Fixed \#926 - Skip ipv6 interfaces that return ENODEV (\#930) @bdraco # 0.33.1 - Version number change only with less restrictive directory permissions Fixed \#923 # 0.33.0 This release eliminates all threading locks as all non-threadsafe operations now happen in the event loop. - Let connection\_lost close the underlying socket (\#918) @bdraco The socket was closed during shutdown before asyncio's connection\_lost handler had a chance to close it which resulted in a traceback on windows. Fixed \#917 Technically backwards incompatible: - Removed duplicate unregister\_all\_services code (\#910) @bdraco Calling Zeroconf.close from same asyncio event loop zeroconf is running in will now skip unregister\_all\_services and log a warning as this a blocking operation and is not async safe and never has been. Use AsyncZeroconf instead, or for legacy code call async\_unregister\_all\_services before Zeroconf.close # 0.32.1 - Increased timeout in ServiceInfo.request to handle loaded systems (\#895) @bdraco It can take a few seconds for a loaded system to run the <span class="title-ref">async\_request</span> coroutine when the event loop is busy, or the system is CPU bound (example being Home Assistant startup). We now add an additional <span class="title-ref">\_LOADED\_SYSTEM\_TIMEOUT</span> (10s) to the <span class="title-ref">run\_coroutine\_threadsafe</span> calls to ensure the coroutine has the total amount of time to run up to its internal timeout (default of 3000ms). Ten seconds is a bit large of a timeout; however, it is only used in cases where we wrap other timeouts. We now expect the only instance the <span class="title-ref">run\_coroutine\_threadsafe</span> result timeout will happen in a production circumstance is when someone is running a <span class="title-ref">ServiceInfo.request()</span> in a thread and another thread calls <span class="title-ref">Zeroconf.close()</span> at just the right moment that the future is never completed unless the system is so loaded that it is nearly unresponsive. The timeout for <span class="title-ref">run\_coroutine\_threadsafe</span> is the maximum time a thread can cleanly shut down when zeroconf is closed out in another thread, which should always be longer than the underlying thread operation. # 0.32.0 This release offers 100% line and branch coverage. - Made ServiceInfo first question QU (\#852) @bdraco We want an immediate response when requesting with ServiceInfo by asking a QU question; most responders will not delay the response and respond right away to our question. This also improves compatibility with split networks as we may not have been able to see the response otherwise. If the responder has not multicast the record recently, it may still choose to do so in addition to responding via unicast Reduces traffic when there are multiple zeroconf instances running on the network running ServiceBrowsers If we don't get an answer on the first try, we ask a QM question in the event, we can't receive a unicast response for some reason This change puts ServiceInfo inline with ServiceBrowser which also asks the first question as QU since ServiceInfo is commonly called from ServiceBrowser callbacks - Limited duplicate packet suppression to 1s intervals (\#841) @bdraco Only suppress duplicate packets that happen within the same second. Legitimate queriers will retry the question if they are suppressed. The limit was reduced to one second to be in line with rfc6762 - Made multipacket known answer suppression per interface (\#836) @bdraco The suppression was happening per instance of Zeroconf instead of per interface. Since the same network can be seen on multiple interfaces (usually and wifi and ethernet), this would confuse the multi-packet known answer supression since it was not expecting to get the same data more than once - New ServiceBrowsers now request QU in the first outgoing when unspecified (\#812) @bdraco <https://datatracker.ietf.org/doc/html/rfc6762#section-5.4> When we start a ServiceBrowser and zeroconf has just started up, the known answer list will be small. By asking a QU question first, it is likely that we have a large known answer list by the time we ask the QM question a second later (current default which is likely too low but would be a breaking change to increase). This reduces the amount of traffic on the network, and has the secondary advantage that most responders will answer a QU question without the typical delay answering QM questions. - IPv6 link-local addresses are now qualified with scope\_id (\#343) @ibygrave When a service is advertised on an IPv6 address where the scope is link local, i.e. fe80::/64 (see RFC 4007) the resolved IPv6 address must be extended with the scope\_id that identifies through the "%" symbol the local interface to be used when routing to that address. A new API <span class="title-ref">parsed\_scoped\_addresses()</span> is provided to return qualified addresses to avoid breaking compatibility on the existing parsed\_addresses(). - Network adapters that are disconnected are now skipped (\#327) @ZLJasonG - Fixed listeners missing initial packets if Engine starts too quickly (\#387) @bdraco When manually creating a zeroconf.Engine object, it is no longer started automatically. It must manually be started by calling .start() on the created object. The Engine thread is now started after all the listeners have been added to avoid a race condition where packets could be missed at startup. - Fixed answering matching PTR queries with the ANY query (\#618) @bdraco - Fixed lookup of uppercase names in the registry (\#597) @bdraco If the ServiceInfo was registered with an uppercase name and the query was for a lowercase name, it would not be found and vice-versa. - Fixed unicast responses from any source port (\#598) @bdraco Unicast responses were only being sent if the source port was 53, this prevented responses when testing with dig: > dig -p 5353 @224.0.0.251 media-12.local The above query will now see a response - Fixed queries for AAAA records not being answered (\#616) @bdraco - Removed second level caching from ServiceBrowsers (\#737) @bdraco The ServiceBrowser had its own cache of the last time it saw a service that was reimplementing the DNSCache and presenting a source of truth problem that lead to unexpected queries when the two disagreed. - Fixed server cache not being case-insensitive (\#731) @bdraco If the server name had uppercase chars and any of the matching records were lowercase, and the server would not be found - Fixed cache handling of records with different TTLs (\#729) @bdraco There should only be one unique record in the cache at a time as having multiple unique records will different TTLs in the cache can result in unexpected behavior since some functions returned all matching records and some fetched from the right side of the list to return the newest record. Instead we now store the records in a dict to ensure that the newest record always replaces the same unique record, and we never have a source of truth problem determining the TTL of a record from the cache. - Fixed ServiceInfo with multiple A records (\#725) @bdraco If there were multiple A records for the host, ServiceInfo would always return the last one that was in the incoming packet, which was usually not the one that was wanted. - Fixed stale unique records expiring too quickly (\#706) @bdraco Records now expire 1s in the future instead of instant removal. tools.ietf.org/html/rfc6762\#section-10.2 Queriers receiving a Multicast DNS response with a TTL of zero SHOULD NOT immediately delete the record from the cache, but instead record a TTL of 1 and then delete the record one second later. In the case of multiple Multicast DNS responders on the network described in Section 6.6 above, if one of the responders shuts down and incorrectly sends goodbye packets for its records, it gives the other cooperating responders one second to send out their own response to "rescue" the records before they expire and are deleted. - Fixed exception when unregistering a service multiple times (\#679) @bdraco - Added an AsyncZeroconfServiceTypes to mirror ZeroconfServiceTypes to zeroconf.asyncio (\#658) @bdraco - Fixed interface\_index\_to\_ip6\_address not skiping ipv4 adapters (\#651) @bdraco - Added async\_unregister\_all\_services to AsyncZeroconf (\#649) @bdraco - Fixed services not being removed from the registry when calling unregister\_all\_services (\#644) @bdraco There was a race condition where a query could be answered for a service in the registry, while goodbye packets which could result in a fresh record being broadcast after the goodbye if a query came in at just the right time. To avoid this, we now remove the services from the registry right after we generate the goodbye packet - Fixed zeroconf exception on load when the system disables IPv6 (\#624) @bdraco - Fixed the QU bit missing from for probe queries (\#609) @bdraco The bit should be set per datatracker.ietf.org/doc/html/rfc6762\#section-8.1 - Fixed the TC bit missing for query packets where the known answers span multiple packets (\#494) @bdraco - Fixed packets not being properly separated when exceeding maximum size (\#498) @bdraco Ensure that questions that exceed the max packet size are moved to the next packet. This fixes DNSQuestions being sent in multiple packets in violation of: datatracker.ietf.org/doc/html/rfc6762\#section-7.2 Ensure only one resource record is sent when a record exceeds \_MAX\_MSG\_TYPICAL datatracker.ietf.org/doc/html/rfc6762\#section-17 - Fixed PTR questions asked in uppercase not being answered (\#465) @bdraco - Added Support for context managers in Zeroconf and AsyncZeroconf (\#284) @shenek - Implemented an AsyncServiceBrowser to compliment the sync ServiceBrowser (\#429) @bdraco - Added async\_get\_service\_info to AsyncZeroconf and async\_request to AsyncServiceInfo (\#408) @bdraco - Implemented allowing passing in a sync Zeroconf instance to AsyncZeroconf (\#406) @bdraco - Fixed IPv6 setup under MacOS when binding to "" (\#392) @bdraco - Fixed ZeroconfServiceTypes.find not always cancels the ServiceBrowser (\#389) @bdraco There was a short window where the ServiceBrowser thread could be left running after Zeroconf is closed because the .join() was never waited for when a new Zeroconf object was created - Fixed duplicate packets triggering duplicate updates (\#376) @bdraco If TXT or SRV records update was already processed and then received again, it was possible for a second update to be called back in the ServiceBrowser - Fixed ServiceStateChange.Updated event happening for IPs that already existed (\#375) @bdraco - Fixed RFC6762 Section 10.2 paragraph 2 compliance (\#374) @bdraco - Reduced length of ServiceBrowser thread name with many types (\#373) @bdraco - Fixed empty answers being added in ServiceInfo.request (\#367) @bdraco - Fixed ServiceInfo not populating all AAAA records (\#366) @bdraco Use get\_all\_by\_details to ensure all records are loaded into addresses. Only load A/AAAA records from the cache once in load\_from\_cache if there is a SRV record present Move duplicate code that checked if the ServiceInfo was complete into its own function - Fixed a case where the cache list can change during iteration (\#363) @bdraco - Return task objects created by AsyncZeroconf (\#360) @nocarryr Traffic Reduction: - Added support for handling QU questions (\#621) @bdraco Implements RFC 6762 sec 5.4: Questions Requesting Unicast Responses datatracker.ietf.org/doc/html/rfc6762\#section-5.4 - Implemented protect the network against excessive packet flooding (\#619) @bdraco - Additionals are now suppressed when they are already in the answers section (\#617) @bdraco - Additionals are no longer included when the answer is suppressed by known-answer suppression (\#614) @bdraco - Implemented multi-packet known answer supression (\#687) @bdraco Implements datatracker.ietf.org/doc/html/rfc6762\#section-7.2 - Implemented efficient bucketing of queries with known answers (\#698) @bdraco - Implemented duplicate question suppression (\#770) @bdraco <http://datatracker.ietf.org/doc/html/rfc6762#section-7.3> Technically backwards incompatible: - Update internal version check to match docs (3.6+) (\#491) @bdraco Python version earlier then 3.6 were likely broken with zeroconf already, however, the version is now explicitly checked. - Update python compatibility as PyPy3 7.2 is required (\#523) @bdraco Backwards incompatible: - Drop oversize packets before processing them (\#826) @bdraco Oversized packets can quickly overwhelm the system and deny service to legitimate queriers. In practice, this is usually due to broken mDNS implementations rather than malicious actors. - Guard against excessive ServiceBrowser queries from PTR records significantly lowerthan recommended (\#824) @bdraco We now enforce a minimum TTL for PTR records to avoid ServiceBrowsers generating excessive queries refresh queries. Apple uses a 15s minimum TTL, however, we do not have the same level of rate limit and safeguards, so we use 1/4 of the recommended value. - RecordUpdateListener now uses async\_update\_records instead of update\_record (\#419, \#726) @bdraco This allows the listener to receive all the records that have been updated in a single transaction such as a packet or cache expiry. update\_record has been deprecated in favor of async\_update\_records A compatibility shim exists to ensure classes that use RecordUpdateListener as a base class continue to have update\_record called, however, they should be updated as soon as possible. A new method async\_update\_records\_complete is now called on each listener when all listeners have completed processing updates and the cache has been updated. This allows ServiceBrowsers to delay calling handlers until they are sure the cache has been updated as its a common pattern to call for ServiceInfo when a ServiceBrowser handler fires. The async\_ prefix was chosen to make it clear that these functions run in the eventloop and should never do blocking I/O. Before 0.32+ these functions ran in a select() loop and should not have been doing any blocking I/O, but it was not clear to implementors that I/O would block the loop. - Pass both the new and old records to async\_update\_records (\#792) @bdraco Pass the old\_record (cached) as the value and the new\_record (wire) to async\_update\_records instead of forcing each consumer to check the cache since we will always have the old\_record when generating the async\_update\_records call. This avoids the overhead of multiple cache lookups for each listener. # 0.31.0 - Separated cache loading from I/O in ServiceInfo and fixed cache lookup (\#356), thanks to J. Nick Koston. The ServiceInfo class gained a load\_from\_cache() method to only fetch information from Zeroconf cache (if it exists) with no IO performed. Additionally this should reduce IO in cases where cache lookups were previously incorrectly failing. # 0.30.0 - Some nice refactoring work including removal of the Reaper thread, thanks to J. Nick Koston. - Fixed a Windows-specific The requested address is not valid in its context regression, thanks to Timothee ‘TTimo’ Besset and J. Nick Koston. - Provided an asyncio-compatible service registration layer (in the zeroconf.asyncio module), thanks to J. Nick Koston. # 0.29.0 - A single socket is used for listening on responding when <span class="title-ref">InterfaceChoice.Default</span> is chosen. Thanks to J. Nick Koston. Backwards incompatible: - Dropped Python 3.5 support # 0.28.8 - Fixed the packet generation when multiple packets are necessary, previously invalid packets were generated sometimes. Patch thanks to J. Nick Koston. # 0.28.7 - Fixed the IPv6 address rendering in the browser example, thanks to Alexey Vazhnov. - Fixed a crash happening when a service is added or removed during handle\_response and improved exception handling, thanks to J. Nick Koston. # 0.28.6 - Loosened service name validation when receiving from the network this lets us handle some real world devices previously causing errors, thanks to J. Nick Koston. # 0.28.5 - Enabled ignoring duplicated messages which decreases CPU usage, thanks to J. Nick Koston. - Fixed spurious AttributeError: module 'unittest' has no attribute 'mock' in tests. # 0.28.4 - Improved cache reaper performance significantly, thanks to J. Nick Koston. - Added ServiceListener to \_\_all\_\_ as it's part of the public API, thanks to Justin Nesselrotte. # 0.28.3 - Reduced a time an internal lock is held which should eliminate deadlocks in high-traffic networks, thanks to J. Nick Koston. # 0.28.2 - Stopped asking questions we already have answers for in cache, thanks to Paul Daumlechner. - Removed initial delay before querying for service info, thanks to Erik Montnemery. # 0.28.1 - Fixed a resource leak connected to using ServiceBrowser with multiple types, thanks to 10. Nick Koston. # 0.28.0 - Improved Windows support when using socket errno checks, thanks to Sandy Patterson. - Added support for passing text addresses to ServiceInfo. - Improved logging (includes fixing an incorrect logging call) - Improved Windows compatibility by using Adapter.index from ifaddr, thanks to PhilippSelenium. - Improved Windows compatibility by stopping using socket.if\_nameindex. - Fixed an OS X edge case which should also eliminate a memory leak, thanks to Emil Styrke. Technically backwards incompatible: - `ifaddr` 0.1.7 or newer is required now. ## 0.27.1 - Improved the logging situation (includes fixing a false-positive "packets() made no progress adding records", thanks to Greg Badros) ## 0.27.0 - Large multi-resource responses are now split into separate packets which fixes a bad mdns-repeater/ChromeCast Audio interaction ending with ChromeCast Audio crash (and possibly some others) and improves RFC 6762 compliance, thanks to Greg Badros - Added a warning presented when the listener passed to ServiceBrowser lacks update\_service() callback - Added support for finding all services available in the browser example, thanks to Perry Kunder Backwards incompatible: - Removed previously deprecated ServiceInfo address constructor parameter and property ## 0.26.3 - Improved readability of logged incoming data, thanks to Erik Montnemery - Threads are given unique names now to aid debugging, thanks to Erik Montnemery - Fixed a regression where get\_service\_info() called within a listener add\_service method would deadlock, timeout and incorrectly return None, fix thanks to Erik Montnemery, but Matt Saxon and Hmmbob were also involved in debugging it. ## 0.26.2 - Added support for multiple types to ServiceBrowser, thanks to J. Nick Koston - Fixed a race condition where a listener gets a message before the lock is created, thanks to 10. Nick Koston ## 0.26.1 - Fixed a performance regression introduced in 0.26.0, thanks to J. Nick Koston (this is close in spirit to an optimization made in 0.24.5 by the same author) ## 0.26.0 - Fixed a regression where service update listener wasn't called on IP address change (it's called on SRV/A/AAAA record changes now), thanks to Matt Saxon Technically backwards incompatible: - Service update hook is no longer called on service addition (service added hook is still called), this is related to the fix above ## 0.25.1 - Eliminated 5s hangup when calling Zeroconf.close(), thanks to Erik Montnemery ## 0.25.0 - Reverted uniqueness assertions when browsing, they caused a regression Backwards incompatible: - Rationalized handling of TXT records. Non-bytes values are converted to str and encoded to bytes using UTF-8 now, None values mean value-less attributes. When receiving TXT records no decoding is performed now, keys are always bytes and values are either bytes or None in value-less attributes. ## 0.24.5 - Fixed issues with shared records being used where they shouldn't be (TXT, SRV, A records are unique now), thanks to Matt Saxon - Stopped unnecessarily excluding host-only interfaces from InterfaceChoice.all as they don't forbid multicast, thanks to Andreas Oberritter - Fixed repr() of IPv6 DNSAddress, thanks to Aldo Hoeben - Removed duplicate update messages sent to listeners, thanks to Matt Saxon - Added support for cooperating responders, thanks to Matt Saxon - Optimized handle\_response cache check, thanks to J. Nick Koston - Fixed memory leak in DNSCache, thanks to J. Nick Koston ## 0.24.4 - Fixed resetting TTL in DNSRecord.reset\_ttl(), thanks to Matt Saxon - Improved various DNS class' string representations, thanks to Jay Hogg ## 0.24.3 - Fixed import-time "TypeError: 'ellipsis' object is not iterable." on CPython 3.5.2 ## 0.24.2 - Added support for AWDL interface on macOS (needed and used by the opendrop project but should be useful in general), thanks to Milan Stute - Added missing type hints ## 0.24.1 - Applied some significant performance optimizations, thanks to Jaime van Kessel for the patch and to Ghostkeeper for performance measurements - Fixed flushing outdated cache entries when incoming record is unique, thanks to Michael Hu - Fixed handling updates of TXT records (they'd not get recorded previously), thanks to Michael Hu ## 0.24.0 - Added IPv6 support, thanks to Dmitry Tantsur - Added additional recommended records to PTR responses, thanks to Scott Mertz - Added handling of ENOTCONN being raised during shutdown when using Eventlet, thanks to Tamás Nepusz - Included the py.typed marker in the package so that type checkers know to use type hints from the source code, thanks to Dmitry Tantsur ## 0.23.0 - Added support for MyListener call getting updates to service TXT records, thanks to Matt Saxon - Added support for multiple addresses when publishing a service, getting/setting single address has become deprecated. Change thanks to Dmitry Tantsur Backwards incompatible: - Dropped Python 3.4 support ## 0.22.0 - A lot of maintenance work (tooling, typing coverage and improvements, spelling) done, thanks to Ville Skyttä - Provided saner defaults in ServiceInfo's constructor, thanks to Jorge Miranda - Fixed service removal packets not being sent on shutdown, thanks to Andrew Bonney - Added a way to define TTL-s through ServiceInfo contructor parameters, thanks to Andrew Bonney Technically backwards incompatible: - Adjusted query intervals to match RFC 6762, thanks to Andrew Bonney - Made default TTL-s match RFC 6762, thanks to Andrew Bonney ## 0.21.3 - This time really allowed incoming service names to contain underscores (patch released as part of 0.21.0 was defective) ## 0.21.2 - Fixed import-time typing-related TypeError when older typing version is used ## 0.21.1 - Fixed installation on Python 3.4 (we use typing now but there was no explicit dependency on it) ## 0.21.0 - Added an error message when importing the package using unsupported Python version - Fixed TTL handling for published service - Implemented unicast support - Fixed WSL (Windows Subsystem for Linux) compatibility - Fixed occasional UnboundLocalError issue - Fixed UTF-8 multibyte name compression - Switched from netifaces to ifaddr (pure Python) - Allowed incoming service names to contain underscores ## 0.20.0 - Dropped support for Python 2 (this includes PyPy) and 3.3 - Fixed some class' equality operators - ServiceBrowser entries are being refreshed when 'stale' now - Cache returns new records first now instead of last ## 0.19.1 - Allowed installation with netifaces \>= 0.10.6 (a bug that was concerning us got fixed) ## 0.19.0 - Technically backwards incompatible - restricted netifaces dependency version to work around a bug, see <https://github.com/jstasiak/python-zeroconf/issues/84> for details ## 0.18.0 - Dropped Python 2.6 support - Improved error handling inside code executed when Zeroconf object is being closed ## 0.17.7 - Better Handling of DNS Incoming Packets parsing exceptions - Many exceptions will now log a warning the first time they are seen - Catch and log sendto() errors - Fix/Implement duplicate name change - Fix overly strict name validation introduced in 0.17.6 - Greatly improve handling of oversized packets including: - Implement name compression per RFC1035 - Limit size of generated packets to 9000 bytes as per RFC6762 - Better handle over sized incoming packets - Increased test coverage to 95% ## 0.17.6 - Many improvements to address race conditions and exceptions during ZC() startup and shutdown, thanks to: morpav, veawor, justingiorgi, herczy, stephenrauch - Added more test coverage: strahlex, stephenrauch - Stephen Rauch contributed: - Speed up browser startup - Add ZeroconfServiceTypes() query class to discover all advertised service types - Add full validation for service names, types and subtypes - Fix for subtype browsing - Fix DNSHInfo support ## 0.17.5 - Fixed OpenBSD compatibility, thanks to Alessio Sergi - Fixed race condition on ServiceBrowser startup, thanks to gbiddison - Fixed installation on some Python 3 systems, thanks to Per Sandström - Fixed "size change during iteration" bug on Python 3, thanks to gbiddison ## 0.17.4 - Fixed support for Linux kernel versions \< 3.9 (thanks to Giovanni Harting and Luckydonald, GitHub pull request \#26) ## 0.17.3 - Fixed DNSText repr on Python 3 (it'd crash when the text was longer than 10 bytes), thanks to Paulus Schoutsen for the patch, GitHub pull request \#24 ## 0.17.2 - Fixed installation on Python 3.4.3+ (was failing because of enum34 dependency which fails to install on 3.4.3+, changed to depend on enum-compat instead; thanks to Michael Brennan for the original patch, GitHub pull request \#22) ## 0.17.1 - Fixed EADDRNOTAVAIL when attempting to use dummy network interfaces on Windows, thanks to daid ## 0.17.0 - Added some Python dependencies so it's not zero-dependencies anymore - Improved exception handling (it'll be quieter now) - Messages are listened to and sent using all available network interfaces by default (configurable); thanks to Marcus Müller - Started using logging more freely - Fixed a bug with binary strings as property values being converted to False (<https://github.com/jstasiak/python-zeroconf/pull/10>); thanks to Dr. Seuss - Added new `ServiceBrowser` event handler interface (see the examples) - PyPy3 now officially supported - Fixed ServiceInfo repr on Python 3, thanks to Yordan Miladinov ## 0.16.0 - Set up Python logging and started using it - Cleaned up code style (includes migrating from camel case to snake case) ## 0.15.1 - Fixed handling closed socket (GitHub \#4) ## 0.15 - Forked by Jakub Stasiak - Made Python 3 compatible - Added setup script, made installable by pip and uploaded to PyPI - Set up Travis build - Reformatted the code and moved files around - Stopped catching BaseException in several places, that could hide errors - Marked threads as daemonic, they won't keep application alive now ## 0.14 - Fix for SOL\_IP undefined on some systems - thanks Mike Erdely. - Cleaned up examples. - Lowercased module name. ## 0.13 - Various minor changes; see git for details. - No longer compatible with Python 2.2. Only tested with 2.5-2.7. - Fork by William McBrine. ## 0.12 - allow selection of binding interface - typo fix - Thanks A. M. Kuchlingi - removed all use of word 'Rendezvous' - this is an API change ## 0.11 - correction to comments for addListener method - support for new record types seen from OS X - IPv6 address - hostinfo - ignore unknown DNS record types - fixes to name decoding - works alongside other processes using port 5353 (e.g. on Mac OS X) - tested against Mac OS X 10.3.2's mDNSResponder - corrections to removal of list entries for service browser ## 0.10 - Jonathon Paisley contributed these corrections: - always multicast replies, even when query is unicast - correct a pointer encoding problem - can now write records in any order - traceback shown on failure - better TXT record parsing - server is now separate from name - can cancel a service browser - modified some unit tests to accommodate these changes ## 0.09 - remove all records on service unregistration - fix DOS security problem with readName ## 0.08 - changed licensing to LGPL ## 0.07 - faster shutdown on engine - pointer encoding of outgoing names - ServiceBrowser now works - new unit tests ## 0.06 - small improvements with unit tests - added defined exception types - new style objects - fixed hostname/interface problem - fixed socket timeout problem - fixed add\_service\_listener() typo bug - using select() for socket reads - tested on Debian unstable with Python 2.2.2 ## 0.05 - ensure case insensitivty on domain names - support for unicast DNS queries ## 0.04 - added some unit tests - added \_\_ne\_\_ adjuncts where required - ensure names end in '.local.' - timeout on receiving socket for clean shutdown 07070100000008000081A40000000000000000000000016619D4CC00005F3C000000000000000000000000000000000000002000000000python-zeroconf-0.132.2/COPYING GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, 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. [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 07070100000009000081A40000000000000000000000016619D4CC00000036000000000000000000000000000000000000002400000000python-zeroconf-0.132.2/MANIFEST.ininclude README.rst include COPYING global-exclude *.c 0707010000000A000081A40000000000000000000000016619D4CC0000004F000000000000000000000000000000000000002100000000python-zeroconf-0.132.2/Makefile# version: 1.3 test: poetry run pytest --durations=20 --timeout=60 -v tests 0707010000000B000081A40000000000000000000000016619D4CC00001137000000000000000000000000000000000000002300000000python-zeroconf-0.132.2/README.rstpython-zeroconf =============== .. image:: https://github.com/python-zeroconf/python-zeroconf/workflows/CI/badge.svg :target: https://github.com/python-zeroconf/python-zeroconf?query=workflow%3ACI+branch%3Amaster .. image:: https://img.shields.io/pypi/v/zeroconf.svg :target: https://pypi.python.org/pypi/zeroconf .. image:: https://codecov.io/gh/python-zeroconf/python-zeroconf/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-zeroconf/python-zeroconf `Documentation <https://python-zeroconf.readthedocs.io/en/latest/>`_. This is fork of pyzeroconf, Multicast DNS Service Discovery for Python, originally by Paul Scott-Murphy (https://github.com/paulsm/pyzeroconf), modified by William McBrine (https://github.com/wmcbrine/pyzeroconf). The original William McBrine's fork note:: This fork is used in all of my TiVo-related projects: HME for Python (and therefore HME/VLC), Network Remote, Remote Proxy, and pyTivo. Before this, I was tracking the changes for zeroconf.py in three separate repos. I figured I should have an authoritative source. Although I make changes based on my experience with TiVos, I expect that they're generally applicable. This version also includes patches found on the now-defunct (?) Launchpad repo of pyzeroconf, and elsewhere around the net -- not always well-documented, sorry. Compatible with: * Bonjour * Avahi Compared to some other Zeroconf/Bonjour/Avahi Python packages, python-zeroconf: * isn't tied to Bonjour or Avahi * doesn't use D-Bus * doesn't force you to use particular event loop or Twisted (asyncio is used under the hood but not required) * is pip-installable * has PyPI distribution * has an optional cython extension for performance (pure python is supported as well) Python compatibility -------------------- * CPython 3.8+ * PyPy3.8 7.3+ Versioning ---------- This project uses semantic versioning. Status ------ This project is actively maintained. Traffic Reduction ----------------- Before version 0.32, most traffic reduction techniques described in https://datatracker.ietf.org/doc/html/rfc6762#section-7 where not implemented which could lead to excessive network traffic. It is highly recommended that version 0.32 or later is used if this is a concern. IPv6 support ------------ IPv6 support is relatively new and currently limited, specifically: * `InterfaceChoice.All` is an alias for `InterfaceChoice.Default` on non-POSIX systems. * Dual-stack IPv6 sockets are used, which may not be supported everywhere (some BSD variants do not have them). * Listening on localhost (`::1`) does not work. Help with understanding why is appreciated. How to get python-zeroconf? =========================== * PyPI page https://pypi.org/project/zeroconf/ * GitHub project https://github.com/python-zeroconf/python-zeroconf The easiest way to install python-zeroconf is using pip:: pip install zeroconf How do I use it? ================ Here's an example of browsing for a service: .. code-block:: python from zeroconf import ServiceBrowser, ServiceListener, Zeroconf class MyListener(ServiceListener): def update_service(self, zc: Zeroconf, type_: str, name: str) -> None: print(f"Service {name} updated") def remove_service(self, zc: Zeroconf, type_: str, name: str) -> None: print(f"Service {name} removed") def add_service(self, zc: Zeroconf, type_: str, name: str) -> None: info = zc.get_service_info(type_, name) print(f"Service {name} added, service info: {info}") zeroconf = Zeroconf() listener = MyListener() browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener) try: input("Press enter to exit...\n\n") finally: zeroconf.close() .. note:: Discovery and service registration use *all* available network interfaces by default. If you want to customize that you need to specify ``interfaces`` argument when constructing ``Zeroconf`` object (see the code for details). If you don't know the name of the service you need to browse for, try: .. code-block:: python from zeroconf import ZeroconfServiceTypes print('\n'.join(ZeroconfServiceTypes.find())) See examples directory for more. Changelog ========= `Changelog <CHANGELOG.md>`_ License ======= LGPL, see COPYING file for details. 0707010000000C000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000001E00000000python-zeroconf-0.132.2/bench0707010000000D000081A40000000000000000000000016619D4CC0000022A000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/bench/create_destory.py"""Benchmark for AsyncZeroconf.""" import asyncio import time from zeroconf.asyncio import AsyncZeroconf iterations = 10000 async def _create_destroy(count: int) -> None: for _ in range(count): async with AsyncZeroconf() as zc: await zc.zeroconf.async_wait_for_start() async def _run() -> None: start = time.perf_counter() await _create_destroy(iterations) duration = time.perf_counter() - start print(f"Creating and destroying {iterations} Zeroconf instances took {duration} seconds") asyncio.run(_run()) 0707010000000E000081A40000000000000000000000016619D4CC00001857000000000000000000000000000000000000002A00000000python-zeroconf-0.132.2/bench/incoming.py"""Benchmark for DNSIncoming.""" import socket import timeit from typing import List from zeroconf import ( DNSAddress, DNSIncoming, DNSNsec, DNSOutgoing, DNSService, DNSText, const, ) def generate_packets() -> List[bytes]: out = DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA) address = socket.inet_pton(socket.AF_INET, "192.168.208.5") additionals = [ { "name": "HASS Bridge ZJWH FF5137._hap._tcp.local.", "address": address, "port": 51832, "text": b"\x13md=HASS Bridge" b" ZJWH\x06pv=1.0\x14id=01:6B:30:FF:51:37\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=L0m/aQ==", }, { "name": "HASS Bridge 3K9A C2582A._hap._tcp.local.", "address": address, "port": 51834, "text": b"\x13md=HASS Bridge" b" 3K9A\x06pv=1.0\x14id=E2:AA:5B:C2:58:2A\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=b2CnzQ==", }, { "name": "Master Bed TV CEDB27._hap._tcp.local.", "address": address, "port": 51830, "text": b"\x10md=Master Bed" b" TV\x06pv=1.0\x14id=9E:B7:44:CE:DB:27\x05c#=18\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=CVj1kw==", }, { "name": "Living Room TV 921B77._hap._tcp.local.", "address": address, "port": 51833, "text": b"\x11md=Living Room" b" TV\x06pv=1.0\x14id=11:61:E7:92:1B:77\x05c#=17\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=qU77SQ==", }, { "name": "HASS Bridge ZC8X FF413D._hap._tcp.local.", "address": address, "port": 51829, "text": b"\x13md=HASS Bridge" b" ZC8X\x06pv=1.0\x14id=96:14:45:FF:41:3D\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=b0QZlg==", }, { "name": "HASS Bridge WLTF 4BE61F._hap._tcp.local.", "address": address, "port": 51837, "text": b"\x13md=HASS Bridge" b" WLTF\x06pv=1.0\x14id=E0:E7:98:4B:E6:1F\x04c#=2\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=ahAISA==", }, { "name": "FrontdoorCamera 8941D1._hap._tcp.local.", "address": address, "port": 54898, "text": b"\x12md=FrontdoorCamera\x06pv=1.0\x14id=9F:B7:DC:89:41:D1\x04c#=2\x04" b"s#=1\x04ff=0\x04ci=2\x04sf=0\x0bsh=0+MXmA==", }, { "name": "HASS Bridge W9DN 5B5CC5._hap._tcp.local.", "address": address, "port": 51836, "text": b"\x13md=HASS Bridge" b" W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=6fLM5A==", }, { "name": "HASS Bridge Y9OO EFF0A7._hap._tcp.local.", "address": address, "port": 51838, "text": b"\x13md=HASS Bridge" b" Y9OO\x06pv=1.0\x14id=D3:FE:98:EF:F0:A7\x04c#=2\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=u3bdfw==", }, { "name": "Snooze Room TV 6B89B0._hap._tcp.local.", "address": address, "port": 51835, "text": b"\x11md=Snooze Room" b" TV\x06pv=1.0\x14id=5F:D5:70:6B:89:B0\x05c#=17\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=xNTqsg==", }, { "name": "AlexanderHomeAssistant 74651D._hap._tcp.local.", "address": address, "port": 54811, "text": b"\x19md=AlexanderHomeAssistant\x06pv=1.0\x14id=59:8A:0B:74:65:1D\x05" b"c#=14\x04s#=1\x04ff=0\x04ci=2\x04sf=0\x0bsh=ccZLPA==", }, { "name": "HASS Bridge OS95 39C053._hap._tcp.local.", "address": address, "port": 51831, "text": b"\x13md=HASS Bridge" b" OS95\x06pv=1.0\x14id=7E:8C:E6:39:C0:53\x05c#=12\x04s#=1\x04ff=0\x04ci=2" b"\x04sf=0\x0bsh=Xfe5LQ==", }, ] out.add_answer_at_time( DNSText( "HASS Bridge W9DN 5B5CC5._hap._tcp.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, b'\x13md=HASS Bridge W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1' b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) for record in additionals: out.add_additional_answer( DNSService( record["name"], # type: ignore const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, record["port"], # type: ignore record["name"], # type: ignore ) ) out.add_additional_answer( DNSText( record["name"], # type: ignore const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, record["text"], # type: ignore ) ) out.add_additional_answer( DNSAddress( record["name"], # type: ignore const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, record["address"], # type: ignore ) ) out.add_additional_answer( DNSNsec( record["name"], # type: ignore const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, record["name"], # type: ignore [const._TYPE_TXT, const._TYPE_SRV], ) ) return out.packets() packets = generate_packets() def parse_incoming_message() -> None: for packet in packets: DNSIncoming(packet).answers break count = 100000 time = timeit.Timer(parse_incoming_message).timeit(count) print(f"Parsing {count} incoming messages took {time} seconds") 0707010000000F000081A40000000000000000000000016619D4CC000016E8000000000000000000000000000000000000002A00000000python-zeroconf-0.132.2/bench/outgoing.py"""Benchmark for DNSOutgoing.""" import socket import timeit from zeroconf import DNSAddress, DNSOutgoing, DNSService, DNSText, const from zeroconf._protocol.outgoing import State def generate_packets() -> DNSOutgoing: out = DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA) address = socket.inet_pton(socket.AF_INET, "192.168.208.5") additionals = [ { "name": "HASS Bridge ZJWH FF5137._hap._tcp.local.", "address": address, "port": 51832, "text": b"\x13md=HASS Bridge" b" ZJWH\x06pv=1.0\x14id=01:6B:30:FF:51:37\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=L0m/aQ==", }, { "name": "HASS Bridge 3K9A C2582A._hap._tcp.local.", "address": address, "port": 51834, "text": b"\x13md=HASS Bridge" b" 3K9A\x06pv=1.0\x14id=E2:AA:5B:C2:58:2A\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=b2CnzQ==", }, { "name": "Master Bed TV CEDB27._hap._tcp.local.", "address": address, "port": 51830, "text": b"\x10md=Master Bed" b" TV\x06pv=1.0\x14id=9E:B7:44:CE:DB:27\x05c#=18\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=CVj1kw==", }, { "name": "Living Room TV 921B77._hap._tcp.local.", "address": address, "port": 51833, "text": b"\x11md=Living Room" b" TV\x06pv=1.0\x14id=11:61:E7:92:1B:77\x05c#=17\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=qU77SQ==", }, { "name": "HASS Bridge ZC8X FF413D._hap._tcp.local.", "address": address, "port": 51829, "text": b"\x13md=HASS Bridge" b" ZC8X\x06pv=1.0\x14id=96:14:45:FF:41:3D\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=b0QZlg==", }, { "name": "HASS Bridge WLTF 4BE61F._hap._tcp.local.", "address": address, "port": 51837, "text": b"\x13md=HASS Bridge" b" WLTF\x06pv=1.0\x14id=E0:E7:98:4B:E6:1F\x04c#=2\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=ahAISA==", }, { "name": "FrontdoorCamera 8941D1._hap._tcp.local.", "address": address, "port": 54898, "text": b"\x12md=FrontdoorCamera\x06pv=1.0\x14id=9F:B7:DC:89:41:D1\x04c#=2\x04" b"s#=1\x04ff=0\x04ci=2\x04sf=0\x0bsh=0+MXmA==", }, { "name": "HASS Bridge W9DN 5B5CC5._hap._tcp.local.", "address": address, "port": 51836, "text": b"\x13md=HASS Bridge" b" W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=6fLM5A==", }, { "name": "HASS Bridge Y9OO EFF0A7._hap._tcp.local.", "address": address, "port": 51838, "text": b"\x13md=HASS Bridge" b" Y9OO\x06pv=1.0\x14id=D3:FE:98:EF:F0:A7\x04c#=2\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=u3bdfw==", }, { "name": "Snooze Room TV 6B89B0._hap._tcp.local.", "address": address, "port": 51835, "text": b"\x11md=Snooze Room" b" TV\x06pv=1.0\x14id=5F:D5:70:6B:89:B0\x05c#=17\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=xNTqsg==", }, { "name": "AlexanderHomeAssistant 74651D._hap._tcp.local.", "address": address, "port": 54811, "text": b"\x19md=AlexanderHomeAssistant\x06pv=1.0\x14id=59:8A:0B:74:65:1D\x05" b"c#=14\x04s#=1\x04ff=0\x04ci=2\x04sf=0\x0bsh=ccZLPA==", }, { "name": "HASS Bridge OS95 39C053._hap._tcp.local.", "address": address, "port": 51831, "text": b"\x13md=HASS Bridge" b" OS95\x06pv=1.0\x14id=7E:8C:E6:39:C0:53\x05c#=12\x04s#=1\x04ff=0\x04ci=2" b"\x04sf=0\x0bsh=Xfe5LQ==", }, ] out.add_answer_at_time( DNSText( "HASS Bridge W9DN 5B5CC5._hap._tcp.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, b'\x13md=HASS Bridge W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1' b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) for record in additionals: out.add_additional_answer( DNSService( record["name"], # type: ignore const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, record["port"], # type: ignore record["name"], # type: ignore ) ) out.add_additional_answer( DNSText( record["name"], # type: ignore const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, record["text"], # type: ignore ) ) out.add_additional_answer( DNSAddress( record["name"], # type: ignore const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, record["address"], # type: ignore ) ) return out out = generate_packets() def make_outgoing_message() -> None: out.packets() out.state = State.init.value out.finished = False out._reset_for_next_packet() count = 100000 time = timeit.Timer(make_outgoing_message).timeit(count) print(f"Construction {count} outgoing messages took {time} seconds") 07070100000010000081A40000000000000000000000016619D4CC000001FC000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/bench/txt_properties.pyimport timeit from zeroconf import ServiceInfo info = ServiceInfo( "_test._tcp.local.", "test._test._tcp.local.", properties=( b"\x19md=AlexanderHomeAssistant\x06pv=1.0\x14id=59:8A:0B:74:65:1D\x05" b"c#=14\x04s#=1\x04ff=0\x04ci=2\x04sf=0\x0bsh=ccZLPA==" ), ) def process_properties() -> None: info._properties = None info.properties count = 100000 time = timeit.Timer(process_properties).timeit(count) print(f"Processing {count} properties took {time} seconds") 07070100000011000081A40000000000000000000000016619D4CC000007D5000000000000000000000000000000000000002500000000python-zeroconf-0.132.2/build_ext.py"""Build optional cython modules.""" import os from distutils.command.build_ext import build_ext from typing import Any class BuildExt(build_ext): def build_extensions(self) -> None: try: super().build_extensions() except Exception: pass def build(setup_kwargs: Any) -> None: if os.environ.get("SKIP_CYTHON", False): return try: from Cython.Build import cythonize setup_kwargs.update( dict( ext_modules=cythonize( [ "src/zeroconf/_dns.py", "src/zeroconf/_cache.py", "src/zeroconf/_history.py", "src/zeroconf/_record_update.py", "src/zeroconf/_listener.py", "src/zeroconf/_protocol/incoming.py", "src/zeroconf/_protocol/outgoing.py", "src/zeroconf/_handlers/answers.py", "src/zeroconf/_handlers/record_manager.py", "src/zeroconf/_handlers/multicast_outgoing_queue.py", "src/zeroconf/_handlers/query_handler.py", "src/zeroconf/_services/__init__.py", "src/zeroconf/_services/browser.py", "src/zeroconf/_services/info.py", "src/zeroconf/_services/registry.py", "src/zeroconf/_updates.py", "src/zeroconf/_utils/ipaddress.py", "src/zeroconf/_utils/time.py", ], compiler_directives={"language_level": "3"}, # Python 3 ), cmdclass=dict(build_ext=BuildExt), ) ) setup_kwargs["exclude_package_data"] = {pkg: ["*.c"] for pkg in setup_kwargs["packages"]} except Exception: if os.environ.get("REQUIRE_CYTHON"): raise pass 07070100000012000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000001D00000000python-zeroconf-0.132.2/docs07070100000013000081A40000000000000000000000016619D4CC00001A72000000000000000000000000000000000000002600000000python-zeroconf-0.132.2/docs/Makefile# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/zeroconf.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/zeroconf.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/zeroconf" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/zeroconf" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 07070100000014000081A40000000000000000000000016619D4CC000000EA000000000000000000000000000000000000002500000000python-zeroconf-0.132.2/docs/api.rstpython-zeroconf API reference ============================= .. automodule:: zeroconf :members: :undoc-members: :show-inheritance: .. automodule:: zeroconf.asyncio :members: :undoc-members: :show-inheritance: 07070100000015000081A40000000000000000000000016619D4CC00001FD1000000000000000000000000000000000000002500000000python-zeroconf-0.132.2/docs/conf.py# # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. from typing import Any, Dict import zeroconf # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'python-zeroconf' copyright = 'python-zeroconf authors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = zeroconf.__version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { 'index': ('sidebar.html', 'sourcelink.html', 'searchbox.html'), '**': ('localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'), } # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'zeroconfdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements: Dict[str, Any] = {} # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). # latex_documents = [] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). # man_pages = [] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) # texinfo_documents = [] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} def setup(app): # type: ignore[no-untyped-def] app.connect('autodoc-skip-member', skip_member) def skip_member(app, what, name, obj, skip, options): # type: ignore[no-untyped-def] return ( skip or getattr(obj, '__doc__', None) is None or getattr(obj, '__private__', False) is True or getattr(getattr(obj, '__func__', None), '__private__', False) is True ) 07070100000016000081A40000000000000000000000016619D4CC000003DF000000000000000000000000000000000000002700000000python-zeroconf-0.132.2/docs/index.rstWelcome to python-zeroconf documentation! ========================================= .. image:: https://github.com/jstasiak/python-zeroconf/workflows/CI/badge.svg :target: https://github.com/jstasiak/python-zeroconf?query=workflow%3ACI+branch%3Amaster .. image:: https://img.shields.io/pypi/v/zeroconf.svg :target: https://pypi.python.org/pypi/zeroconf .. image:: https://codecov.io/gh/jstasiak/python-zeroconf/branch/master/graph/badge.svg :target: https://codecov.io/gh/jstasiak/python-zeroconf GitHub (code repository, issues): https://github.com/jstasiak/python-zeroconf PyPI (installable, stable distributions): https://pypi.org/project/zeroconf. You can install python-zeroconf using pip:: pip install zeroconf python-zeroconf works with CPython 3.6+ and PyPy 3 implementing Python 3.6+. Contents -------- .. toctree:: :maxdepth: 1 api See `the project's README <https://github.com/jstasiak/python-zeroconf/blob/master/README.rst>`_ for more information. 07070100000017000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002100000000python-zeroconf-0.132.2/examples07070100000018000081A40000000000000000000000016619D4CC000010E5000000000000000000000000000000000000003800000000python-zeroconf-0.132.2/examples/async_apple_scanner.py#!/usr/bin/env python3 """ Scan for apple devices. """ import argparse import asyncio import logging from typing import Any, Optional, cast from zeroconf import DNSQuestionType, IPVersion, ServiceStateChange, Zeroconf from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconf HOMESHARING_SERVICE: str = "_appletv-v2._tcp.local." DEVICE_SERVICE: str = "_touch-able._tcp.local." MEDIAREMOTE_SERVICE: str = "_mediaremotetv._tcp.local." AIRPLAY_SERVICE: str = "_airplay._tcp.local." COMPANION_SERVICE: str = "_companion-link._tcp.local." RAOP_SERVICE: str = "_raop._tcp.local." AIRPORT_ADMIN_SERVICE: str = "_airport._tcp.local." DEVICE_INFO_SERVICE: str = "_device-info._tcp.local." ALL_SERVICES = [ HOMESHARING_SERVICE, DEVICE_SERVICE, MEDIAREMOTE_SERVICE, AIRPLAY_SERVICE, COMPANION_SERVICE, RAOP_SERVICE, AIRPORT_ADMIN_SERVICE, DEVICE_INFO_SERVICE, ] log = logging.getLogger(__name__) def async_on_service_state_change( zeroconf: Zeroconf, service_type: str, name: str, state_change: ServiceStateChange ) -> None: print(f"Service {name} of type {service_type} state changed: {state_change}") if state_change is not ServiceStateChange.Added: return base_name = name[: -len(service_type) - 1] device_name = f"{base_name}.{DEVICE_INFO_SERVICE}" asyncio.ensure_future(_async_show_service_info(zeroconf, service_type, name)) # Also probe for device info asyncio.ensure_future(_async_show_service_info(zeroconf, DEVICE_INFO_SERVICE, device_name)) async def _async_show_service_info(zeroconf: Zeroconf, service_type: str, name: str) -> None: info = AsyncServiceInfo(service_type, name) await info.async_request(zeroconf, 3000, question_type=DNSQuestionType.QU) print("Info from zeroconf.get_service_info: %r" % (info)) if info: addresses = ["%s:%d" % (addr, cast(int, info.port)) for addr in info.parsed_addresses()] print(" Name: %s" % name) print(" Addresses: %s" % ", ".join(addresses)) print(" Weight: %d, priority: %d" % (info.weight, info.priority)) print(f" Server: {info.server}") if info.properties: print(" Properties are:") for key, value in info.properties.items(): print(f" {key!r}: {value!r}") else: print(" No properties") else: print(" No info") print('\n') class AsyncAppleScanner: def __init__(self, args: Any) -> None: self.args = args self.aiobrowser: Optional[AsyncServiceBrowser] = None self.aiozc: Optional[AsyncZeroconf] = None async def async_run(self) -> None: self.aiozc = AsyncZeroconf(ip_version=ip_version) await self.aiozc.zeroconf.async_wait_for_start() print("\nBrowsing %s service(s), press Ctrl-C to exit...\n" % ALL_SERVICES) kwargs = {'handlers': [async_on_service_state_change], 'question_type': DNSQuestionType.QU} if self.args.target: kwargs["addr"] = self.args.target self.aiobrowser = AsyncServiceBrowser(self.aiozc.zeroconf, ALL_SERVICES, **kwargs) # type: ignore while True: await asyncio.sleep(1) async def async_close(self) -> None: assert self.aiozc is not None assert self.aiobrowser is not None await self.aiobrowser.async_cancel() await self.aiozc.async_close() if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') version_group = parser.add_mutually_exclusive_group() version_group.add_argument('--target', help='Unicast target') version_group.add_argument('--v6', action='store_true') version_group.add_argument('--v6-only', action='store_true') args = parser.parse_args() if args.debug: logging.getLogger('zeroconf').setLevel(logging.DEBUG) if args.v6: ip_version = IPVersion.All elif args.v6_only: ip_version = IPVersion.V6Only else: ip_version = IPVersion.V4Only loop = asyncio.get_event_loop() runner = AsyncAppleScanner(args) try: loop.run_until_complete(runner.async_run()) except KeyboardInterrupt: loop.run_until_complete(runner.async_close()) 07070100000019000081A40000000000000000000000016619D4CC00000E18000000000000000000000000000000000000003200000000python-zeroconf-0.132.2/examples/async_browser.py#!/usr/bin/env python3 """ Example of browsing for a service. The default is HTTP and HAP; use --find to search for all available services in the network """ import argparse import asyncio import logging from typing import Any, Optional, cast from zeroconf import IPVersion, ServiceStateChange, Zeroconf from zeroconf.asyncio import ( AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconf, AsyncZeroconfServiceTypes, ) def async_on_service_state_change( zeroconf: Zeroconf, service_type: str, name: str, state_change: ServiceStateChange ) -> None: print(f"Service {name} of type {service_type} state changed: {state_change}") if state_change is not ServiceStateChange.Added: return asyncio.ensure_future(async_display_service_info(zeroconf, service_type, name)) async def async_display_service_info(zeroconf: Zeroconf, service_type: str, name: str) -> None: info = AsyncServiceInfo(service_type, name) await info.async_request(zeroconf, 3000) print("Info from zeroconf.get_service_info: %r" % (info)) if info: addresses = ["%s:%d" % (addr, cast(int, info.port)) for addr in info.parsed_scoped_addresses()] print(" Name: %s" % name) print(" Addresses: %s" % ", ".join(addresses)) print(" Weight: %d, priority: %d" % (info.weight, info.priority)) print(f" Server: {info.server}") if info.properties: print(" Properties are:") for key, value in info.properties.items(): print(f" {key!r}: {value!r}") else: print(" No properties") else: print(" No info") print('\n') class AsyncRunner: def __init__(self, args: Any) -> None: self.args = args self.aiobrowser: Optional[AsyncServiceBrowser] = None self.aiozc: Optional[AsyncZeroconf] = None async def async_run(self) -> None: self.aiozc = AsyncZeroconf(ip_version=ip_version) services = ["_http._tcp.local.", "_hap._tcp.local."] if self.args.find: services = list( await AsyncZeroconfServiceTypes.async_find(aiozc=self.aiozc, ip_version=ip_version) ) print("\nBrowsing %s service(s), press Ctrl-C to exit...\n" % services) self.aiobrowser = AsyncServiceBrowser( self.aiozc.zeroconf, services, handlers=[async_on_service_state_change] ) while True: await asyncio.sleep(1) async def async_close(self) -> None: assert self.aiozc is not None assert self.aiobrowser is not None await self.aiobrowser.async_cancel() await self.aiozc.async_close() if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--find', action='store_true', help='Browse all available services') version_group = parser.add_mutually_exclusive_group() version_group.add_argument('--v6', action='store_true') version_group.add_argument('--v6-only', action='store_true') args = parser.parse_args() if args.debug: logging.getLogger('zeroconf').setLevel(logging.DEBUG) if args.v6: ip_version = IPVersion.All elif args.v6_only: ip_version = IPVersion.V6Only else: ip_version = IPVersion.V4Only loop = asyncio.get_event_loop() runner = AsyncRunner(args) try: loop.run_until_complete(runner.async_run()) except KeyboardInterrupt: loop.run_until_complete(runner.async_close()) 0707010000001A000081A40000000000000000000000016619D4CC000009F5000000000000000000000000000000000000003700000000python-zeroconf-0.132.2/examples/async_registration.py#!/usr/bin/env python3 """Example of announcing 250 services (in this case, a fake HTTP server).""" import argparse import asyncio import logging import socket from typing import List, Optional from zeroconf import IPVersion from zeroconf.asyncio import AsyncServiceInfo, AsyncZeroconf class AsyncRunner: def __init__(self, ip_version: IPVersion) -> None: self.ip_version = ip_version self.aiozc: Optional[AsyncZeroconf] = None async def register_services(self, infos: List[AsyncServiceInfo]) -> None: self.aiozc = AsyncZeroconf(ip_version=self.ip_version) tasks = [self.aiozc.async_register_service(info) for info in infos] background_tasks = await asyncio.gather(*tasks) await asyncio.gather(*background_tasks) print("Finished registration, press Ctrl-C to exit...") while True: await asyncio.sleep(1) async def unregister_services(self, infos: List[AsyncServiceInfo]) -> None: assert self.aiozc is not None tasks = [self.aiozc.async_unregister_service(info) for info in infos] background_tasks = await asyncio.gather(*tasks) await asyncio.gather(*background_tasks) await self.aiozc.async_close() if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') version_group = parser.add_mutually_exclusive_group() version_group.add_argument('--v6', action='store_true') version_group.add_argument('--v6-only', action='store_true') args = parser.parse_args() if args.debug: logging.getLogger('zeroconf').setLevel(logging.DEBUG) if args.v6: ip_version = IPVersion.All elif args.v6_only: ip_version = IPVersion.V6Only else: ip_version = IPVersion.V4Only infos = [] for i in range(250): infos.append( AsyncServiceInfo( "_http._tcp.local.", f"Paul's Test Web Site {i}._http._tcp.local.", addresses=[socket.inet_aton("127.0.0.1")], port=80, properties={'path': '/~paulsm/'}, server=f"zcdemohost-{i}.local.", ) ) print("Registration of 250 services...") loop = asyncio.get_event_loop() runner = AsyncRunner(ip_version) try: loop.run_until_complete(runner.register_services(infos)) except KeyboardInterrupt: loop.run_until_complete(runner.unregister_services(infos)) 0707010000001B000081A40000000000000000000000016619D4CC00000DA1000000000000000000000000000000000000003F00000000python-zeroconf-0.132.2/examples/async_service_info_request.py#!/usr/bin/env python3 """Example of perodic dump of homekit services. This example is useful when a user wants an ondemand list of HomeKit devices on the network. """ import argparse import asyncio import logging from typing import Any, List, Optional, cast from zeroconf import IPVersion, ServiceBrowser, ServiceStateChange, Zeroconf from zeroconf.asyncio import AsyncServiceInfo, AsyncZeroconf HAP_TYPE = "_hap._tcp.local." async def async_watch_services(aiozc: AsyncZeroconf) -> None: zeroconf = aiozc.zeroconf while True: await asyncio.sleep(5) infos: List[AsyncServiceInfo] = [] for name in zeroconf.cache.names(): if not name.endswith(HAP_TYPE): continue infos.append(AsyncServiceInfo(HAP_TYPE, name)) tasks = [info.async_request(aiozc.zeroconf, 3000) for info in infos] await asyncio.gather(*tasks) for info in infos: print("Info for %s" % (info.name)) if info: addresses = ["%s:%d" % (addr, cast(int, info.port)) for addr in info.parsed_addresses()] print(" Addresses: %s" % ", ".join(addresses)) print(" Weight: %d, priority: %d" % (info.weight, info.priority)) print(f" Server: {info.server}") if info.properties: print(" Properties are:") for key, value in info.properties.items(): print(f" {key!r}: {value!r}") else: print(" No properties") else: print(" No info") print('\n') class AsyncRunner: def __init__(self, args: Any) -> None: self.args = args self.threaded_browser: Optional[ServiceBrowser] = None self.aiozc: Optional[AsyncZeroconf] = None async def async_run(self) -> None: self.aiozc = AsyncZeroconf(ip_version=ip_version) assert self.aiozc is not None def on_service_state_change( zeroconf: Zeroconf, service_type: str, state_change: ServiceStateChange, name: str ) -> None: """Dummy handler.""" self.threaded_browser = ServiceBrowser( self.aiozc.zeroconf, [HAP_TYPE], handlers=[on_service_state_change] ) await async_watch_services(self.aiozc) async def async_close(self) -> None: assert self.aiozc is not None assert self.threaded_browser is not None self.threaded_browser.cancel() await self.aiozc.async_close() if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') version_group = parser.add_mutually_exclusive_group() version_group.add_argument('--v6', action='store_true') version_group.add_argument('--v6-only', action='store_true') args = parser.parse_args() if args.debug: logging.getLogger('zeroconf').setLevel(logging.DEBUG) if args.v6: ip_version = IPVersion.All elif args.v6_only: ip_version = IPVersion.V6Only else: ip_version = IPVersion.V4Only print(f"Services with {HAP_TYPE} will be shown every 5s, press Ctrl-C to exit...") loop = asyncio.get_event_loop() runner = AsyncRunner(args) try: loop.run_until_complete(runner.async_run()) except KeyboardInterrupt: loop.run_until_complete(runner.async_close()) 0707010000001C000081ED0000000000000000000000016619D4CC00000A53000000000000000000000000000000000000002C00000000python-zeroconf-0.132.2/examples/browser.py#!/usr/bin/env python3 """ Example of browsing for a service. The default is HTTP and HAP; use --find to search for all available services in the network """ import argparse import logging from time import sleep from typing import cast from zeroconf import ( IPVersion, ServiceBrowser, ServiceStateChange, Zeroconf, ZeroconfServiceTypes, ) def on_service_state_change( zeroconf: Zeroconf, service_type: str, name: str, state_change: ServiceStateChange ) -> None: print(f"Service {name} of type {service_type} state changed: {state_change}") if state_change is ServiceStateChange.Added: info = zeroconf.get_service_info(service_type, name) print("Info from zeroconf.get_service_info: %r" % (info)) if info: addresses = ["%s:%d" % (addr, cast(int, info.port)) for addr in info.parsed_scoped_addresses()] print(" Addresses: %s" % ", ".join(addresses)) print(" Weight: %d, priority: %d" % (info.weight, info.priority)) print(f" Server: {info.server}") if info.properties: print(" Properties are:") for key, value in info.properties.items(): print(f" {key!r}: {value!r}") else: print(" No properties") else: print(" No info") print('\n') if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--find', action='store_true', help='Browse all available services') version_group = parser.add_mutually_exclusive_group() version_group.add_argument('--v6-only', action='store_true') version_group.add_argument('--v4-only', action='store_true') args = parser.parse_args() if args.debug: logging.getLogger('zeroconf').setLevel(logging.DEBUG) if args.v6_only: ip_version = IPVersion.V6Only elif args.v4_only: ip_version = IPVersion.V4Only else: ip_version = IPVersion.All zeroconf = Zeroconf(ip_version=ip_version) services = ["_http._tcp.local.", "_hap._tcp.local.", "_esphomelib._tcp.local.", "_airplay._tcp.local."] if args.find: services = list(ZeroconfServiceTypes.find(zc=zeroconf)) print("\nBrowsing %d service(s), press Ctrl-C to exit...\n" % len(services)) browser = ServiceBrowser(zeroconf, services, handlers=[on_service_state_change]) try: while True: sleep(0.1) except KeyboardInterrupt: pass finally: zeroconf.close() 0707010000001D000081ED0000000000000000000000016619D4CC000005C1000000000000000000000000000000000000003100000000python-zeroconf-0.132.2/examples/registration.py#!/usr/bin/env python3 """ Example of announcing a service (in this case, a fake HTTP server) """ import argparse import logging import socket from time import sleep from zeroconf import IPVersion, ServiceInfo, Zeroconf if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') version_group = parser.add_mutually_exclusive_group() version_group.add_argument('--v6', action='store_true') version_group.add_argument('--v6-only', action='store_true') args = parser.parse_args() if args.debug: logging.getLogger('zeroconf').setLevel(logging.DEBUG) if args.v6: ip_version = IPVersion.All elif args.v6_only: ip_version = IPVersion.V6Only else: ip_version = IPVersion.V4Only desc = {'path': '/~paulsm/'} info = ServiceInfo( "_http._tcp.local.", "Paul's Test Web Site._http._tcp.local.", addresses=[socket.inet_aton("127.0.0.1")], port=80, properties=desc, server="ash-2.local.", ) zeroconf = Zeroconf(ip_version=ip_version) print("Registration of a service, press Ctrl-C to exit...") zeroconf.register_service(info) try: while True: sleep(0.1) except KeyboardInterrupt: pass finally: print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() 0707010000001E000081ED0000000000000000000000016619D4CC00000219000000000000000000000000000000000000002D00000000python-zeroconf-0.132.2/examples/resolver.py#!/usr/bin/env python3 """ Example of resolving a service with a known name """ import logging import sys from zeroconf import Zeroconf TYPE = '_test._tcp.local.' NAME = 'My Service Name' if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) if len(sys.argv) > 1: assert sys.argv[1:] == ['--debug'] logging.getLogger('zeroconf').setLevel(logging.DEBUG) zeroconf = Zeroconf() try: print(zeroconf.get_service_info(TYPE, NAME + '.' + TYPE)) finally: zeroconf.close() 0707010000001F000081ED0000000000000000000000016619D4CC000006F9000000000000000000000000000000000000002E00000000python-zeroconf-0.132.2/examples/self_test.py#!/usr/bin/env python3 import logging import socket import sys from zeroconf import ServiceInfo, Zeroconf, __version__ if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) if len(sys.argv) > 1: assert sys.argv[1:] == ['--debug'] logging.getLogger('zeroconf').setLevel(logging.DEBUG) # Test a few module features, including service registration, service # query (for Zoe), and service unregistration. print(f"Multicast DNS Service Discovery for Python, version {__version__}") r = Zeroconf() print("1. Testing registration of a service...") desc = {'version': '0.10', 'a': 'test value', 'b': 'another value'} addresses = [socket.inet_aton("127.0.0.1")] expected = {'127.0.0.1'} if socket.has_ipv6: addresses.append(socket.inet_pton(socket.AF_INET6, '::1')) expected.add('::1') info = ServiceInfo( "_http._tcp.local.", "My Service Name._http._tcp.local.", addresses=addresses, port=1234, properties=desc, ) print(" Registering service...") r.register_service(info) print(" Registration done.") print("2. Testing query of service information...") print(" Getting ZOE service: %s" % (r.get_service_info("_http._tcp.local.", "ZOE._http._tcp.local."))) print(" Query done.") print("3. Testing query of own service...") queried_info = r.get_service_info("_http._tcp.local.", "My Service Name._http._tcp.local.") assert queried_info assert set(queried_info.parsed_addresses()) == expected print(f" Getting self: {queried_info}") print(" Query done.") print("4. Testing unregister of service information...") r.unregister_service(info) print(" Unregister done.") r.close() 07070100000020000081A40000000000000000000000016619D4CC000063C1000000000000000000000000000000000000002400000000python-zeroconf-0.132.2/poetry.lock# This file is automatically @generated by Poetry 1.7.1 and should not be changed by hand. [[package]] name = "async-timeout" version = "4.0.3" description = "Timeout context manager for asyncio programs" optional = false python-versions = ">=3.7" files = [ {file = "async-timeout-4.0.3.tar.gz", hash = "sha256:4640d96be84d82d02ed59ea2b7105a0f7b33abe8703703cd0ab0bf87c427522f"}, {file = "async_timeout-4.0.3-py3-none-any.whl", hash = "sha256:7405140ff1230c310e51dc27b3145b9092d659ce68ff733fb0cefe3ee42be028"}, ] [[package]] name = "colorama" version = "0.4.6" description = "Cross-platform colored terminal text." optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" files = [ {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, ] [[package]] name = "coverage" version = "7.4.1" description = "Code coverage measurement for Python" optional = false python-versions = ">=3.8" files = [ {file = "coverage-7.4.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:077d366e724f24fc02dbfe9d946534357fda71af9764ff99d73c3c596001bbd7"}, {file = "coverage-7.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0193657651f5399d433c92f8ae264aff31fc1d066deee4b831549526433f3f61"}, {file = "coverage-7.4.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d17bbc946f52ca67adf72a5ee783cd7cd3477f8f8796f59b4974a9b59cacc9ee"}, {file = "coverage-7.4.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a3277f5fa7483c927fe3a7b017b39351610265308f5267ac6d4c2b64cc1d8d25"}, {file = "coverage-7.4.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6dceb61d40cbfcf45f51e59933c784a50846dc03211054bd76b421a713dcdf19"}, {file = "coverage-7.4.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:6008adeca04a445ea6ef31b2cbaf1d01d02986047606f7da266629afee982630"}, {file = "coverage-7.4.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:c61f66d93d712f6e03369b6a7769233bfda880b12f417eefdd4f16d1deb2fc4c"}, {file = "coverage-7.4.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b9bb62fac84d5f2ff523304e59e5c439955fb3b7f44e3d7b2085184db74d733b"}, {file = "coverage-7.4.1-cp310-cp310-win32.whl", hash = "sha256:f86f368e1c7ce897bf2457b9eb61169a44e2ef797099fb5728482b8d69f3f016"}, {file = "coverage-7.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:869b5046d41abfea3e381dd143407b0d29b8282a904a19cb908fa24d090cc018"}, {file = "coverage-7.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b8ffb498a83d7e0305968289441914154fb0ef5d8b3157df02a90c6695978295"}, {file = "coverage-7.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3cacfaefe6089d477264001f90f55b7881ba615953414999c46cc9713ff93c8c"}, {file = "coverage-7.4.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d6850e6e36e332d5511a48a251790ddc545e16e8beaf046c03985c69ccb2676"}, {file = "coverage-7.4.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:18e961aa13b6d47f758cc5879383d27b5b3f3dcd9ce8cdbfdc2571fe86feb4dd"}, {file = "coverage-7.4.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dfd1e1b9f0898817babf840b77ce9fe655ecbe8b1b327983df485b30df8cc011"}, {file = "coverage-7.4.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:6b00e21f86598b6330f0019b40fb397e705135040dbedc2ca9a93c7441178e74"}, {file = "coverage-7.4.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:536d609c6963c50055bab766d9951b6c394759190d03311f3e9fcf194ca909e1"}, {file = "coverage-7.4.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:7ac8f8eb153724f84885a1374999b7e45734bf93a87d8df1e7ce2146860edef6"}, {file = "coverage-7.4.1-cp311-cp311-win32.whl", hash = "sha256:f3771b23bb3675a06f5d885c3630b1d01ea6cac9e84a01aaf5508706dba546c5"}, {file = "coverage-7.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:9d2f9d4cc2a53b38cabc2d6d80f7f9b7e3da26b2f53d48f05876fef7956b6968"}, {file = "coverage-7.4.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:f68ef3660677e6624c8cace943e4765545f8191313a07288a53d3da188bd8581"}, {file = "coverage-7.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:23b27b8a698e749b61809fb637eb98ebf0e505710ec46a8aa6f1be7dc0dc43a6"}, {file = "coverage-7.4.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e3424c554391dc9ef4a92ad28665756566a28fecf47308f91841f6c49288e66"}, {file = "coverage-7.4.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e0860a348bf7004c812c8368d1fc7f77fe8e4c095d661a579196a9533778e156"}, {file = "coverage-7.4.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fe558371c1bdf3b8fa03e097c523fb9645b8730399c14fe7721ee9c9e2a545d3"}, {file = "coverage-7.4.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:3468cc8720402af37b6c6e7e2a9cdb9f6c16c728638a2ebc768ba1ef6f26c3a1"}, {file = "coverage-7.4.1-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:02f2edb575d62172aa28fe00efe821ae31f25dc3d589055b3fb64d51e52e4ab1"}, {file = "coverage-7.4.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:ca6e61dc52f601d1d224526360cdeab0d0712ec104a2ce6cc5ccef6ed9a233bc"}, {file = "coverage-7.4.1-cp312-cp312-win32.whl", hash = "sha256:ca7b26a5e456a843b9b6683eada193fc1f65c761b3a473941efe5a291f604c74"}, {file = "coverage-7.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:85ccc5fa54c2ed64bd91ed3b4a627b9cce04646a659512a051fa82a92c04a448"}, {file = "coverage-7.4.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:8bdb0285a0202888d19ec6b6d23d5990410decb932b709f2b0dfe216d031d218"}, {file = "coverage-7.4.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:918440dea04521f499721c039863ef95433314b1db00ff826a02580c1f503e45"}, {file = "coverage-7.4.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:379d4c7abad5afbe9d88cc31ea8ca262296480a86af945b08214eb1a556a3e4d"}, {file = "coverage-7.4.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b094116f0b6155e36a304ff912f89bbb5067157aff5f94060ff20bbabdc8da06"}, {file = "coverage-7.4.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f2f5968608b1fe2a1d00d01ad1017ee27efd99b3437e08b83ded9b7af3f6f766"}, {file = "coverage-7.4.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:10e88e7f41e6197ea0429ae18f21ff521d4f4490aa33048f6c6f94c6045a6a75"}, {file = "coverage-7.4.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:a4a3907011d39dbc3e37bdc5df0a8c93853c369039b59efa33a7b6669de04c60"}, {file = "coverage-7.4.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:6d224f0c4c9c98290a6990259073f496fcec1b5cc613eecbd22786d398ded3ad"}, {file = "coverage-7.4.1-cp38-cp38-win32.whl", hash = "sha256:23f5881362dcb0e1a92b84b3c2809bdc90db892332daab81ad8f642d8ed55042"}, {file = "coverage-7.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:a07f61fc452c43cd5328b392e52555f7d1952400a1ad09086c4a8addccbd138d"}, {file = "coverage-7.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8e738a492b6221f8dcf281b67129510835461132b03024830ac0e554311a5c54"}, {file = "coverage-7.4.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:46342fed0fff72efcda77040b14728049200cbba1279e0bf1188f1f2078c1d70"}, {file = "coverage-7.4.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9641e21670c68c7e57d2053ddf6c443e4f0a6e18e547e86af3fad0795414a628"}, {file = "coverage-7.4.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:aeb2c2688ed93b027eb0d26aa188ada34acb22dceea256d76390eea135083950"}, {file = "coverage-7.4.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d12c923757de24e4e2110cf8832d83a886a4cf215c6e61ed506006872b43a6d1"}, {file = "coverage-7.4.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0491275c3b9971cdbd28a4595c2cb5838f08036bca31765bad5e17edf900b2c7"}, {file = "coverage-7.4.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:8dfc5e195bbef80aabd81596ef52a1277ee7143fe419efc3c4d8ba2754671756"}, {file = "coverage-7.4.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:1a78b656a4d12b0490ca72651fe4d9f5e07e3c6461063a9b6265ee45eb2bdd35"}, {file = "coverage-7.4.1-cp39-cp39-win32.whl", hash = "sha256:f90515974b39f4dea2f27c0959688621b46d96d5a626cf9c53dbc653a895c05c"}, {file = "coverage-7.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:64e723ca82a84053dd7bfcc986bdb34af8d9da83c521c19d6b472bc6880e191a"}, {file = "coverage-7.4.1-pp38.pp39.pp310-none-any.whl", hash = "sha256:32a8d985462e37cfdab611a6f95b09d7c091d07668fdc26e47a725ee575fe166"}, {file = "coverage-7.4.1.tar.gz", hash = "sha256:1ed4b95480952b1a26d863e546fa5094564aa0065e1e5f0d4d0041f293251d04"}, ] [package.dependencies] tomli = {version = "*", optional = true, markers = "python_full_version <= \"3.11.0a6\" and extra == \"toml\""} [package.extras] toml = ["tomli"] [[package]] name = "cython" version = "3.0.8" description = "The Cython compiler for writing C extensions in the Python language." optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" files = [ {file = "Cython-3.0.8-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:a846e0a38e2b24e9a5c5dc74b0e54c6e29420d88d1dafabc99e0fc0f3e338636"}, {file = "Cython-3.0.8-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:45523fdc2b78d79b32834cc1cc12dc2ca8967af87e22a3ee1bff20e77c7f5520"}, {file = "Cython-3.0.8-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:baa0b7f3f841fe087410cab66778e2d3fb20ae2d2078a2be3dffe66c6574be39"}, {file = "Cython-3.0.8-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e87294e33e40c289c77a135f491cd721bd089f193f956f7b8ed5aa2d0b8c558f"}, {file = "Cython-3.0.8-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:a1df7a129344b1215c20096d33c00193437df1a8fcca25b71f17c23b1a44f782"}, {file = "Cython-3.0.8-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:13c2a5e57a0358da467d97667297bf820b62a1a87ae47c5f87938b9bb593acbd"}, {file = "Cython-3.0.8-cp310-cp310-win32.whl", hash = "sha256:96b028f044f5880e3cb18ecdcfc6c8d3ce9d0af28418d5ab464509f26d8adf12"}, {file = "Cython-3.0.8-cp310-cp310-win_amd64.whl", hash = "sha256:8140597a8b5cc4f119a1190f5a2228a84f5ca6d8d9ec386cfce24663f48b2539"}, {file = "Cython-3.0.8-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:aae26f9663e50caf9657148403d9874eea41770ecdd6caf381d177c2b1bb82ba"}, {file = "Cython-3.0.8-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:547eb3cdb2f8c6f48e6865d5a741d9dd051c25b3ce076fbca571727977b28ac3"}, {file = "Cython-3.0.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5a567d4b9ba70b26db89d75b243529de9e649a2f56384287533cf91512705bee"}, {file = "Cython-3.0.8-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:51d1426263b0e82fb22bda8ea60dc77a428581cc19e97741011b938445d383f1"}, {file = "Cython-3.0.8-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:c26daaeccda072459b48d211415fd1e5507c06bcd976fa0d5b8b9f1063467d7b"}, {file = "Cython-3.0.8-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:289ce7838208211cd166e975865fd73b0649bf118170b6cebaedfbdaf4a37795"}, {file = "Cython-3.0.8-cp311-cp311-win32.whl", hash = "sha256:c8aa05f5e17f8042a3be052c24f2edc013fb8af874b0bf76907d16c51b4e7871"}, {file = "Cython-3.0.8-cp311-cp311-win_amd64.whl", hash = "sha256:000dc9e135d0eec6ecb2b40a5b02d0868a2f8d2e027a41b0fe16a908a9e6de02"}, {file = "Cython-3.0.8-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:90d3fe31db55685d8cb97d43b0ec39ef614fcf660f83c77ed06aa670cb0e164f"}, {file = "Cython-3.0.8-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e24791ddae2324e88e3c902a765595c738f19ae34ee66bfb1a6dac54b1833419"}, {file = "Cython-3.0.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2f020fa1c0552052e0660790b8153b79e3fc9a15dbd8f1d0b841fe5d204a6ae6"}, {file = "Cython-3.0.8-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:18bfa387d7a7f77d7b2526af69a65dbd0b731b8d941aaff5becff8e21f6d7717"}, {file = "Cython-3.0.8-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:fe81b339cffd87c0069c6049b4d33e28bdd1874625ee515785bf42c9fdff3658"}, {file = "Cython-3.0.8-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:80fd94c076e1e1b1ee40a309be03080b75f413e8997cddcf401a118879863388"}, {file = "Cython-3.0.8-cp312-cp312-win32.whl", hash = "sha256:85077915a93e359a9b920280d214dc0cf8a62773e1f3d7d30fab8ea4daed670c"}, {file = "Cython-3.0.8-cp312-cp312-win_amd64.whl", hash = "sha256:0cb2dcc565c7851f75d496f724a384a790fab12d1b82461b663e66605bec429a"}, {file = "Cython-3.0.8-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:870d2a0a7e3cbd5efa65aecdb38d715ea337a904ea7bb22324036e78fb7068e7"}, {file = "Cython-3.0.8-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7e8f2454128974905258d86534f4fd4f91d2f1343605657ecab779d80c9d6d5e"}, {file = "Cython-3.0.8-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c1949d6aa7bc792554bee2b67a9fe41008acbfe22f4f8df7b6ec7b799613a4b3"}, {file = "Cython-3.0.8-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c9f2c6e1b8f3bcd6cb230bac1843f85114780bb8be8614855b1628b36bb510e0"}, {file = "Cython-3.0.8-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:05d7eddc668ae7993643f32c7661f25544e791edb745758672ea5b1a82ecffa6"}, {file = "Cython-3.0.8-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:bfabe115deef4ada5d23c87bddb11289123336dcc14347011832c07db616dd93"}, {file = "Cython-3.0.8-cp36-cp36m-win32.whl", hash = "sha256:0c38c9f0bcce2df0c3347285863621be904ac6b64c5792d871130569d893efd7"}, {file = "Cython-3.0.8-cp36-cp36m-win_amd64.whl", hash = "sha256:6c46939c3983217d140999de7c238c3141f56b1ea349e47ca49cae899969aa2c"}, {file = "Cython-3.0.8-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:115f0a50f752da6c99941b103b5cb090da63eb206abbc7c2ad33856ffc73f064"}, {file = "Cython-3.0.8-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c9c0f29246734561c90f36e70ed0506b61aa3d044e4cc4cba559065a2a741fae"}, {file = "Cython-3.0.8-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1ab75242869ff71e5665fe5c96f3378e79e792fa3c11762641b6c5afbbbbe026"}, {file = "Cython-3.0.8-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6717c06e9cfc6c1df18543cd31a21f5d8e378a40f70c851fa2d34f0597037abc"}, {file = "Cython-3.0.8-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:9d3f74388db378a3c6fd06e79a809ed98df3f56484d317b81ee762dbf3c263e0"}, {file = "Cython-3.0.8-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:ae7ac561fd8253a9ae96311e91d12af5f701383564edc11d6338a7b60b285a6f"}, {file = "Cython-3.0.8-cp37-cp37m-win32.whl", hash = "sha256:97b2a45845b993304f1799664fa88da676ee19442b15fdcaa31f9da7e1acc434"}, {file = "Cython-3.0.8-cp37-cp37m-win_amd64.whl", hash = "sha256:9e2be2b340fea46fb849d378f9b80d3c08ff2e81e2bfbcdb656e2e3cd8c6b2dc"}, {file = "Cython-3.0.8-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:2cde23c555470db3f149ede78b518e8274853745289c956a0e06ad8d982e4db9"}, {file = "Cython-3.0.8-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7990ca127e1f1beedaf8fc8bf66541d066ef4723ad7d8d47a7cbf842e0f47580"}, {file = "Cython-3.0.8-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b983c8e6803f016146c26854d9150ddad5662960c804ea7f0c752c9266752f0"}, {file = "Cython-3.0.8-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a973268d7ca1a2bdf78575e459a94a78e1a0a9bb62a7db0c50041949a73b02ff"}, {file = "Cython-3.0.8-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:61a237bc9dd23c7faef0fcfce88c11c65d0c9bb73c74ccfa408b3a012073c20e"}, {file = "Cython-3.0.8-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:3a3d67f079598af49e90ff9655bf85bd358f093d727eb21ca2708f467c489cae"}, {file = "Cython-3.0.8-cp38-cp38-win32.whl", hash = "sha256:17a642bb01a693e34c914106566f59844b4461665066613913463a719e0dd15d"}, {file = "Cython-3.0.8-cp38-cp38-win_amd64.whl", hash = "sha256:2cdfc32252f3b6dc7c94032ab744dcedb45286733443c294d8f909a4854e7f83"}, {file = "Cython-3.0.8-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:fa97893d99385386925d00074654aeae3a98867f298d1e12ceaf38a9054a9bae"}, {file = "Cython-3.0.8-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f05c0bf9d085c031df8f583f0d506aa3be1692023de18c45d0aaf78685bbb944"}, {file = "Cython-3.0.8-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:de892422582f5758bd8de187e98ac829330ec1007bc42c661f687792999988a7"}, {file = "Cython-3.0.8-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:314f2355a1f1d06e3c431eaad4708cf10037b5e91e4b231d89c913989d0bdafd"}, {file = "Cython-3.0.8-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:78825a3774211e7d5089730f00cdf7f473042acc9ceb8b9eeebe13ed3a5541de"}, {file = "Cython-3.0.8-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:df8093deabc55f37028190cf5e575c26aad23fc673f34b85d5f45076bc37ce39"}, {file = "Cython-3.0.8-cp39-cp39-win32.whl", hash = "sha256:1aca1b97e0095b3a9a6c33eada3f661a4ed0d499067d121239b193e5ba3bb4f0"}, {file = "Cython-3.0.8-cp39-cp39-win_amd64.whl", hash = "sha256:16873d78be63bd38ffb759da7ab82814b36f56c769ee02b1d5859560e4c3ac3c"}, {file = "Cython-3.0.8-py2.py3-none-any.whl", hash = "sha256:171b27051253d3f9108e9759e504ba59ff06e7f7ba944457f94deaf9c21bf0b6"}, {file = "Cython-3.0.8.tar.gz", hash = "sha256:8333423d8fd5765e7cceea3a9985dd1e0a5dfeb2734629e1a2ed2d6233d39de6"}, ] [[package]] name = "exceptiongroup" version = "1.2.0" description = "Backport of PEP 654 (exception groups)" optional = false python-versions = ">=3.7" files = [ {file = "exceptiongroup-1.2.0-py3-none-any.whl", hash = "sha256:4bfd3996ac73b41e9b9628b04e079f193850720ea5945fc96a08633c66912f14"}, {file = "exceptiongroup-1.2.0.tar.gz", hash = "sha256:91f5c769735f051a4290d52edd0858999b57e5876e9f85937691bd4c9fa3ed68"}, ] [package.extras] test = ["pytest (>=6)"] [[package]] name = "ifaddr" version = "0.2.0" description = "Cross-platform network interface and IP address enumeration library" optional = false python-versions = "*" files = [ {file = "ifaddr-0.2.0-py3-none-any.whl", hash = "sha256:085e0305cfe6f16ab12d72e2024030f5d52674afad6911bb1eee207177b8a748"}, {file = "ifaddr-0.2.0.tar.gz", hash = "sha256:cc0cbfcaabf765d44595825fb96a99bb12c79716b73b44330ea38ee2b0c4aed4"}, ] [[package]] name = "iniconfig" version = "2.0.0" description = "brain-dead simple config-ini parsing" optional = false python-versions = ">=3.7" files = [ {file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"}, {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"}, ] [[package]] name = "packaging" version = "23.2" description = "Core utilities for Python packages" optional = false python-versions = ">=3.7" files = [ {file = "packaging-23.2-py3-none-any.whl", hash = "sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7"}, {file = "packaging-23.2.tar.gz", hash = "sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5"}, ] [[package]] name = "pluggy" version = "1.4.0" description = "plugin and hook calling mechanisms for python" optional = false python-versions = ">=3.8" files = [ {file = "pluggy-1.4.0-py3-none-any.whl", hash = "sha256:7db9f7b503d67d1c5b95f59773ebb58a8c1c288129a88665838012cfb07b8981"}, {file = "pluggy-1.4.0.tar.gz", hash = "sha256:8c85c2876142a764e5b7548e7d9a0e0ddb46f5185161049a79b7e974454223be"}, ] [package.extras] dev = ["pre-commit", "tox"] testing = ["pytest", "pytest-benchmark"] [[package]] name = "pytest" version = "7.4.4" description = "pytest: simple powerful testing with Python" optional = false python-versions = ">=3.7" files = [ {file = "pytest-7.4.4-py3-none-any.whl", hash = "sha256:b090cdf5ed60bf4c45261be03239c2c1c22df034fbffe691abe93cd80cea01d8"}, {file = "pytest-7.4.4.tar.gz", hash = "sha256:2cf0005922c6ace4a3e2ec8b4080eb0d9753fdc93107415332f50ce9e7994280"}, ] [package.dependencies] colorama = {version = "*", markers = "sys_platform == \"win32\""} exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""} iniconfig = "*" packaging = "*" pluggy = ">=0.12,<2.0" tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""} [package.extras] testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"] [[package]] name = "pytest-asyncio" version = "0.20.3" description = "Pytest support for asyncio" optional = false python-versions = ">=3.7" files = [ {file = "pytest-asyncio-0.20.3.tar.gz", hash = "sha256:83cbf01169ce3e8eb71c6c278ccb0574d1a7a3bb8eaaf5e50e0ad342afb33b36"}, {file = "pytest_asyncio-0.20.3-py3-none-any.whl", hash = "sha256:f129998b209d04fcc65c96fc85c11e5316738358909a8399e93be553d7656442"}, ] [package.dependencies] pytest = ">=6.1.0" [package.extras] docs = ["sphinx (>=5.3)", "sphinx-rtd-theme (>=1.0)"] testing = ["coverage (>=6.2)", "flaky (>=3.5.0)", "hypothesis (>=5.7.1)", "mypy (>=0.931)", "pytest-trio (>=0.7.0)"] [[package]] name = "pytest-cov" version = "4.1.0" description = "Pytest plugin for measuring coverage." optional = false python-versions = ">=3.7" files = [ {file = "pytest-cov-4.1.0.tar.gz", hash = "sha256:3904b13dfbfec47f003b8e77fd5b589cd11904a21ddf1ab38a64f204d6a10ef6"}, {file = "pytest_cov-4.1.0-py3-none-any.whl", hash = "sha256:6ba70b9e97e69fcc3fb45bfeab2d0a138fb65c4d0d6a41ef33983ad114be8c3a"}, ] [package.dependencies] coverage = {version = ">=5.2.1", extras = ["toml"]} pytest = ">=4.6" [package.extras] testing = ["fields", "hunter", "process-tests", "pytest-xdist", "six", "virtualenv"] [[package]] name = "pytest-timeout" version = "2.2.0" description = "pytest plugin to abort hanging tests" optional = false python-versions = ">=3.7" files = [ {file = "pytest-timeout-2.2.0.tar.gz", hash = "sha256:3b0b95dabf3cb50bac9ef5ca912fa0cfc286526af17afc806824df20c2f72c90"}, {file = "pytest_timeout-2.2.0-py3-none-any.whl", hash = "sha256:bde531e096466f49398a59f2dde76fa78429a09a12411466f88a07213e220de2"}, ] [package.dependencies] pytest = ">=5.0.0" [[package]] name = "setuptools" version = "65.7.0" description = "Easily download, build, install, upgrade, and uninstall Python packages" optional = false python-versions = ">=3.7" files = [ {file = "setuptools-65.7.0-py3-none-any.whl", hash = "sha256:8ab4f1dbf2b4a65f7eec5ad0c620e84c34111a68d3349833494b9088212214dd"}, {file = "setuptools-65.7.0.tar.gz", hash = "sha256:4d3c92fac8f1118bb77a22181355e29c239cabfe2b9effdaa665c66b711136d7"}, ] [package.extras] docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-hoverxref (<2)", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (==0.8.3)", "sphinx-reredirects", "sphinxcontrib-towncrier"] testing = ["build[virtualenv]", "filelock (>=3.4.0)", "flake8 (<5)", "flake8-2020", "ini2toml[lite] (>=0.9)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pip (>=19.1)", "pip-run (>=8.8)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)", "pytest-perf", "pytest-timeout", "pytest-xdist", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"] testing-integration = ["build[virtualenv]", "filelock (>=3.4.0)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pytest", "pytest-enabler", "pytest-xdist", "tomli", "virtualenv (>=13.0.0)", "wheel"] [[package]] name = "tomli" version = "2.0.1" description = "A lil' TOML parser" optional = false python-versions = ">=3.7" files = [ {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, ] [metadata] lock-version = "2.0" python-versions = "^3.8" content-hash = "26c7f2ec91a34a0661a5511d2ade43511d80dd4f89e1aefbb59c9fafc2c92df2" 07070100000021000081A40000000000000000000000016619D4CC00000FA2000000000000000000000000000000000000002700000000python-zeroconf-0.132.2/pyproject.toml[tool.poetry] name = "zeroconf" version = "0.132.2" description = "A pure python implementation of multicast DNS service discovery" authors = ["Paul Scott-Murphy", "William McBrine", "Jakub Stasiak", "J. Nick Koston"] license = "LGPL" readme = "README.rst" repository = "https://github.com/python-zeroconf/python-zeroconf" documentation = "https://python-zeroconf.readthedocs.io" classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Libraries', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] packages = [ { include = "zeroconf", from = "src" }, ] include = [ { path = "CHANGELOG.md", format = "sdist" }, { path = "COPYING", format = "sdist" }, { path = "docs", format = "sdist" }, { path = "tests", format = "sdist" }, ] [tool.poetry.urls] "Bug Tracker" = "https://github.com/python-zeroconf/python-zeroconf/issues" "Changelog" = "https://github.com/python-zeroconf/python-zeroconf/blob/master/CHANGELOG.md" [tool.poetry.build] generate-setup-file = true script = "build_ext.py" [tool.semantic_release] branch = "master" version_toml = "pyproject.toml:tool.poetry.version" version_variable = "src/zeroconf/__init__.py:__version__" build_command = "pip install poetry && poetry build" tag_format = "{version}" [tool.poetry.dependencies] python = "^3.8" async-timeout = {version = ">=3.0.0", python = "<3.11"} ifaddr = ">=0.1.7" [tool.poetry.group.dev.dependencies] pytest = "^7.2.0" pytest-cov = "^4.0.0" pytest-asyncio = "^0.20.3" cython = "^3.0.5" setuptools = "^65.6.3" pytest-timeout = "^2.1.0" [tool.black] line-length = 110 target_version = ['py37', 'py38', 'py39', 'py310', 'py311'] skip_string_normalization = true [tool.pylint.BASIC] class-const-naming-style = "any" good-names = [ "e", "er", "h", "i", "id", "ip", "os", "n", "rr", "rs", "s", "t", "wr", "zc", "_GLOBAL_DONE", ] [tool.pylint."MESSAGES CONTROL"] disable = [ "duplicate-code", "fixme", "format", "missing-class-docstring", "missing-function-docstring", "too-few-public-methods", "too-many-arguments", "too-many-instance-attributes", "too-many-public-methods" ] [tool.pytest.ini_options] addopts = "-v -Wdefault --cov=zeroconf --cov-report=term-missing:skip-covered" pythonpath = ["src"] [tool.coverage.run] branch = true [tool.coverage.report] exclude_lines = [ "pragma: no cover", "@overload", "if TYPE_CHECKING", "raise NotImplementedError", ] [tool.isort] profile = "black" known_first_party = ["zeroconf", "tests"] [tool.mypy] check_untyped_defs = true disallow_any_generics = false # turn this on when we drop 3.7/3.8 support disallow_incomplete_defs = true disallow_untyped_defs = true mypy_path = "src/" no_implicit_optional = true show_error_codes = true warn_unreachable = true warn_unused_ignores = true exclude = [ 'docs/*', 'bench/*', ] [[tool.mypy.overrides]] module = "tests.*" allow_untyped_defs = true [[tool.mypy.overrides]] module = "docs.*" ignore_errors = true allow_untyped_defs = true [[tool.mypy.overrides]] module = "bench.*" ignore_errors = true [build-system] # 1.5.2 required for https://github.com/python-poetry/poetry/issues/7505 requires = ['setuptools>=65.4.1', 'wheel', 'Cython>=3.0.8', "poetry-core>=1.5.2"] build-backend = "poetry.core.masonry.api" [tool.codespell] skip = '*.po,*.ts,./tests,./bench' count = '' quiet-level = 3 07070100000022000081A40000000000000000000000016619D4CC000000FA000000000000000000000000000000000000002D00000000python-zeroconf-0.132.2/requirements-dev.txtasync_timeout>=4.0.1 autopep8 black;implementation_name=="cpython" bump2version coverage flake8 flake8-import-order ifaddr mypy;implementation_name=="cpython" pep8-naming>=0.12.0 pylint pytest pytest-asyncio pytest-cov pytest-timeout readme_renderer 07070100000023000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000001C00000000python-zeroconf-0.132.2/src07070100000024000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002500000000python-zeroconf-0.132.2/src/zeroconf07070100000025000081A40000000000000000000000016619D4CC00000F38000000000000000000000000000000000000003100000000python-zeroconf-0.132.2/src/zeroconf/__init__.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import sys from ._cache import DNSCache # noqa # import needed for backwards compat from ._core import Zeroconf from ._dns import ( # noqa # import needed for backwards compat DNSAddress, DNSEntry, DNSHinfo, DNSNsec, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, DNSService, DNSText, ) from ._exceptions import ( AbstractMethodException, BadTypeInNameException, Error, EventLoopBlocked, IncomingDecodeError, NamePartTooLongException, NonUniqueNameException, NotRunningException, ServiceNameAlreadyRegistered, ) from ._logger import QuietLogger, log # noqa # import needed for backwards compat from ._protocol.incoming import DNSIncoming # noqa # import needed for backwards compat from ._protocol.outgoing import DNSOutgoing # noqa # import needed for backwards compat from ._record_update import RecordUpdate from ._services import ( # noqa # import needed for backwards compat ServiceListener, ServiceStateChange, Signal, SignalRegistrationInterface, ) from ._services.browser import ServiceBrowser from ._services.info import ( # noqa # import needed for backwards compat ServiceInfo, instance_name_from_service_info, ) from ._services.registry import ( # noqa # import needed for backwards compat ServiceRegistry, ) from ._services.types import ZeroconfServiceTypes from ._updates import RecordUpdateListener from ._utils.name import service_type_name # noqa # import needed for backwards compat from ._utils.net import ( # noqa # import needed for backwards compat InterfaceChoice, InterfacesType, IPVersion, add_multicast_member, autodetect_ip_version, create_sockets, get_all_addresses, get_all_addresses_v6, ) from ._utils.time import ( # noqa # import needed for backwards compat current_time_millis, millis_to_seconds, ) __author__ = 'Paul Scott-Murphy, William McBrine' __maintainer__ = 'Jakub Stasiak <jakub@stasiak.at>' __version__ = '0.132.2' __license__ = 'LGPL' __all__ = [ "__version__", "Zeroconf", "ServiceInfo", "ServiceBrowser", "ServiceListener", "DNSQuestionType", "InterfaceChoice", "ServiceStateChange", "IPVersion", "ZeroconfServiceTypes", "RecordUpdate", "RecordUpdateListener", "current_time_millis", # Exceptions "Error", "AbstractMethodException", "BadTypeInNameException", "EventLoopBlocked", "IncomingDecodeError", "NamePartTooLongException", "NonUniqueNameException", "NotRunningException", "ServiceNameAlreadyRegistered", ] if sys.version_info <= (3, 6): # pragma: no cover raise ImportError( # pragma: no cover ''' Python version > 3.6 required for python-zeroconf. If you need support for Python 2 or Python 3.3-3.4 please use version 19.1 If you need support for Python 3.5 please use version 0.28.0 ''' ) 07070100000026000081A40000000000000000000000016619D4CC000006A1000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/src/zeroconf/_cache.pxdimport cython from ._dns cimport ( DNSAddress, DNSEntry, DNSHinfo, DNSNsec, DNSPointer, DNSRecord, DNSService, DNSText, ) cdef object _UNIQUE_RECORD_TYPES cdef object _TYPE_PTR cdef cython.uint _ONE_SECOND cdef _remove_key(cython.dict cache, object key, DNSRecord record) cdef class DNSCache: cdef public cython.dict cache cdef public cython.dict service_cache cpdef bint async_add_records(self, object entries) cpdef void async_remove_records(self, object entries) @cython.locals( store=cython.dict, ) cpdef DNSRecord async_get_unique(self, DNSRecord entry) @cython.locals( record=DNSRecord, ) cpdef list async_expire(self, double now) @cython.locals( records=cython.dict, record=DNSRecord, ) cpdef list async_all_by_details(self, str name, object type_, object class_) cpdef cython.dict async_entries_with_name(self, str name) cpdef cython.dict async_entries_with_server(self, str name) @cython.locals( cached_entry=DNSRecord, ) cpdef DNSRecord get_by_details(self, str name, object type_, object class_) @cython.locals( records=cython.dict, entry=DNSRecord, ) cpdef cython.list get_all_by_details(self, str name, object type_, object class_) @cython.locals( store=cython.dict, ) cdef bint _async_add(self, DNSRecord record) cdef void _async_remove(self, DNSRecord record) @cython.locals( record=DNSRecord, created_double=double, ) cpdef void async_mark_unique_records_older_than_1s_to_expire(self, cython.set unique_types, object answers, double now) 07070100000027000081A40000000000000000000000016619D4CC000024F1000000000000000000000000000000000000002F00000000python-zeroconf-0.132.2/src/zeroconf/_cache.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from typing import Dict, Iterable, List, Optional, Set, Tuple, Union, cast from ._dns import ( DNSAddress, DNSEntry, DNSHinfo, DNSNsec, DNSPointer, DNSRecord, DNSService, DNSText, ) from ._utils.time import current_time_millis from .const import _ONE_SECOND, _TYPE_PTR _UNIQUE_RECORD_TYPES = (DNSAddress, DNSHinfo, DNSPointer, DNSText, DNSService) _UniqueRecordsType = Union[DNSAddress, DNSHinfo, DNSPointer, DNSText, DNSService] _DNSRecordCacheType = Dict[str, Dict[DNSRecord, DNSRecord]] _DNSRecord = DNSRecord _str = str _float = float _int = int def _remove_key(cache: _DNSRecordCacheType, key: _str, record: _DNSRecord) -> None: """Remove a key from a DNSRecord cache This function must be run in from event loop. """ del cache[key][record] if not cache[key]: del cache[key] class DNSCache: """A cache of DNS entries.""" def __init__(self) -> None: self.cache: _DNSRecordCacheType = {} self.service_cache: _DNSRecordCacheType = {} # Functions prefixed with async_ are NOT threadsafe and must # be run in the event loop. def _async_add(self, record: _DNSRecord) -> bool: """Adds an entry. Returns true if the entry was not already in the cache. This function must be run in from event loop. """ # Previously storage of records was implemented as a list # instead a dict. Since DNSRecords are now hashable, the implementation # uses a dict to ensure that adding a new record to the cache # replaces any existing records that are __eq__ to each other which # removes the risk that accessing the cache from the wrong # direction would return the old incorrect entry. store = self.cache.setdefault(record.key, {}) new = record not in store and not isinstance(record, DNSNsec) store[record] = record if isinstance(record, DNSService): self.service_cache.setdefault(record.server_key, {})[record] = record return new def async_add_records(self, entries: Iterable[DNSRecord]) -> bool: """Add multiple records. Returns true if any of the records were not in the cache. This function must be run in from event loop. """ new = False for entry in entries: if self._async_add(entry): new = True return new def _async_remove(self, record: _DNSRecord) -> None: """Removes an entry. This function must be run in from event loop. """ if isinstance(record, DNSService): _remove_key(self.service_cache, record.server_key, record) _remove_key(self.cache, record.key, record) def async_remove_records(self, entries: Iterable[DNSRecord]) -> None: """Remove multiple records. This function must be run in from event loop. """ for entry in entries: self._async_remove(entry) def async_expire(self, now: _float) -> List[DNSRecord]: """Purge expired entries from the cache. This function must be run in from event loop. """ expired = [record for records in self.cache.values() for record in records if record.is_expired(now)] self.async_remove_records(expired) return expired def async_get_unique(self, entry: _UniqueRecordsType) -> Optional[DNSRecord]: """Gets a unique entry by key. Will return None if there is no matching entry. This function is not threadsafe and must be called from the event loop. """ store = self.cache.get(entry.key) if store is None: return None return store.get(entry) def async_all_by_details(self, name: _str, type_: _int, class_: _int) -> List[DNSRecord]: """Gets all matching entries by details. This function is not thread-safe and must be called from the event loop. """ key = name.lower() records = self.cache.get(key) matches: List[DNSRecord] = [] if records is None: return matches for record in records: if type_ == record.type and class_ == record.class_: matches.append(record) return matches def async_entries_with_name(self, name: str) -> Dict[DNSRecord, DNSRecord]: """Returns a dict of entries whose key matches the name. This function is not threadsafe and must be called from the event loop. """ return self.cache.get(name.lower()) or {} def async_entries_with_server(self, name: str) -> Dict[DNSRecord, DNSRecord]: """Returns a dict of entries whose key matches the server. This function is not threadsafe and must be called from the event loop. """ return self.service_cache.get(name.lower()) or {} # The below functions are threadsafe and do not need to be run in the # event loop, however they all make copies so they significantly # inefficent def get(self, entry: DNSEntry) -> Optional[DNSRecord]: """Gets an entry by key. Will return None if there is no matching entry.""" if isinstance(entry, _UNIQUE_RECORD_TYPES): return self.cache.get(entry.key, {}).get(entry) for cached_entry in reversed(list(self.cache.get(entry.key, []))): if entry.__eq__(cached_entry): return cached_entry return None def get_by_details(self, name: str, type_: _int, class_: _int) -> Optional[DNSRecord]: """Gets the first matching entry by details. Returns None if no entries match. Calling this function is not recommended as it will only return one record even if there are multiple entries. For example if there are multiple A or AAAA addresses this function will return the last one that was added to the cache which may not be the one you expect. Use get_all_by_details instead. """ key = name.lower() records = self.cache.get(key) if records is None: return None for cached_entry in reversed(list(records)): if type_ == cached_entry.type and class_ == cached_entry.class_: return cached_entry return None def get_all_by_details(self, name: str, type_: _int, class_: _int) -> List[DNSRecord]: """Gets all matching entries by details.""" key = name.lower() records = self.cache.get(key) if records is None: return [] return [entry for entry in list(records) if type_ == entry.type and class_ == entry.class_] def entries_with_server(self, server: str) -> List[DNSRecord]: """Returns a list of entries whose server matches the name.""" return list(self.service_cache.get(server.lower(), [])) def entries_with_name(self, name: str) -> List[DNSRecord]: """Returns a list of entries whose key matches the name.""" return list(self.cache.get(name.lower(), [])) def current_entry_with_name_and_alias(self, name: str, alias: str) -> Optional[DNSRecord]: now = current_time_millis() for record in reversed(self.entries_with_name(name)): if ( record.type == _TYPE_PTR and not record.is_expired(now) and cast(DNSPointer, record).alias == alias ): return record return None def names(self) -> List[str]: """Return a copy of the list of current cache names.""" return list(self.cache) def async_mark_unique_records_older_than_1s_to_expire( self, unique_types: Set[Tuple[_str, _int, _int]], answers: Iterable[DNSRecord], now: _float ) -> None: # rfc6762#section-10.2 para 2 # Since unique is set, all old records with that name, rrtype, # and rrclass that were received more than one second ago are declared # invalid, and marked to expire from the cache in one second. answers_rrset = set(answers) for name, type_, class_ in unique_types: for record in self.async_all_by_details(name, type_, class_): created_double = record.created if (now - created_double > _ONE_SECOND) and record not in answers_rrset: # Expire in 1s record.set_created_ttl(now, 1) 07070100000028000081A40000000000000000000000016619D4CC00006878000000000000000000000000000000000000002E00000000python-zeroconf-0.132.2/src/zeroconf/_core.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import logging import sys import threading from types import TracebackType from typing import Awaitable, Dict, List, Optional, Set, Tuple, Type, Union from ._cache import DNSCache from ._dns import DNSQuestion, DNSQuestionType from ._engine import AsyncEngine from ._exceptions import NonUniqueNameException, NotRunningException from ._handlers.multicast_outgoing_queue import MulticastOutgoingQueue from ._handlers.query_handler import QueryHandler from ._handlers.record_manager import RecordManager from ._history import QuestionHistory from ._logger import QuietLogger, log from ._protocol.outgoing import DNSOutgoing from ._services import ServiceListener from ._services.browser import ServiceBrowser from ._services.info import ( AsyncServiceInfo, ServiceInfo, instance_name_from_service_info, ) from ._services.registry import ServiceRegistry from ._transport import _WrappedTransport from ._updates import RecordUpdateListener from ._utils.asyncio import ( _resolve_all_futures_to_none, await_awaitable, get_running_loop, run_coro_with_timeout, shutdown_loop, wait_event_or_timeout, wait_for_future_set_or_timeout, ) from ._utils.name import service_type_name from ._utils.net import ( InterfaceChoice, InterfacesType, IPVersion, autodetect_ip_version, can_send_to, create_sockets, ) from ._utils.time import current_time_millis, millis_to_seconds from .const import ( _CHECK_TIME, _CLASS_IN, _CLASS_UNIQUE, _FLAGS_AA, _FLAGS_QR_QUERY, _FLAGS_QR_RESPONSE, _MAX_MSG_ABSOLUTE, _MDNS_ADDR, _MDNS_ADDR6, _MDNS_PORT, _ONE_SECOND, _REGISTER_TIME, _STARTUP_TIMEOUT, _TYPE_PTR, _UNREGISTER_TIME, ) # The maximum amont of time to delay a multicast # response in order to aggregate answers _AGGREGATION_DELAY = 500 # ms # The maximum amont of time to delay a multicast # response in order to aggregate answers after # it has already been delayed to protect the network # from excessive traffic. We use a shorter time # window here as we want to _try_ to answer all # queries in under 1350ms while protecting # the network from excessive traffic to ensure # a service info request with two questions # can be answered in the default timeout of # 3000ms _PROTECTED_AGGREGATION_DELAY = 200 # ms _REGISTER_BROADCASTS = 3 def async_send_with_transport( log_debug: bool, transport: _WrappedTransport, packet: bytes, packet_num: int, out: DNSOutgoing, addr: Optional[str], port: int, v6_flow_scope: Union[Tuple[()], Tuple[int, int]] = (), ) -> None: ipv6_socket = transport.is_ipv6 if addr is None: real_addr = _MDNS_ADDR6 if ipv6_socket else _MDNS_ADDR else: real_addr = addr if not can_send_to(ipv6_socket, real_addr): return if log_debug: log.debug( 'Sending to (%s, %d) via [socket %s (%s)] (%d bytes #%d) %r as %r...', real_addr, port or _MDNS_PORT, transport.fileno, transport.sock_name, len(packet), packet_num + 1, out, packet, ) # Get flowinfo and scopeid for the IPV6 socket to create a complete IPv6 # address tuple: https://docs.python.org/3.6/library/socket.html#socket-families if ipv6_socket and not v6_flow_scope: _, _, sock_flowinfo, sock_scopeid = transport.sock_name v6_flow_scope = (sock_flowinfo, sock_scopeid) transport.transport.sendto(packet, (real_addr, port or _MDNS_PORT, *v6_flow_scope)) class Zeroconf(QuietLogger): """Implementation of Zeroconf Multicast DNS Service Discovery Supports registration, unregistration, queries and browsing. """ def __init__( self, interfaces: InterfacesType = InterfaceChoice.All, unicast: bool = False, ip_version: Optional[IPVersion] = None, apple_p2p: bool = False, ) -> None: """Creates an instance of the Zeroconf class, establishing multicast communications, listening and reaping threads. :param interfaces: :class:`InterfaceChoice` or a list of IP addresses (IPv4 and IPv6) and interface indexes (IPv6 only). IPv6 notes for non-POSIX systems: * `InterfaceChoice.All` is an alias for `InterfaceChoice.Default` on Python versions before 3.8. Also listening on loopback (``::1``) doesn't work, use a real address. :param ip_version: IP versions to support. If `choice` is a list, the default is detected from it. Otherwise defaults to V4 only for backward compatibility. :param apple_p2p: use AWDL interface (only macOS) """ if ip_version is None: ip_version = autodetect_ip_version(interfaces) self.done = False if apple_p2p and sys.platform != 'darwin': raise RuntimeError('Option `apple_p2p` is not supported on non-Apple platforms.') self.unicast = unicast listen_socket, respond_sockets = create_sockets(interfaces, unicast, ip_version, apple_p2p=apple_p2p) log.debug('Listen socket %s, respond sockets %s', listen_socket, respond_sockets) self.engine = AsyncEngine(self, listen_socket, respond_sockets) self.browsers: Dict[ServiceListener, ServiceBrowser] = {} self.registry = ServiceRegistry() self.cache = DNSCache() self.question_history = QuestionHistory() self.out_queue = MulticastOutgoingQueue(self, 0, _AGGREGATION_DELAY) self.out_delay_queue = MulticastOutgoingQueue(self, _ONE_SECOND, _PROTECTED_AGGREGATION_DELAY) self.query_handler = QueryHandler(self) self.record_manager = RecordManager(self) self._notify_futures: Set[asyncio.Future] = set() self.loop: Optional[asyncio.AbstractEventLoop] = None self._loop_thread: Optional[threading.Thread] = None self.start() @property def started(self) -> bool: """Check if the instance has started.""" return bool(not self.done and self.engine.running_event and self.engine.running_event.is_set()) def start(self) -> None: """Start Zeroconf.""" self.loop = get_running_loop() if self.loop: self.engine.setup(self.loop, None) return self._start_thread() def _start_thread(self) -> None: """Start a thread with a running event loop.""" loop_thread_ready = threading.Event() def _run_loop() -> None: self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) self.engine.setup(self.loop, loop_thread_ready) self.loop.run_forever() self._loop_thread = threading.Thread(target=_run_loop, daemon=True) self._loop_thread.start() loop_thread_ready.wait() async def async_wait_for_start(self) -> None: """Wait for start up for actions that require a running Zeroconf instance. Throws NotRunningException if the instance is not running or could not be started. """ if self.done: # If the instance was shutdown from under us, raise immediately raise NotRunningException assert self.engine.running_event is not None await wait_event_or_timeout(self.engine.running_event, timeout=_STARTUP_TIMEOUT) if not self.engine.running_event.is_set() or self.done: raise NotRunningException @property def listeners(self) -> Set[RecordUpdateListener]: return self.record_manager.listeners async def async_wait(self, timeout: float) -> None: """Calling task waits for a given number of milliseconds or until notified.""" loop = self.loop assert loop is not None await wait_for_future_set_or_timeout(loop, self._notify_futures, timeout) def notify_all(self) -> None: """Notifies all waiting threads and notify listeners.""" assert self.loop is not None self.loop.call_soon_threadsafe(self.async_notify_all) def async_notify_all(self) -> None: """Schedule an async_notify_all.""" notify_futures = self._notify_futures if notify_futures: _resolve_all_futures_to_none(notify_futures) def get_service_info( self, type_: str, name: str, timeout: int = 3000, question_type: Optional[DNSQuestionType] = None ) -> Optional[ServiceInfo]: """Returns network's service information for a particular name and type, or None if no service matches by the timeout, which defaults to 3 seconds. :param type_: fully qualified service type name :param name: the name of the service :param timeout: milliseconds to wait for a response :param question_type: The type of questions to ask (DNSQuestionType.QM or DNSQuestionType.QU) """ info = ServiceInfo(type_, name) if info.request(self, timeout, question_type): return info return None def add_service_listener(self, type_: str, listener: ServiceListener) -> None: """Adds a listener for a particular service type. This object will then have its add_service and remove_service methods called when services of that type become available and unavailable.""" self.remove_service_listener(listener) self.browsers[listener] = ServiceBrowser(self, type_, listener) def remove_service_listener(self, listener: ServiceListener) -> None: """Removes a listener from the set that is currently listening.""" if listener in self.browsers: self.browsers[listener].cancel() del self.browsers[listener] def remove_all_service_listeners(self) -> None: """Removes a listener from the set that is currently listening.""" for listener in list(self.browsers): self.remove_service_listener(listener) def register_service( self, info: ServiceInfo, ttl: Optional[int] = None, allow_name_change: bool = False, cooperating_responders: bool = False, strict: bool = True, ) -> None: """Registers service information to the network with a default TTL. Zeroconf will then respond to requests for information for that service. The name of the service may be changed if needed to make it unique on the network. Additionally multiple cooperating responders can register the same service on the network for resilience (if you want this behavior set `cooperating_responders` to `True`). While it is not expected during normal operation, this function may raise EventLoopBlocked if the underlying call to `register_service` cannot be completed. """ assert self.loop is not None run_coro_with_timeout( await_awaitable( self.async_register_service(info, ttl, allow_name_change, cooperating_responders, strict) ), self.loop, _REGISTER_TIME * _REGISTER_BROADCASTS, ) async def async_register_service( self, info: ServiceInfo, ttl: Optional[int] = None, allow_name_change: bool = False, cooperating_responders: bool = False, strict: bool = True, ) -> Awaitable: """Registers service information to the network with a default TTL. Zeroconf will then respond to requests for information for that service. The name of the service may be changed if needed to make it unique on the network. Additionally multiple cooperating responders can register the same service on the network for resilience (if you want this behavior set `cooperating_responders` to `True`).""" if ttl is not None: # ttl argument is used to maintain backward compatibility # Setting TTLs via ServiceInfo is preferred info.host_ttl = ttl info.other_ttl = ttl info.set_server_if_missing() await self.async_wait_for_start() await self.async_check_service(info, allow_name_change, cooperating_responders, strict) self.registry.async_add(info) return asyncio.ensure_future(self._async_broadcast_service(info, _REGISTER_TIME, None)) def update_service(self, info: ServiceInfo) -> None: """Registers service information to the network with a default TTL. Zeroconf will then respond to requests for information for that service. While it is not expected during normal operation, this function may raise EventLoopBlocked if the underlying call to `async_update_service` cannot be completed. """ assert self.loop is not None run_coro_with_timeout( await_awaitable(self.async_update_service(info)), self.loop, _REGISTER_TIME * _REGISTER_BROADCASTS ) async def async_update_service(self, info: ServiceInfo) -> Awaitable: """Registers service information to the network with a default TTL. Zeroconf will then respond to requests for information for that service.""" self.registry.async_update(info) return asyncio.ensure_future(self._async_broadcast_service(info, _REGISTER_TIME, None)) async def async_get_service_info( self, type_: str, name: str, timeout: int = 3000, question_type: Optional[DNSQuestionType] = None ) -> Optional[AsyncServiceInfo]: """Returns network's service information for a particular name and type, or None if no service matches by the timeout, which defaults to 3 seconds. :param type_: fully qualified service type name :param name: the name of the service :param timeout: milliseconds to wait for a response :param question_type: The type of questions to ask (DNSQuestionType.QM or DNSQuestionType.QU) """ info = AsyncServiceInfo(type_, name) if await info.async_request(self, timeout, question_type): return info return None async def _async_broadcast_service( self, info: ServiceInfo, interval: int, ttl: Optional[int], broadcast_addresses: bool = True, ) -> None: """Send a broadcasts to announce a service at intervals.""" for i in range(_REGISTER_BROADCASTS): if i != 0: await asyncio.sleep(millis_to_seconds(interval)) self.async_send(self.generate_service_broadcast(info, ttl, broadcast_addresses)) def generate_service_broadcast( self, info: ServiceInfo, ttl: Optional[int], broadcast_addresses: bool = True, ) -> DNSOutgoing: """Generate a broadcast to announce a service.""" out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) self._add_broadcast_answer(out, info, ttl, broadcast_addresses) return out def generate_service_query(self, info: ServiceInfo) -> DNSOutgoing: # pylint: disable=no-self-use """Generate a query to lookup a service.""" out = DNSOutgoing(_FLAGS_QR_QUERY | _FLAGS_AA) # https://datatracker.ietf.org/doc/html/rfc6762#section-8.1 # Because of the mDNS multicast rate-limiting # rules, the probes SHOULD be sent as "QU" questions with the unicast- # response bit set, to allow a defending host to respond immediately # via unicast, instead of potentially having to wait before replying # via multicast. # # _CLASS_UNIQUE is the "QU" bit out.add_question(DNSQuestion(info.type, _TYPE_PTR, _CLASS_IN | _CLASS_UNIQUE)) out.add_authorative_answer(info.dns_pointer()) return out def _add_broadcast_answer( # pylint: disable=no-self-use self, out: DNSOutgoing, info: ServiceInfo, override_ttl: Optional[int], broadcast_addresses: bool = True, ) -> None: """Add answers to broadcast a service.""" current_time_millis() other_ttl = None if override_ttl is None else override_ttl host_ttl = None if override_ttl is None else override_ttl out.add_answer_at_time(info.dns_pointer(override_ttl=other_ttl), 0) out.add_answer_at_time(info.dns_service(override_ttl=host_ttl), 0) out.add_answer_at_time(info.dns_text(override_ttl=other_ttl), 0) if broadcast_addresses: for record in info.get_address_and_nsec_records(override_ttl=host_ttl): out.add_answer_at_time(record, 0) def unregister_service(self, info: ServiceInfo) -> None: """Unregister a service. While it is not expected during normal operation, this function may raise EventLoopBlocked if the underlying call to `async_unregister_service` cannot be completed. """ assert self.loop is not None run_coro_with_timeout( self.async_unregister_service(info), self.loop, _UNREGISTER_TIME * _REGISTER_BROADCASTS ) async def async_unregister_service(self, info: ServiceInfo) -> Awaitable: """Unregister a service.""" info.set_server_if_missing() self.registry.async_remove(info) # If another server uses the same addresses, we do not want to send # goodbye packets for the address records assert info.server_key is not None entries = self.registry.async_get_infos_server(info.server_key) broadcast_addresses = not bool(entries) return asyncio.ensure_future( self._async_broadcast_service(info, _UNREGISTER_TIME, 0, broadcast_addresses) ) def generate_unregister_all_services(self) -> Optional[DNSOutgoing]: """Generate a DNSOutgoing goodbye for all services and remove them from the registry.""" service_infos = self.registry.async_get_service_infos() if not service_infos: return None out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) for info in service_infos: self._add_broadcast_answer(out, info, 0) self.registry.async_remove(service_infos) return out async def async_unregister_all_services(self) -> None: """Unregister all registered services. Unlike async_register_service and async_unregister_service, this method does not return a future and is always expected to be awaited since its only called at shutdown. """ # Send Goodbye packets https://datatracker.ietf.org/doc/html/rfc6762#section-10.1 out = self.generate_unregister_all_services() if not out: return for i in range(_REGISTER_BROADCASTS): if i != 0: await asyncio.sleep(millis_to_seconds(_UNREGISTER_TIME)) self.async_send(out) def unregister_all_services(self) -> None: """Unregister all registered services. While it is not expected during normal operation, this function may raise EventLoopBlocked if the underlying call to `async_unregister_all_services` cannot be completed. """ assert self.loop is not None run_coro_with_timeout( self.async_unregister_all_services(), self.loop, _UNREGISTER_TIME * _REGISTER_BROADCASTS ) async def async_check_service( self, info: ServiceInfo, allow_name_change: bool, cooperating_responders: bool = False, strict: bool = True, ) -> None: """Checks the network for a unique service name, modifying the ServiceInfo passed in if it is not unique.""" instance_name = instance_name_from_service_info(info, strict=strict) if cooperating_responders: return next_instance_number = 2 next_time = now = current_time_millis() i = 0 while i < _REGISTER_BROADCASTS: # check for a name conflict while self.cache.current_entry_with_name_and_alias(info.type, info.name): if not allow_name_change: raise NonUniqueNameException # change the name and look for a conflict info.name = f'{instance_name}-{next_instance_number}.{info.type}' next_instance_number += 1 service_type_name(info.name, strict=strict) next_time = now i = 0 if now < next_time: await self.async_wait(next_time - now) now = current_time_millis() continue self.async_send(self.generate_service_query(info)) i += 1 next_time += _CHECK_TIME def add_listener( self, listener: RecordUpdateListener, question: Optional[Union[DNSQuestion, List[DNSQuestion]]] ) -> None: """Adds a listener for a given question. The listener will have its update_record method called when information is available to answer the question(s). This function is threadsafe """ assert self.loop is not None self.loop.call_soon_threadsafe(self.record_manager.async_add_listener, listener, question) def remove_listener(self, listener: RecordUpdateListener) -> None: """Removes a listener. This function is threadsafe """ assert self.loop is not None self.loop.call_soon_threadsafe(self.record_manager.async_remove_listener, listener) def async_add_listener( self, listener: RecordUpdateListener, question: Optional[Union[DNSQuestion, List[DNSQuestion]]] ) -> None: """Adds a listener for a given question. The listener will have its update_record method called when information is available to answer the question(s). This function is not threadsafe and must be called in the eventloop. """ self.record_manager.async_add_listener(listener, question) def async_remove_listener(self, listener: RecordUpdateListener) -> None: """Removes a listener. This function is not threadsafe and must be called in the eventloop. """ self.record_manager.async_remove_listener(listener) def send( self, out: DNSOutgoing, addr: Optional[str] = None, port: int = _MDNS_PORT, v6_flow_scope: Union[Tuple[()], Tuple[int, int]] = (), transport: Optional[_WrappedTransport] = None, ) -> None: """Sends an outgoing packet threadsafe.""" assert self.loop is not None self.loop.call_soon_threadsafe(self.async_send, out, addr, port, v6_flow_scope, transport) def async_send( self, out: DNSOutgoing, addr: Optional[str] = None, port: int = _MDNS_PORT, v6_flow_scope: Union[Tuple[()], Tuple[int, int]] = (), transport: Optional[_WrappedTransport] = None, ) -> None: """Sends an outgoing packet.""" if self.done: return # If no transport is specified, we send to all the ones # with the same address family transports = [transport] if transport else self.engine.senders log_debug = log.isEnabledFor(logging.DEBUG) for packet_num, packet in enumerate(out.packets()): if len(packet) > _MAX_MSG_ABSOLUTE: self.log_warning_once("Dropping %r over-sized packet (%d bytes) %r", out, len(packet), packet) return for send_transport in transports: async_send_with_transport( log_debug, send_transport, packet, packet_num, out, addr, port, v6_flow_scope ) def _close(self) -> None: """Set global done and remove all service listeners.""" if self.done: return self.remove_all_service_listeners() self.done = True def _shutdown_threads(self) -> None: """Shutdown any threads.""" self.notify_all() if not self._loop_thread: return assert self.loop is not None shutdown_loop(self.loop) self._loop_thread.join() self._loop_thread = None def close(self) -> None: """Ends the background threads, and prevent this instance from servicing further queries. This method is idempotent and irreversible. """ assert self.loop is not None if self.loop.is_running(): if self.loop == get_running_loop(): log.warning( "unregister_all_services skipped as it does blocking i/o; use AsyncZeroconf with asyncio" ) else: self.unregister_all_services() self._close() self.engine.close() self._shutdown_threads() async def _async_close(self) -> None: """Ends the background threads, and prevent this instance from servicing further queries. This method is idempotent and irreversible. This call only intended to be used by AsyncZeroconf Callers are responsible for unregistering all services before calling this function """ self._close() await self.engine._async_close() # pylint: disable=protected-access self._shutdown_threads() def __enter__(self) -> 'Zeroconf': return self def __exit__( # pylint: disable=useless-return self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: self.close() return None 07070100000029000081A40000000000000000000000016619D4CC00000C27000000000000000000000000000000000000002E00000000python-zeroconf-0.132.2/src/zeroconf/_dns.pxd import cython from ._protocol.outgoing cimport DNSOutgoing cdef cython.uint _LEN_BYTE cdef cython.uint _LEN_SHORT cdef cython.uint _LEN_INT cdef cython.uint _NAME_COMPRESSION_MIN_SIZE cdef cython.uint _BASE_MAX_SIZE cdef cython.uint _EXPIRE_FULL_TIME_MS cdef cython.uint _EXPIRE_STALE_TIME_MS cdef cython.uint _RECENT_TIME_MS cdef cython.uint _TYPE_ANY cdef cython.uint _CLASS_UNIQUE cdef cython.uint _CLASS_MASK cdef object current_time_millis cdef class DNSEntry: cdef public str key cdef public str name cdef public cython.uint type cdef public cython.uint class_ cdef public bint unique cdef _set_class(self, cython.uint class_) cdef bint _dns_entry_matches(self, DNSEntry other) cdef class DNSQuestion(DNSEntry): cdef public cython.int _hash cpdef bint answered_by(self, DNSRecord rec) cdef class DNSRecord(DNSEntry): cdef public cython.float ttl cdef public double created cdef bint _suppressed_by_answer(self, DNSRecord answer) @cython.locals( answers=cython.list, ) cpdef bint suppressed_by(self, object msg) cpdef get_remaining_ttl(self, double now) cpdef double get_expiration_time(self, cython.uint percent) cpdef bint is_expired(self, double now) cpdef bint is_stale(self, double now) cpdef bint is_recent(self, double now) cpdef reset_ttl(self, DNSRecord other) cpdef set_created_ttl(self, double now, cython.float ttl) cdef class DNSAddress(DNSRecord): cdef public cython.int _hash cdef public object address cdef public object scope_id cdef bint _eq(self, DNSAddress other) cpdef write(self, DNSOutgoing out) cdef class DNSHinfo(DNSRecord): cdef public cython.int _hash cdef public str cpu cdef public str os cdef bint _eq(self, DNSHinfo other) cpdef write(self, DNSOutgoing out) cdef class DNSPointer(DNSRecord): cdef public cython.int _hash cdef public str alias cdef public str alias_key cdef bint _eq(self, DNSPointer other) cpdef write(self, DNSOutgoing out) cdef class DNSText(DNSRecord): cdef public cython.int _hash cdef public bytes text cdef bint _eq(self, DNSText other) cpdef write(self, DNSOutgoing out) cdef class DNSService(DNSRecord): cdef public cython.int _hash cdef public cython.uint priority cdef public cython.uint weight cdef public cython.uint port cdef public str server cdef public str server_key cdef bint _eq(self, DNSService other) cpdef write(self, DNSOutgoing out) cdef class DNSNsec(DNSRecord): cdef public cython.int _hash cdef public object next_name cdef public cython.list rdtypes cdef bint _eq(self, DNSNsec other) cpdef write(self, DNSOutgoing out) cdef class DNSRRSet: cdef cython.list _records cdef cython.dict _lookup @cython.locals(other=DNSRecord) cpdef bint suppresses(self, DNSRecord record) @cython.locals( record=DNSRecord, record_sets=cython.list, ) cdef cython.dict _get_lookup(self) cpdef cython.set lookup_set(self) 0707010000002A000081A40000000000000000000000016619D4CC00004907000000000000000000000000000000000000002D00000000python-zeroconf-0.132.2/src/zeroconf/_dns.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import enum import socket from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union, cast from ._exceptions import AbstractMethodException from ._utils.net import _is_v6_address from ._utils.time import current_time_millis from .const import _CLASS_MASK, _CLASS_UNIQUE, _CLASSES, _TYPE_ANY, _TYPES _LEN_BYTE = 1 _LEN_SHORT = 2 _LEN_INT = 4 _BASE_MAX_SIZE = _LEN_SHORT + _LEN_SHORT + _LEN_INT + _LEN_SHORT # type # class # ttl # length _NAME_COMPRESSION_MIN_SIZE = _LEN_BYTE * 2 _EXPIRE_FULL_TIME_MS = 1000 _EXPIRE_STALE_TIME_MS = 500 _RECENT_TIME_MS = 250 _float = float _int = int if TYPE_CHECKING: from ._protocol.incoming import DNSIncoming from ._protocol.outgoing import DNSOutgoing @enum.unique class DNSQuestionType(enum.Enum): """An MDNS question type. "QU" - questions requesting unicast responses "QM" - questions requesting multicast responses https://datatracker.ietf.org/doc/html/rfc6762#section-5.4 """ QU = 1 QM = 2 class DNSEntry: """A DNS entry""" __slots__ = ('key', 'name', 'type', 'class_', 'unique') def __init__(self, name: str, type_: int, class_: int) -> None: self.name = name self.key = name.lower() self.type = type_ self._set_class(class_) def _set_class(self, class_: _int) -> None: self.class_ = class_ & _CLASS_MASK self.unique = (class_ & _CLASS_UNIQUE) != 0 def _dns_entry_matches(self, other) -> bool: # type: ignore[no-untyped-def] return self.key == other.key and self.type == other.type and self.class_ == other.class_ def __eq__(self, other: Any) -> bool: """Equality test on key (lowercase name), type, and class""" return isinstance(other, DNSEntry) and self._dns_entry_matches(other) @staticmethod def get_class_(class_: int) -> str: """Class accessor""" return _CLASSES.get(class_, f"?({class_})") @staticmethod def get_type(t: int) -> str: """Type accessor""" return _TYPES.get(t, f"?({t})") def entry_to_string(self, hdr: str, other: Optional[Union[bytes, str]]) -> str: """String representation with additional information""" return "{}[{},{}{},{}]{}".format( hdr, self.get_type(self.type), self.get_class_(self.class_), "-unique" if self.unique else "", self.name, "=%s" % cast(Any, other) if other is not None else "", ) class DNSQuestion(DNSEntry): """A DNS question entry""" __slots__ = ('_hash',) def __init__(self, name: str, type_: int, class_: int) -> None: super().__init__(name, type_, class_) self._hash = hash((self.key, type_, self.class_)) def answered_by(self, rec: 'DNSRecord') -> bool: """Returns true if the question is answered by the record""" return self.class_ == rec.class_ and self.type in (rec.type, _TYPE_ANY) and self.name == rec.name def __hash__(self) -> int: return self._hash def __eq__(self, other: Any) -> bool: """Tests equality on dns question.""" return isinstance(other, DNSQuestion) and self._dns_entry_matches(other) @property def max_size(self) -> int: """Maximum size of the question in the packet.""" return len(self.name.encode('utf-8')) + _LEN_BYTE + _LEN_SHORT + _LEN_SHORT # type # class @property def unicast(self) -> bool: """Returns true if the QU (not QM) is set. unique shares the same mask as the one used for unicast. """ return self.unique @unicast.setter def unicast(self, value: bool) -> None: """Sets the QU bit (not QM).""" self.unique = value def __repr__(self) -> str: """String representation""" return "{}[question,{},{},{}]".format( self.get_type(self.type), "QU" if self.unicast else "QM", self.get_class_(self.class_), self.name, ) class DNSRecord(DNSEntry): """A DNS record - like a DNS entry, but has a TTL""" __slots__ = ('ttl', 'created') # TODO: Switch to just int ttl def __init__( self, name: str, type_: int, class_: int, ttl: Union[float, int], created: Optional[float] = None ) -> None: super().__init__(name, type_, class_) self.ttl = ttl self.created = created or current_time_millis() def __eq__(self, other: Any) -> bool: # pylint: disable=no-self-use """Abstract method""" raise AbstractMethodException def suppressed_by(self, msg: 'DNSIncoming') -> bool: """Returns true if any answer in a message can suffice for the information held in this record.""" answers = msg.answers() for record in answers: if self._suppressed_by_answer(record): return True return False def _suppressed_by_answer(self, other) -> bool: # type: ignore[no-untyped-def] """Returns true if another record has same name, type and class, and if its TTL is at least half of this record's.""" return self == other and other.ttl > (self.ttl / 2) def get_expiration_time(self, percent: _int) -> float: """Returns the time at which this record will have expired by a certain percentage.""" return self.created + (percent * self.ttl * 10) # TODO: Switch to just int here def get_remaining_ttl(self, now: _float) -> Union[int, float]: """Returns the remaining TTL in seconds.""" remain = (self.created + (_EXPIRE_FULL_TIME_MS * self.ttl) - now) / 1000.0 return 0 if remain < 0 else remain def is_expired(self, now: _float) -> bool: """Returns true if this record has expired.""" return self.created + (_EXPIRE_FULL_TIME_MS * self.ttl) <= now def is_stale(self, now: _float) -> bool: """Returns true if this record is at least half way expired.""" return self.created + (_EXPIRE_STALE_TIME_MS * self.ttl) <= now def is_recent(self, now: _float) -> bool: """Returns true if the record more than one quarter of its TTL remaining.""" return self.created + (_RECENT_TIME_MS * self.ttl) > now def reset_ttl(self, other) -> None: # type: ignore[no-untyped-def] """Sets this record's TTL and created time to that of another record.""" self.set_created_ttl(other.created, other.ttl) def set_created_ttl(self, created: _float, ttl: Union[float, int]) -> None: """Set the created and ttl of a record.""" self.created = created self.ttl = ttl def write(self, out: 'DNSOutgoing') -> None: # pylint: disable=no-self-use """Abstract method""" raise AbstractMethodException def to_string(self, other: Union[bytes, str]) -> str: """String representation with additional information""" arg = f"{self.ttl}/{int(self.get_remaining_ttl(current_time_millis()))},{cast(Any, other)}" return DNSEntry.entry_to_string(self, "record", arg) class DNSAddress(DNSRecord): """A DNS address record""" __slots__ = ('_hash', 'address', 'scope_id') def __init__( self, name: str, type_: int, class_: int, ttl: int, address: bytes, scope_id: Optional[int] = None, created: Optional[float] = None, ) -> None: super().__init__(name, type_, class_, ttl, created) self.address = address self.scope_id = scope_id self._hash = hash((self.key, type_, self.class_, address, scope_id)) def write(self, out: 'DNSOutgoing') -> None: """Used in constructing an outgoing packet""" out.write_string(self.address) def __eq__(self, other: Any) -> bool: """Tests equality on address""" return isinstance(other, DNSAddress) and self._eq(other) def _eq(self, other) -> bool: # type: ignore[no-untyped-def] return ( self.address == other.address and self.scope_id == other.scope_id and self._dns_entry_matches(other) ) def __hash__(self) -> int: """Hash to compare like DNSAddresses.""" return self._hash def __repr__(self) -> str: """String representation""" try: return self.to_string( socket.inet_ntop( socket.AF_INET6 if _is_v6_address(self.address) else socket.AF_INET, self.address ) ) except (ValueError, OSError): return self.to_string(str(self.address)) class DNSHinfo(DNSRecord): """A DNS host information record""" __slots__ = ('_hash', 'cpu', 'os') def __init__( self, name: str, type_: int, class_: int, ttl: int, cpu: str, os: str, created: Optional[float] = None ) -> None: super().__init__(name, type_, class_, ttl, created) self.cpu = cpu self.os = os self._hash = hash((self.key, type_, self.class_, cpu, os)) def write(self, out: 'DNSOutgoing') -> None: """Used in constructing an outgoing packet""" out.write_character_string(self.cpu.encode('utf-8')) out.write_character_string(self.os.encode('utf-8')) def __eq__(self, other: Any) -> bool: """Tests equality on cpu and os.""" return isinstance(other, DNSHinfo) and self._eq(other) def _eq(self, other) -> bool: # type: ignore[no-untyped-def] """Tests equality on cpu and os.""" return self.cpu == other.cpu and self.os == other.os and self._dns_entry_matches(other) def __hash__(self) -> int: """Hash to compare like DNSHinfo.""" return self._hash def __repr__(self) -> str: """String representation""" return self.to_string(self.cpu + " " + self.os) class DNSPointer(DNSRecord): """A DNS pointer record""" __slots__ = ('_hash', 'alias', 'alias_key') def __init__( self, name: str, type_: int, class_: int, ttl: int, alias: str, created: Optional[float] = None ) -> None: super().__init__(name, type_, class_, ttl, created) self.alias = alias self.alias_key = alias.lower() self._hash = hash((self.key, type_, self.class_, self.alias_key)) @property def max_size_compressed(self) -> int: """Maximum size of the record in the packet assuming the name has been compressed.""" return ( _BASE_MAX_SIZE + _NAME_COMPRESSION_MIN_SIZE + (len(self.alias) - len(self.name)) + _NAME_COMPRESSION_MIN_SIZE ) def write(self, out: 'DNSOutgoing') -> None: """Used in constructing an outgoing packet""" out.write_name(self.alias) def __eq__(self, other: Any) -> bool: """Tests equality on alias.""" return isinstance(other, DNSPointer) and self._eq(other) def _eq(self, other) -> bool: # type: ignore[no-untyped-def] """Tests equality on alias.""" return self.alias_key == other.alias_key and self._dns_entry_matches(other) def __hash__(self) -> int: """Hash to compare like DNSPointer.""" return self._hash def __repr__(self) -> str: """String representation""" return self.to_string(self.alias) class DNSText(DNSRecord): """A DNS text record""" __slots__ = ('_hash', 'text') def __init__( self, name: str, type_: int, class_: int, ttl: int, text: bytes, created: Optional[float] = None ) -> None: super().__init__(name, type_, class_, ttl, created) self.text = text self._hash = hash((self.key, type_, self.class_, text)) def write(self, out: 'DNSOutgoing') -> None: """Used in constructing an outgoing packet""" out.write_string(self.text) def __hash__(self) -> int: """Hash to compare like DNSText.""" return self._hash def __eq__(self, other: Any) -> bool: """Tests equality on text.""" return isinstance(other, DNSText) and self._eq(other) def _eq(self, other) -> bool: # type: ignore[no-untyped-def] """Tests equality on text.""" return self.text == other.text and self._dns_entry_matches(other) def __repr__(self) -> str: """String representation""" if len(self.text) > 10: return self.to_string(self.text[:7]) + "..." return self.to_string(self.text) class DNSService(DNSRecord): """A DNS service record""" __slots__ = ('_hash', 'priority', 'weight', 'port', 'server', 'server_key') def __init__( self, name: str, type_: int, class_: int, ttl: Union[float, int], priority: int, weight: int, port: int, server: str, created: Optional[float] = None, ) -> None: super().__init__(name, type_, class_, ttl, created) self.priority = priority self.weight = weight self.port = port self.server = server self.server_key = server.lower() self._hash = hash((self.key, type_, self.class_, priority, weight, port, self.server_key)) def write(self, out: 'DNSOutgoing') -> None: """Used in constructing an outgoing packet""" out.write_short(self.priority) out.write_short(self.weight) out.write_short(self.port) out.write_name(self.server) def __eq__(self, other: Any) -> bool: """Tests equality on priority, weight, port and server""" return isinstance(other, DNSService) and self._eq(other) def _eq(self, other) -> bool: # type: ignore[no-untyped-def] """Tests equality on priority, weight, port and server.""" return ( self.priority == other.priority and self.weight == other.weight and self.port == other.port and self.server_key == other.server_key and self._dns_entry_matches(other) ) def __hash__(self) -> int: """Hash to compare like DNSService.""" return self._hash def __repr__(self) -> str: """String representation""" return self.to_string(f"{self.server}:{self.port}") class DNSNsec(DNSRecord): """A DNS NSEC record""" __slots__ = ('_hash', 'next_name', 'rdtypes') def __init__( self, name: str, type_: int, class_: int, ttl: int, next_name: str, rdtypes: List[int], created: Optional[float] = None, ) -> None: super().__init__(name, type_, class_, ttl, created) self.next_name = next_name self.rdtypes = sorted(rdtypes) self._hash = hash((self.key, type_, self.class_, next_name, *self.rdtypes)) def write(self, out: 'DNSOutgoing') -> None: """Used in constructing an outgoing packet.""" bitmap = bytearray(b'\0' * 32) total_octets = 0 for rdtype in self.rdtypes: if rdtype > 255: # mDNS only supports window 0 raise ValueError(f"rdtype {rdtype} is too large for NSEC") byte = rdtype // 8 total_octets = byte + 1 bitmap[byte] |= 0x80 >> (rdtype % 8) if total_octets == 0: # NSEC must have at least one rdtype # Writing an empty bitmap is not allowed raise ValueError("NSEC must have at least one rdtype") out_bytes = bytes(bitmap[0:total_octets]) out.write_name(self.next_name) out._write_byte(0) # Always window 0 out._write_byte(len(out_bytes)) out.write_string(out_bytes) def __eq__(self, other: Any) -> bool: """Tests equality on next_name and rdtypes.""" return isinstance(other, DNSNsec) and self._eq(other) def _eq(self, other) -> bool: # type: ignore[no-untyped-def] """Tests equality on next_name and rdtypes.""" return ( self.next_name == other.next_name and self.rdtypes == other.rdtypes and self._dns_entry_matches(other) ) def __hash__(self) -> int: """Hash to compare like DNSNSec.""" return self._hash def __repr__(self) -> str: """String representation""" return self.to_string( self.next_name + "," + "|".join([self.get_type(type_) for type_ in self.rdtypes]) ) _DNSRecord = DNSRecord class DNSRRSet: """A set of dns records with a lookup to get the ttl.""" __slots__ = ('_records', '_lookup') def __init__(self, records: List[DNSRecord]) -> None: """Create an RRset from records sets.""" self._records = records self._lookup: Optional[Dict[DNSRecord, DNSRecord]] = None @property def lookup(self) -> Dict[DNSRecord, DNSRecord]: """Return the lookup table.""" return self._get_lookup() def lookup_set(self) -> Set[DNSRecord]: """Return the lookup table as aset.""" return set(self._get_lookup()) def _get_lookup(self) -> Dict[DNSRecord, DNSRecord]: """Return the lookup table, building it if needed.""" if self._lookup is None: # Build the hash table so we can lookup the record ttl self._lookup = {record: record for record in self._records} return self._lookup def suppresses(self, record: _DNSRecord) -> bool: """Returns true if any answer in the rrset can suffice for the information held in this record.""" lookup = self._get_lookup() other = lookup.get(record) if other is None: return False return other.ttl > (record.ttl / 2) 0707010000002B000081A40000000000000000000000016619D4CC00001711000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/src/zeroconf/_engine.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import itertools import socket import threading from typing import TYPE_CHECKING, List, Optional, cast from ._record_update import RecordUpdate from ._utils.asyncio import get_running_loop, run_coro_with_timeout from ._utils.time import current_time_millis from .const import _CACHE_CLEANUP_INTERVAL if TYPE_CHECKING: from ._core import Zeroconf from ._listener import AsyncListener from ._transport import _WrappedTransport, make_wrapped_transport _CLOSE_TIMEOUT = 3000 # ms class AsyncEngine: """An engine wraps sockets in the event loop.""" __slots__ = ( 'loop', 'zc', 'protocols', 'readers', 'senders', 'running_event', '_listen_socket', '_respond_sockets', '_cleanup_timer', ) def __init__( self, zeroconf: 'Zeroconf', listen_socket: Optional[socket.socket], respond_sockets: List[socket.socket], ) -> None: self.loop: Optional[asyncio.AbstractEventLoop] = None self.zc = zeroconf self.protocols: List[AsyncListener] = [] self.readers: List[_WrappedTransport] = [] self.senders: List[_WrappedTransport] = [] self.running_event: Optional[asyncio.Event] = None self._listen_socket = listen_socket self._respond_sockets = respond_sockets self._cleanup_timer: Optional[asyncio.TimerHandle] = None def setup(self, loop: asyncio.AbstractEventLoop, loop_thread_ready: Optional[threading.Event]) -> None: """Set up the instance.""" self.loop = loop self.running_event = asyncio.Event() self.loop.create_task(self._async_setup(loop_thread_ready)) async def _async_setup(self, loop_thread_ready: Optional[threading.Event]) -> None: """Set up the instance.""" self._async_schedule_next_cache_cleanup() await self._async_create_endpoints() assert self.running_event is not None self.running_event.set() if loop_thread_ready: loop_thread_ready.set() async def _async_create_endpoints(self) -> None: """Create endpoints to send and receive.""" assert self.loop is not None loop = self.loop reader_sockets = [] sender_sockets = [] if self._listen_socket: reader_sockets.append(self._listen_socket) for s in self._respond_sockets: if s not in reader_sockets: reader_sockets.append(s) sender_sockets.append(s) for s in reader_sockets: transport, protocol = await loop.create_datagram_endpoint( lambda: AsyncListener(self.zc), sock=s # type: ignore[arg-type, return-value] ) self.protocols.append(cast(AsyncListener, protocol)) self.readers.append(make_wrapped_transport(cast(asyncio.DatagramTransport, transport))) if s in sender_sockets: self.senders.append(make_wrapped_transport(cast(asyncio.DatagramTransport, transport))) def _async_cache_cleanup(self) -> None: """Periodic cache cleanup.""" now = current_time_millis() self.zc.question_history.async_expire(now) self.zc.record_manager.async_updates( now, [RecordUpdate(record, record) for record in self.zc.cache.async_expire(now)] ) self.zc.record_manager.async_updates_complete(False) self._async_schedule_next_cache_cleanup() def _async_schedule_next_cache_cleanup(self) -> None: """Schedule the next cache cleanup.""" loop = self.loop assert loop is not None self._cleanup_timer = loop.call_at(loop.time() + _CACHE_CLEANUP_INTERVAL, self._async_cache_cleanup) async def _async_close(self) -> None: """Cancel and wait for the cleanup task to finish.""" self._async_shutdown() await asyncio.sleep(0) # flush out any call soons assert self._cleanup_timer is not None self._cleanup_timer.cancel() def _async_shutdown(self) -> None: """Shutdown transports and sockets.""" assert self.running_event is not None self.running_event.clear() for wrapped_transport in itertools.chain(self.senders, self.readers): wrapped_transport.transport.close() def close(self) -> None: """Close from sync context. While it is not expected during normal operation, this function may raise EventLoopBlocked if the underlying call to `_async_close` cannot be completed. """ assert self.loop is not None # Guard against Zeroconf.close() being called from the eventloop if get_running_loop() == self.loop: self._async_shutdown() return if not self.loop.is_running(): return run_coro_with_timeout(self._async_close(), self.loop, _CLOSE_TIMEOUT) 0707010000002C000081A40000000000000000000000016619D4CC00000877000000000000000000000000000000000000003400000000python-zeroconf-0.132.2/src/zeroconf/_exceptions.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ class Error(Exception): """Base class for all zeroconf exceptions.""" class IncomingDecodeError(Error): """Exception when there is invalid data in an incoming packet.""" class NonUniqueNameException(Error): """Exception when the name is already registered.""" class NamePartTooLongException(Error): """Exception when the name is too long.""" class AbstractMethodException(Error): """Exception when a required method is not implemented.""" class BadTypeInNameException(Error): """Exception when the type in a name is invalid.""" class ServiceNameAlreadyRegistered(Error): """Exception when a service name is already registered.""" class EventLoopBlocked(Error): """Exception when the event loop is blocked. This exception is never expected to be thrown during normal operation. It should only happen when the cpu is maxed out or there is something blocking the event loop. """ class NotRunningException(Error): """Exception when an action is called with a zeroconf instance that is not running. The instance may not be running because it was already shutdown or startup has failed in some unexpected way. """ 0707010000002D000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002F00000000python-zeroconf-0.132.2/src/zeroconf/_handlers0707010000002E000081A40000000000000000000000016619D4CC000003CB000000000000000000000000000000000000003B00000000python-zeroconf-0.132.2/src/zeroconf/_handlers/__init__.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ 0707010000002F000081A40000000000000000000000016619D4CC0000033A000000000000000000000000000000000000003B00000000python-zeroconf-0.132.2/src/zeroconf/_handlers/answers.pxd import cython from .._dns cimport DNSRecord from .._protocol.outgoing cimport DNSOutgoing cdef class QuestionAnswers: cdef public dict ucast cdef public dict mcast_now cdef public dict mcast_aggregate cdef public dict mcast_aggregate_last_second cdef class AnswerGroup: cdef public double send_after cdef public double send_before cdef public cython.dict answers cdef object _FLAGS_QR_RESPONSE_AA cdef object NAME_GETTER cpdef DNSOutgoing construct_outgoing_multicast_answers(cython.dict answers) cpdef DNSOutgoing construct_outgoing_unicast_answers( cython.dict answers, bint ucast_source, cython.list questions, object id_ ) @cython.locals(answer=DNSRecord, additionals=cython.set, additional=DNSRecord) cdef void _add_answers_additionals(DNSOutgoing out, cython.dict answers) 07070100000030000081A40000000000000000000000016619D4CC000010DC000000000000000000000000000000000000003A00000000python-zeroconf-0.132.2/src/zeroconf/_handlers/answers.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from operator import attrgetter from typing import Dict, List, Set from .._dns import DNSQuestion, DNSRecord from .._protocol.outgoing import DNSOutgoing from ..const import _FLAGS_AA, _FLAGS_QR_RESPONSE _AnswerWithAdditionalsType = Dict[DNSRecord, Set[DNSRecord]] int_ = int MULTICAST_DELAY_RANDOM_INTERVAL = (20, 120) NAME_GETTER = attrgetter('name') _FLAGS_QR_RESPONSE_AA = _FLAGS_QR_RESPONSE | _FLAGS_AA float_ = float class QuestionAnswers: """A group of answers to a question.""" __slots__ = ('ucast', 'mcast_now', 'mcast_aggregate', 'mcast_aggregate_last_second') def __init__( self, ucast: _AnswerWithAdditionalsType, mcast_now: _AnswerWithAdditionalsType, mcast_aggregate: _AnswerWithAdditionalsType, mcast_aggregate_last_second: _AnswerWithAdditionalsType, ) -> None: """Initialize a QuestionAnswers.""" self.ucast = ucast self.mcast_now = mcast_now self.mcast_aggregate = mcast_aggregate self.mcast_aggregate_last_second = mcast_aggregate_last_second def __repr__(self) -> str: """Return a string representation of this QuestionAnswers.""" return ( f'QuestionAnswers(ucast={self.ucast}, mcast_now={self.mcast_now}, ' f'mcast_aggregate={self.mcast_aggregate}, ' f'mcast_aggregate_last_second={self.mcast_aggregate_last_second})' ) class AnswerGroup: """A group of answers scheduled to be sent at the same time.""" __slots__ = ('send_after', 'send_before', 'answers') def __init__(self, send_after: float_, send_before: float_, answers: _AnswerWithAdditionalsType) -> None: self.send_after = send_after # Must be sent after this time self.send_before = send_before # Must be sent before this time self.answers = answers def construct_outgoing_multicast_answers(answers: _AnswerWithAdditionalsType) -> DNSOutgoing: """Add answers and additionals to a DNSOutgoing.""" out = DNSOutgoing(_FLAGS_QR_RESPONSE_AA, True) _add_answers_additionals(out, answers) return out def construct_outgoing_unicast_answers( answers: _AnswerWithAdditionalsType, ucast_source: bool, questions: List[DNSQuestion], id_: int_ ) -> DNSOutgoing: """Add answers and additionals to a DNSOutgoing.""" out = DNSOutgoing(_FLAGS_QR_RESPONSE_AA, False, id_) # Adding the questions back when the source is legacy unicast behavior if ucast_source: for question in questions: out.add_question(question) _add_answers_additionals(out, answers) return out def _add_answers_additionals(out: DNSOutgoing, answers: _AnswerWithAdditionalsType) -> None: # Find additionals and suppress any additionals that are already in answers sending: Set[DNSRecord] = set(answers) # Answers are sorted to group names together to increase the chance # that similar names will end up in the same packet and can reduce the # overall size of the outgoing response via name compression for answer in sorted(answers, key=NAME_GETTER): out.add_answer_at_time(answer, 0) additionals = answers[answer] for additional in additionals: if additional not in sending: out.add_additional_answer(additional) sending.add(additional) 07070100000031000081A40000000000000000000000016619D4CC00000307000000000000000000000000000000000000004C00000000python-zeroconf-0.132.2/src/zeroconf/_handlers/multicast_outgoing_queue.pxd import cython from .._utils.time cimport current_time_millis, millis_to_seconds from .answers cimport AnswerGroup, construct_outgoing_multicast_answers cdef bint TYPE_CHECKING cdef tuple MULTICAST_DELAY_RANDOM_INTERVAL cdef object RAND_INT cdef class MulticastOutgoingQueue: cdef object zc cdef public object queue cdef public object _multicast_delay_random_min cdef public object _multicast_delay_random_max cdef object _additional_delay cdef object _aggregation_delay @cython.locals(last_group=AnswerGroup, random_int=cython.uint) cpdef void async_add(self, double now, cython.dict answers) @cython.locals(pending=AnswerGroup) cdef void _remove_answers_from_queue(self, cython.dict answers) cpdef void async_ready(self) 07070100000032000081A40000000000000000000000016619D4CC000013A4000000000000000000000000000000000000004B00000000python-zeroconf-0.132.2/src/zeroconf/_handlers/multicast_outgoing_queue.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import random from collections import deque from typing import TYPE_CHECKING from .._utils.time import current_time_millis, millis_to_seconds from .answers import ( MULTICAST_DELAY_RANDOM_INTERVAL, AnswerGroup, _AnswerWithAdditionalsType, construct_outgoing_multicast_answers, ) RAND_INT = random.randint if TYPE_CHECKING: from .._core import Zeroconf _float = float _int = int class MulticastOutgoingQueue: """An outgoing queue used to aggregate multicast responses.""" __slots__ = ( "zc", "queue", "_multicast_delay_random_min", "_multicast_delay_random_max", "_additional_delay", "_aggregation_delay", ) def __init__(self, zeroconf: 'Zeroconf', additional_delay: _int, max_aggregation_delay: _int) -> None: self.zc = zeroconf self.queue: deque[AnswerGroup] = deque() # Additional delay is used to implement # Protect the network against excessive packet flooding # https://datatracker.ietf.org/doc/html/rfc6762#section-14 self._multicast_delay_random_min = MULTICAST_DELAY_RANDOM_INTERVAL[0] self._multicast_delay_random_max = MULTICAST_DELAY_RANDOM_INTERVAL[1] self._additional_delay = additional_delay self._aggregation_delay = max_aggregation_delay def async_add(self, now: _float, answers: _AnswerWithAdditionalsType) -> None: """Add a group of answers with additionals to the outgoing queue.""" loop = self.zc.loop if TYPE_CHECKING: assert loop is not None random_int = RAND_INT(self._multicast_delay_random_min, self._multicast_delay_random_max) random_delay = random_int + self._additional_delay send_after = now + random_delay send_before = now + self._aggregation_delay + self._additional_delay if len(self.queue): # If we calculate a random delay for the send after time # that is less than the last group scheduled to go out, # we instead add the answers to the last group as this # allows aggregating additional responses last_group = self.queue[-1] if send_after <= last_group.send_after: last_group.answers.update(answers) return else: loop.call_at(loop.time() + millis_to_seconds(random_delay), self.async_ready) self.queue.append(AnswerGroup(send_after, send_before, answers)) def _remove_answers_from_queue(self, answers: _AnswerWithAdditionalsType) -> None: """Remove a set of answers from the outgoing queue.""" for pending in self.queue: for record in answers: pending.answers.pop(record, None) def async_ready(self) -> None: """Process anything in the queue that is ready.""" zc = self.zc loop = zc.loop if TYPE_CHECKING: assert loop is not None now = current_time_millis() if len(self.queue) > 1 and self.queue[0].send_before > now: # There is more than one answer in the queue, # delay until we have to send it (first answer group reaches send_before) loop.call_at(loop.time() + millis_to_seconds(self.queue[0].send_before - now), self.async_ready) return answers: _AnswerWithAdditionalsType = {} # Add all groups that can be sent now while len(self.queue) and self.queue[0].send_after <= now: answers.update(self.queue.popleft().answers) if len(self.queue): # If there are still groups in the queue that are not ready to send # be sure we schedule them to go out later loop.call_at(loop.time() + millis_to_seconds(self.queue[0].send_after - now), self.async_ready) if answers: # pragma: no branch # If we have the same answer scheduled to go out, remove them self._remove_answers_from_queue(answers) zc.async_send(construct_outgoing_multicast_answers(answers)) 07070100000033000081A40000000000000000000000016619D4CC00000F42000000000000000000000000000000000000004100000000python-zeroconf-0.132.2/src/zeroconf/_handlers/query_handler.pxd import cython from .._cache cimport DNSCache from .._dns cimport DNSAddress, DNSPointer, DNSQuestion, DNSRecord, DNSRRSet from .._history cimport QuestionHistory from .._protocol.incoming cimport DNSIncoming from .._services.info cimport ServiceInfo from .._services.registry cimport ServiceRegistry from .answers cimport ( QuestionAnswers, construct_outgoing_multicast_answers, construct_outgoing_unicast_answers, ) from .multicast_outgoing_queue cimport MulticastOutgoingQueue cdef bint TYPE_CHECKING cdef cython.uint _ONE_SECOND, _TYPE_PTR, _TYPE_ANY, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT cdef str _SERVICE_TYPE_ENUMERATION_NAME cdef cython.set _RESPOND_IMMEDIATE_TYPES cdef cython.set _ADDRESS_RECORD_TYPES cdef object IPVersion, _IPVersion_ALL cdef object _TYPE_PTR, _CLASS_IN, _DNS_OTHER_TTL cdef unsigned int _ANSWER_STRATEGY_SERVICE_TYPE_ENUMERATION cdef unsigned int _ANSWER_STRATEGY_POINTER cdef unsigned int _ANSWER_STRATEGY_ADDRESS cdef unsigned int _ANSWER_STRATEGY_SERVICE cdef unsigned int _ANSWER_STRATEGY_TEXT cdef list _EMPTY_SERVICES_LIST cdef list _EMPTY_TYPES_LIST cdef class _AnswerStrategy: cdef public DNSQuestion question cdef public unsigned int strategy_type cdef public list types cdef public list services cdef class _QueryResponse: cdef bint _is_probe cdef cython.list _questions cdef double _now cdef DNSCache _cache cdef cython.dict _additionals cdef cython.set _ucast cdef cython.set _mcast_now cdef cython.set _mcast_aggregate cdef cython.set _mcast_aggregate_last_second @cython.locals(record=DNSRecord) cdef void add_qu_question_response(self, cython.dict answers) cdef void add_ucast_question_response(self, cython.dict answers) @cython.locals(answer=DNSRecord, question=DNSQuestion) cdef void add_mcast_question_response(self, cython.dict answers) @cython.locals(maybe_entry=DNSRecord) cdef bint _has_mcast_within_one_quarter_ttl(self, DNSRecord record) @cython.locals(maybe_entry=DNSRecord) cdef bint _has_mcast_record_in_last_second(self, DNSRecord record) cdef QuestionAnswers answers(self) cdef class QueryHandler: cdef object zc cdef ServiceRegistry registry cdef DNSCache cache cdef QuestionHistory question_history cdef MulticastOutgoingQueue out_queue cdef MulticastOutgoingQueue out_delay_queue @cython.locals(service=ServiceInfo) cdef void _add_service_type_enumeration_query_answers(self, list types, cython.dict answer_set, DNSRRSet known_answers) @cython.locals(service=ServiceInfo) cdef void _add_pointer_answers(self, list services, cython.dict answer_set, DNSRRSet known_answers) @cython.locals(service=ServiceInfo, dns_address=DNSAddress) cdef void _add_address_answers(self, list services, cython.dict answer_set, DNSRRSet known_answers, cython.uint type_) @cython.locals(question_lower_name=str, type_=cython.uint, service=ServiceInfo) cdef cython.dict _answer_question(self, DNSQuestion question, unsigned int strategy_type, list types, list services, DNSRRSet known_answers) @cython.locals( msg=DNSIncoming, msgs=list, strategy=_AnswerStrategy, question=DNSQuestion, answer_set=cython.dict, known_answers=DNSRRSet, known_answers_set=cython.set, is_unicast=bint, is_probe=object, now=double ) cpdef QuestionAnswers async_response(self, cython.list msgs, cython.bint unicast_source) @cython.locals(name=str, question_lower_name=str) cdef list _get_answer_strategies(self, DNSQuestion question) @cython.locals( first_packet=DNSIncoming, ucast_source=bint, ) cpdef void handle_assembled_query( self, list packets, object addr, object port, object transport, tuple v6_flow_scope ) 07070100000034000081A40000000000000000000000016619D4CC000044F0000000000000000000000000000000000000004000000000python-zeroconf-0.132.2/src/zeroconf/_handlers/query_handler.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from typing import TYPE_CHECKING, List, Optional, Set, Tuple, Union, cast from .._cache import DNSCache, _UniqueRecordsType from .._dns import DNSAddress, DNSPointer, DNSQuestion, DNSRecord, DNSRRSet from .._protocol.incoming import DNSIncoming from .._services.info import ServiceInfo from .._transport import _WrappedTransport from .._utils.net import IPVersion from ..const import ( _ADDRESS_RECORD_TYPES, _CLASS_IN, _DNS_OTHER_TTL, _MDNS_PORT, _ONE_SECOND, _SERVICE_TYPE_ENUMERATION_NAME, _TYPE_A, _TYPE_AAAA, _TYPE_ANY, _TYPE_NSEC, _TYPE_PTR, _TYPE_SRV, _TYPE_TXT, ) from .answers import ( QuestionAnswers, _AnswerWithAdditionalsType, construct_outgoing_multicast_answers, construct_outgoing_unicast_answers, ) _RESPOND_IMMEDIATE_TYPES = {_TYPE_NSEC, _TYPE_SRV, *_ADDRESS_RECORD_TYPES} _EMPTY_SERVICES_LIST: List[ServiceInfo] = [] _EMPTY_TYPES_LIST: List[str] = [] _IPVersion_ALL = IPVersion.All _int = int _str = str _ANSWER_STRATEGY_SERVICE_TYPE_ENUMERATION = 0 _ANSWER_STRATEGY_POINTER = 1 _ANSWER_STRATEGY_ADDRESS = 2 _ANSWER_STRATEGY_SERVICE = 3 _ANSWER_STRATEGY_TEXT = 4 if TYPE_CHECKING: from .._core import Zeroconf class _AnswerStrategy: __slots__ = ("question", "strategy_type", "types", "services") def __init__( self, question: DNSQuestion, strategy_type: _int, types: List[str], services: List[ServiceInfo], ) -> None: """Create an answer strategy.""" self.question = question self.strategy_type = strategy_type self.types = types self.services = services class _QueryResponse: """A pair for unicast and multicast DNSOutgoing responses.""" __slots__ = ( "_is_probe", "_questions", "_now", "_cache", "_additionals", "_ucast", "_mcast_now", "_mcast_aggregate", "_mcast_aggregate_last_second", ) def __init__(self, cache: DNSCache, questions: List[DNSQuestion], is_probe: bool, now: float) -> None: """Build a query response.""" self._is_probe = is_probe self._questions = questions self._now = now self._cache = cache self._additionals: _AnswerWithAdditionalsType = {} self._ucast: Set[DNSRecord] = set() self._mcast_now: Set[DNSRecord] = set() self._mcast_aggregate: Set[DNSRecord] = set() self._mcast_aggregate_last_second: Set[DNSRecord] = set() def add_qu_question_response(self, answers: _AnswerWithAdditionalsType) -> None: """Generate a response to a multicast QU query.""" for record, additionals in answers.items(): self._additionals[record] = additionals if self._is_probe: self._ucast.add(record) if not self._has_mcast_within_one_quarter_ttl(record): self._mcast_now.add(record) elif not self._is_probe: self._ucast.add(record) def add_ucast_question_response(self, answers: _AnswerWithAdditionalsType) -> None: """Generate a response to a unicast query.""" self._additionals.update(answers) self._ucast.update(answers) def add_mcast_question_response(self, answers: _AnswerWithAdditionalsType) -> None: """Generate a response to a multicast query.""" self._additionals.update(answers) for answer in answers: if self._is_probe: self._mcast_now.add(answer) continue if self._has_mcast_record_in_last_second(answer): self._mcast_aggregate_last_second.add(answer) continue if len(self._questions) == 1: question = self._questions[0] if question.type in _RESPOND_IMMEDIATE_TYPES: self._mcast_now.add(answer) continue self._mcast_aggregate.add(answer) def answers( self, ) -> QuestionAnswers: """Return answer sets that will be queued.""" ucast = {r: self._additionals[r] for r in self._ucast} mcast_now = {r: self._additionals[r] for r in self._mcast_now} mcast_aggregate = {r: self._additionals[r] for r in self._mcast_aggregate} mcast_aggregate_last_second = {r: self._additionals[r] for r in self._mcast_aggregate_last_second} return QuestionAnswers(ucast, mcast_now, mcast_aggregate, mcast_aggregate_last_second) def _has_mcast_within_one_quarter_ttl(self, record: DNSRecord) -> bool: """Check to see if a record has been mcasted recently. https://datatracker.ietf.org/doc/html/rfc6762#section-5.4 When receiving a question with the unicast-response bit set, a responder SHOULD usually respond with a unicast packet directed back to the querier. However, if the responder has not multicast that record recently (within one quarter of its TTL), then the responder SHOULD instead multicast the response so as to keep all the peer caches up to date """ if TYPE_CHECKING: record = cast(_UniqueRecordsType, record) maybe_entry = self._cache.async_get_unique(record) return bool(maybe_entry is not None and maybe_entry.is_recent(self._now)) def _has_mcast_record_in_last_second(self, record: DNSRecord) -> bool: """Check if an answer was seen in the last second. Protect the network against excessive packet flooding https://datatracker.ietf.org/doc/html/rfc6762#section-14 """ if TYPE_CHECKING: record = cast(_UniqueRecordsType, record) maybe_entry = self._cache.async_get_unique(record) return bool(maybe_entry is not None and self._now - maybe_entry.created < _ONE_SECOND) class QueryHandler: """Query the ServiceRegistry.""" __slots__ = ("zc", "registry", "cache", "question_history", "out_queue", "out_delay_queue") def __init__(self, zc: 'Zeroconf') -> None: """Init the query handler.""" self.zc = zc self.registry = zc.registry self.cache = zc.cache self.question_history = zc.question_history self.out_queue = zc.out_queue self.out_delay_queue = zc.out_delay_queue def _add_service_type_enumeration_query_answers( self, types: List[str], answer_set: _AnswerWithAdditionalsType, known_answers: DNSRRSet ) -> None: """Provide an answer to a service type enumeration query. https://datatracker.ietf.org/doc/html/rfc6763#section-9 """ for stype in types: dns_pointer = DNSPointer( _SERVICE_TYPE_ENUMERATION_NAME, _TYPE_PTR, _CLASS_IN, _DNS_OTHER_TTL, stype, 0.0 ) if not known_answers.suppresses(dns_pointer): answer_set[dns_pointer] = set() def _add_pointer_answers( self, services: List[ServiceInfo], answer_set: _AnswerWithAdditionalsType, known_answers: DNSRRSet ) -> None: """Answer PTR/ANY question.""" for service in services: # Add recommended additional answers according to # https://tools.ietf.org/html/rfc6763#section-12.1. dns_pointer = service._dns_pointer(None) if known_answers.suppresses(dns_pointer): continue answer_set[dns_pointer] = { service._dns_service(None), service._dns_text(None), *service._get_address_and_nsec_records(None), } def _add_address_answers( self, services: List[ServiceInfo], answer_set: _AnswerWithAdditionalsType, known_answers: DNSRRSet, type_: _int, ) -> None: """Answer A/AAAA/ANY question.""" for service in services: answers: List[DNSAddress] = [] additionals: Set[DNSRecord] = set() seen_types: Set[int] = set() for dns_address in service._dns_addresses(None, _IPVersion_ALL): seen_types.add(dns_address.type) if dns_address.type != type_: additionals.add(dns_address) elif not known_answers.suppresses(dns_address): answers.append(dns_address) missing_types: Set[int] = _ADDRESS_RECORD_TYPES - seen_types if answers: if missing_types: assert service.server is not None, "Service server must be set for NSEC record." additionals.add(service._dns_nsec(list(missing_types), None)) for answer in answers: answer_set[answer] = additionals elif type_ in missing_types: assert service.server is not None, "Service server must be set for NSEC record." answer_set[service._dns_nsec(list(missing_types), None)] = set() def _answer_question( self, question: DNSQuestion, strategy_type: _int, types: List[str], services: List[ServiceInfo], known_answers: DNSRRSet, ) -> _AnswerWithAdditionalsType: """Answer a question.""" answer_set: _AnswerWithAdditionalsType = {} if strategy_type == _ANSWER_STRATEGY_SERVICE_TYPE_ENUMERATION: self._add_service_type_enumeration_query_answers(types, answer_set, known_answers) elif strategy_type == _ANSWER_STRATEGY_POINTER: self._add_pointer_answers(services, answer_set, known_answers) elif strategy_type == _ANSWER_STRATEGY_ADDRESS: self._add_address_answers(services, answer_set, known_answers, question.type) elif strategy_type == _ANSWER_STRATEGY_SERVICE: # Add recommended additional answers according to # https://tools.ietf.org/html/rfc6763#section-12.2. service = services[0] dns_service = service._dns_service(None) if not known_answers.suppresses(dns_service): answer_set[dns_service] = service._get_address_and_nsec_records(None) elif strategy_type == _ANSWER_STRATEGY_TEXT: # pragma: no branch service = services[0] dns_text = service._dns_text(None) if not known_answers.suppresses(dns_text): answer_set[dns_text] = set() return answer_set def async_response( # pylint: disable=unused-argument self, msgs: List[DNSIncoming], ucast_source: bool ) -> Optional[QuestionAnswers]: """Deal with incoming query packets. Provides a response if possible. This function must be run in the event loop as it is not threadsafe. """ strategies: List[_AnswerStrategy] = [] for msg in msgs: for question in msg._questions: strategies.extend(self._get_answer_strategies(question)) if not strategies: # We have no way to answer the question because we have # nothing in the ServiceRegistry that matches or we do not # understand the question. return None is_probe = False msg = msgs[0] questions = msg._questions # Only decode known answers if we are not a probe and we have # at least one answer strategy answers: List[DNSRecord] = [] for msg in msgs: if msg.is_probe(): is_probe = True else: answers.extend(msg.answers()) query_res = _QueryResponse(self.cache, questions, is_probe, msg.now) known_answers = DNSRRSet(answers) known_answers_set: Optional[Set[DNSRecord]] = None now = msg.now for strategy in strategies: question = strategy.question is_unicast = question.unique # unique and unicast are the same flag if not is_unicast: if known_answers_set is None: # pragma: no branch known_answers_set = known_answers.lookup_set() self.question_history.add_question_at_time(question, now, known_answers_set) answer_set = self._answer_question( question, strategy.strategy_type, strategy.types, strategy.services, known_answers ) if not ucast_source and is_unicast: query_res.add_qu_question_response(answer_set) continue if ucast_source: query_res.add_ucast_question_response(answer_set) # We always multicast as well even if its a unicast # source as long as we haven't done it recently (75% of ttl) query_res.add_mcast_question_response(answer_set) return query_res.answers() def _get_answer_strategies( self, question: DNSQuestion, ) -> List[_AnswerStrategy]: """Collect strategies to answer a question.""" name = question.name question_lower_name = name.lower() type_ = question.type strategies: List[_AnswerStrategy] = [] if type_ == _TYPE_PTR and question_lower_name == _SERVICE_TYPE_ENUMERATION_NAME: types = self.registry.async_get_types() if types: strategies.append( _AnswerStrategy( question, _ANSWER_STRATEGY_SERVICE_TYPE_ENUMERATION, types, _EMPTY_SERVICES_LIST ) ) return strategies if type_ in (_TYPE_PTR, _TYPE_ANY): services = self.registry.async_get_infos_type(question_lower_name) if services: strategies.append( _AnswerStrategy(question, _ANSWER_STRATEGY_POINTER, _EMPTY_TYPES_LIST, services) ) if type_ in (_TYPE_A, _TYPE_AAAA, _TYPE_ANY): services = self.registry.async_get_infos_server(question_lower_name) if services: strategies.append( _AnswerStrategy(question, _ANSWER_STRATEGY_ADDRESS, _EMPTY_TYPES_LIST, services) ) if type_ in (_TYPE_SRV, _TYPE_TXT, _TYPE_ANY): service = self.registry.async_get_info_name(question_lower_name) if service is not None: if type_ in (_TYPE_SRV, _TYPE_ANY): strategies.append( _AnswerStrategy(question, _ANSWER_STRATEGY_SERVICE, _EMPTY_TYPES_LIST, [service]) ) if type_ in (_TYPE_TXT, _TYPE_ANY): strategies.append( _AnswerStrategy(question, _ANSWER_STRATEGY_TEXT, _EMPTY_TYPES_LIST, [service]) ) return strategies def handle_assembled_query( self, packets: List[DNSIncoming], addr: _str, port: _int, transport: _WrappedTransport, v6_flow_scope: Union[Tuple[()], Tuple[int, int]], ) -> None: """Respond to a (re)assembled query. If the protocol recieved packets with the TC bit set, it will wait a bit for the rest of the packets and only call handle_assembled_query once it has a complete set of packets or the timer expires. If the TC bit is not set, a single packet will be in packets. """ first_packet = packets[0] ucast_source = port != _MDNS_PORT question_answers = self.async_response(packets, ucast_source) if question_answers is None: return if question_answers.ucast: questions = first_packet._questions id_ = first_packet.id out = construct_outgoing_unicast_answers(question_answers.ucast, ucast_source, questions, id_) # When sending unicast, only send back the reply # via the same socket that it was recieved from # as we know its reachable from that socket self.zc.async_send(out, addr, port, v6_flow_scope, transport) if question_answers.mcast_now: self.zc.async_send(construct_outgoing_multicast_answers(question_answers.mcast_now)) if question_answers.mcast_aggregate: self.out_queue.async_add(first_packet.now, question_answers.mcast_aggregate) if question_answers.mcast_aggregate_last_second: # https://datatracker.ietf.org/doc/html/rfc6762#section-14 # If we broadcast it in the last second, we have to delay # at least a second before we send it again self.out_delay_queue.async_add(first_packet.now, question_answers.mcast_aggregate_last_second) 07070100000035000081A40000000000000000000000016619D4CC00000496000000000000000000000000000000000000004200000000python-zeroconf-0.132.2/src/zeroconf/_handlers/record_manager.pxd import cython from .._cache cimport DNSCache from .._dns cimport DNSQuestion, DNSRecord from .._protocol.incoming cimport DNSIncoming from .._updates cimport RecordUpdateListener from .._utils.time cimport current_time_millis cdef cython.float _DNS_PTR_MIN_TTL cdef cython.uint _TYPE_PTR cdef object _ADDRESS_RECORD_TYPES cdef object RecordUpdate cdef bint TYPE_CHECKING cdef object _TYPE_PTR cdef class RecordManager: cdef public object zc cdef public DNSCache cache cdef public cython.set listeners cpdef void async_updates(self, object now, object records) cpdef void async_updates_complete(self, bint notify) @cython.locals( cache=DNSCache, record=DNSRecord, answers=cython.list, maybe_entry=DNSRecord, ) cpdef void async_updates_from_response(self, DNSIncoming msg) cpdef void async_add_listener(self, RecordUpdateListener listener, object question) cpdef void async_remove_listener(self, RecordUpdateListener listener) @cython.locals(question=DNSQuestion, record=DNSRecord) cdef void _async_update_matching_records(self, RecordUpdateListener listener, cython.list questions) 07070100000036000081A40000000000000000000000016619D4CC0000217A000000000000000000000000000000000000004100000000python-zeroconf-0.132.2/src/zeroconf/_handlers/record_manager.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from typing import TYPE_CHECKING, List, Optional, Set, Tuple, Union, cast from .._cache import _UniqueRecordsType from .._dns import DNSQuestion, DNSRecord from .._logger import log from .._protocol.incoming import DNSIncoming from .._record_update import RecordUpdate from .._updates import RecordUpdateListener from .._utils.time import current_time_millis from ..const import _ADDRESS_RECORD_TYPES, _DNS_PTR_MIN_TTL, _TYPE_PTR if TYPE_CHECKING: from .._core import Zeroconf _float = float class RecordManager: """Process records into the cache and notify listeners.""" __slots__ = ("zc", "cache", "listeners") def __init__(self, zeroconf: 'Zeroconf') -> None: """Init the record manager.""" self.zc = zeroconf self.cache = zeroconf.cache self.listeners: Set[RecordUpdateListener] = set() def async_updates(self, now: _float, records: List[RecordUpdate]) -> None: """Used to notify listeners of new information that has updated a record. This method must be called before the cache is updated. This method will be run in the event loop. """ for listener in self.listeners.copy(): listener.async_update_records(self.zc, now, records) def async_updates_complete(self, notify: bool) -> None: """Used to notify listeners of new information that has updated a record. This method must be called after the cache is updated. This method will be run in the event loop. """ for listener in self.listeners.copy(): listener.async_update_records_complete() if notify: self.zc.async_notify_all() def async_updates_from_response(self, msg: DNSIncoming) -> None: """Deal with incoming response packets. All answers are held in the cache, and listeners are notified. This function must be run in the event loop as it is not threadsafe. """ updates: List[RecordUpdate] = [] address_adds: List[DNSRecord] = [] other_adds: List[DNSRecord] = [] removes: Set[DNSRecord] = set() now = msg.now unique_types: Set[Tuple[str, int, int]] = set() cache = self.cache answers = msg.answers() for record in answers: # Protect zeroconf from records that can cause denial of service. # # We enforce a minimum TTL for PTR records to avoid # ServiceBrowsers generating excessive queries refresh queries. # Apple uses a 15s minimum TTL, however we do not have the same # level of rate limit and safe guards so we use 1/4 of the recommended value. record_type = record.type record_ttl = record.ttl if record_ttl and record_type == _TYPE_PTR and record_ttl < _DNS_PTR_MIN_TTL: log.debug( "Increasing effective ttl of %s to minimum of %s to protect against excessive refreshes.", record, _DNS_PTR_MIN_TTL, ) record.set_created_ttl(record.created, _DNS_PTR_MIN_TTL) if record.unique: # https://tools.ietf.org/html/rfc6762#section-10.2 unique_types.add((record.name, record_type, record.class_)) if TYPE_CHECKING: record = cast(_UniqueRecordsType, record) maybe_entry = cache.async_get_unique(record) if not record.is_expired(now): if maybe_entry is not None: maybe_entry.reset_ttl(record) else: if record_type in _ADDRESS_RECORD_TYPES: address_adds.append(record) else: other_adds.append(record) updates.append(RecordUpdate(record, maybe_entry)) # This is likely a goodbye since the record is # expired and exists in the cache elif maybe_entry is not None: updates.append(RecordUpdate(record, maybe_entry)) removes.add(record) if unique_types: cache.async_mark_unique_records_older_than_1s_to_expire(unique_types, answers, now) if updates: self.async_updates(now, updates) # The cache adds must be processed AFTER we trigger # the updates since we compare existing data # with the new data and updating the cache # ahead of update_record will cause listeners # to miss changes # # We must process address adds before non-addresses # otherwise a fetch of ServiceInfo may miss an address # because it thinks the cache is complete # # The cache is processed under the context manager to ensure # that any ServiceBrowser that is going to call # zc.get_service_info will see the cached value # but ONLY after all the record updates have been # processsed. new = False if other_adds or address_adds: new = cache.async_add_records(address_adds) if cache.async_add_records(other_adds): new = True # Removes are processed last since # ServiceInfo could generate an un-needed query # because the data was not yet populated. if removes: cache.async_remove_records(removes) if updates: self.async_updates_complete(new) def async_add_listener( self, listener: RecordUpdateListener, question: Optional[Union[DNSQuestion, List[DNSQuestion]]] ) -> None: """Adds a listener for a given question. The listener will have its update_record method called when information is available to answer the question(s). This function is not thread-safe and must be called in the eventloop. """ if not isinstance(listener, RecordUpdateListener): log.error( # type: ignore[unreachable] "listeners passed to async_add_listener must inherit from RecordUpdateListener;" " In the future this will fail" ) self.listeners.add(listener) if question is None: return questions = [question] if isinstance(question, DNSQuestion) else question self._async_update_matching_records(listener, questions) def _async_update_matching_records( self, listener: RecordUpdateListener, questions: List[DNSQuestion] ) -> None: """Calls back any existing entries in the cache that answer the question. This function must be run from the event loop. """ now = current_time_millis() records: List[RecordUpdate] = [ RecordUpdate(record, None) for question in questions for record in self.cache.async_entries_with_name(question.name) if not record.is_expired(now) and question.answered_by(record) ] if not records: return listener.async_update_records(self.zc, now, records) listener.async_update_records_complete() self.zc.async_notify_all() def async_remove_listener(self, listener: RecordUpdateListener) -> None: """Removes a listener. This function is not threadsafe and must be called in the eventloop. """ try: self.listeners.remove(listener) self.zc.async_notify_all() except ValueError as e: log.exception('Failed to remove listener: %r', e) 07070100000037000081A40000000000000000000000016619D4CC00000232000000000000000000000000000000000000003200000000python-zeroconf-0.132.2/src/zeroconf/_history.pxdimport cython from ._dns cimport DNSQuestion cdef cython.double _DUPLICATE_QUESTION_INTERVAL cdef class QuestionHistory: cdef cython.dict _history cpdef void add_question_at_time(self, DNSQuestion question, double now, cython.set known_answers) @cython.locals(than=double, previous_question=cython.tuple, previous_known_answers=cython.set) cpdef bint suppresses(self, DNSQuestion question, double now, cython.set known_answers) @cython.locals(than=double, now_known_answers=cython.tuple) cpdef void async_expire(self, double now) 07070100000038000081A40000000000000000000000016619D4CC00000C69000000000000000000000000000000000000003100000000python-zeroconf-0.132.2/src/zeroconf/_history.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from typing import Dict, List, Set, Tuple from ._dns import DNSQuestion, DNSRecord from .const import _DUPLICATE_QUESTION_INTERVAL # The QuestionHistory is used to implement Duplicate Question Suppression # https://datatracker.ietf.org/doc/html/rfc6762#section-7.3 _float = float class QuestionHistory: """Remember questions and known answers.""" def __init__(self) -> None: """Init a new QuestionHistory.""" self._history: Dict[DNSQuestion, Tuple[float, Set[DNSRecord]]] = {} def add_question_at_time(self, question: DNSQuestion, now: _float, known_answers: Set[DNSRecord]) -> None: """Remember a question with known answers.""" self._history[question] = (now, known_answers) def suppresses(self, question: DNSQuestion, now: _float, known_answers: Set[DNSRecord]) -> bool: """Check to see if a question should be suppressed. https://datatracker.ietf.org/doc/html/rfc6762#section-7.3 When multiple queriers on the network are querying for the same resource records, there is no need for them to all be repeatedly asking the same question. """ previous_question = self._history.get(question) # There was not previous question in the history if not previous_question: return False than, previous_known_answers = previous_question # The last question was older than 999ms if now - than > _DUPLICATE_QUESTION_INTERVAL: return False # The last question has more known answers than # we knew so we have to ask if previous_known_answers - known_answers: return False return True def async_expire(self, now: _float) -> None: """Expire the history of old questions.""" removes: List[DNSQuestion] = [] for question, now_known_answers in self._history.items(): than, _ = now_known_answers if now - than > _DUPLICATE_QUESTION_INTERVAL: removes.append(question) for question in removes: del self._history[question] def clear(self) -> None: """Clear the history.""" self._history.clear() 07070100000039000081A40000000000000000000000016619D4CC0000063A000000000000000000000000000000000000003300000000python-zeroconf-0.132.2/src/zeroconf/_listener.pxd import cython from ._handlers.query_handler cimport QueryHandler from ._handlers.record_manager cimport RecordManager from ._protocol.incoming cimport DNSIncoming from ._services.registry cimport ServiceRegistry from ._utils.time cimport current_time_millis, millis_to_seconds cdef object log cdef object DEBUG_ENABLED cdef bint TYPE_CHECKING cdef cython.uint _MAX_MSG_ABSOLUTE cdef cython.uint _DUPLICATE_PACKET_SUPPRESSION_INTERVAL cdef class AsyncListener: cdef public object zc cdef ServiceRegistry _registry cdef RecordManager _record_manager cdef QueryHandler _query_handler cdef public cython.bytes data cdef public double last_time cdef public DNSIncoming last_message cdef public object transport cdef public object sock_description cdef public cython.dict _deferred cdef public cython.dict _timers @cython.locals(now=double, debug=cython.bint) cpdef datagram_received(self, cython.bytes bytes, cython.tuple addrs) @cython.locals(msg=DNSIncoming) cpdef _process_datagram_at_time(self, bint debug, cython.uint data_len, double now, bytes data, cython.tuple addrs) cdef _cancel_any_timers_for_addr(self, object addr) @cython.locals(incoming=DNSIncoming, deferred=list) cpdef handle_query_or_defer( self, DNSIncoming msg, object addr, object port, object transport, tuple v6_flow_scope ) cpdef _respond_query( self, object msg, object addr, object port, object transport, tuple v6_flow_scope ) 0707010000003A000081A40000000000000000000000016619D4CC000022F3000000000000000000000000000000000000003200000000python-zeroconf-0.132.2/src/zeroconf/_listener.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import logging import random from functools import partial from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union, cast from ._logger import QuietLogger, log from ._protocol.incoming import DNSIncoming from ._transport import _WrappedTransport, make_wrapped_transport from ._utils.time import current_time_millis, millis_to_seconds from .const import _DUPLICATE_PACKET_SUPPRESSION_INTERVAL, _MAX_MSG_ABSOLUTE if TYPE_CHECKING: from ._core import Zeroconf _TC_DELAY_RANDOM_INTERVAL = (400, 500) _bytes = bytes _str = str _int = int _float = float DEBUG_ENABLED = partial(log.isEnabledFor, logging.DEBUG) class AsyncListener: """A Listener is used by this module to listen on the multicast group to which DNS messages are sent, allowing the implementation to cache information as it arrives. It requires registration with an Engine object in order to have the read() method called when a socket is available for reading.""" __slots__ = ( 'zc', '_registry', '_record_manager', "_query_handler", 'data', 'last_time', 'last_message', 'transport', 'sock_description', '_deferred', '_timers', ) def __init__(self, zc: 'Zeroconf') -> None: self.zc = zc self._registry = zc.registry self._record_manager = zc.record_manager self._query_handler = zc.query_handler self.data: Optional[bytes] = None self.last_time: float = 0 self.last_message: Optional[DNSIncoming] = None self.transport: Optional[_WrappedTransport] = None self.sock_description: Optional[str] = None self._deferred: Dict[str, List[DNSIncoming]] = {} self._timers: Dict[str, asyncio.TimerHandle] = {} super().__init__() def datagram_received( self, data: _bytes, addrs: Union[Tuple[str, int], Tuple[str, int, int, int]] ) -> None: data_len = len(data) debug = DEBUG_ENABLED() if data_len > _MAX_MSG_ABSOLUTE: # Guard against oversized packets to ensure bad implementations cannot overwhelm # the system. if debug: log.debug( "Discarding incoming packet with length %s, which is larger " "than the absolute maximum size of %s", data_len, _MAX_MSG_ABSOLUTE, ) return now = current_time_millis() self._process_datagram_at_time(debug, data_len, now, data, addrs) def _process_datagram_at_time( self, debug: bool, data_len: _int, now: _float, data: _bytes, addrs: Union[Tuple[str, int], Tuple[str, int, int, int]], ) -> None: if ( self.data == data and (now - _DUPLICATE_PACKET_SUPPRESSION_INTERVAL) < self.last_time and self.last_message is not None and not self.last_message.has_qu_question() ): # Guard against duplicate packets if debug: log.debug( 'Ignoring duplicate message with no unicast questions received from %s [socket %s] (%d bytes) as [%r]', addrs, self.sock_description, data_len, data, ) return if len(addrs) == 2: v6_flow_scope: Union[Tuple[()], Tuple[int, int]] = () # https://github.com/python/mypy/issues/1178 addr, port = addrs # type: ignore addr_port = addrs if TYPE_CHECKING: addr_port = cast(Tuple[str, int], addr_port) scope = None else: # https://github.com/python/mypy/issues/1178 addr, port, flow, scope = addrs # type: ignore if debug: # pragma: no branch log.debug('IPv6 scope_id %d associated to the receiving interface', scope) v6_flow_scope = (flow, scope) addr_port = (addr, port) msg = DNSIncoming(data, addr_port, scope, now) self.data = data self.last_time = now self.last_message = msg if msg.valid is True: if debug: log.debug( 'Received from %r:%r [socket %s]: %r (%d bytes) as [%r]', addr, port, self.sock_description, msg, data_len, data, ) else: if debug: log.debug( 'Received from %r:%r [socket %s]: (%d bytes) [%r]', addr, port, self.sock_description, data_len, data, ) return if not msg.is_query(): self._record_manager.async_updates_from_response(msg) return if not self._registry.has_entries: # If the registry is empty, we have no answers to give. return if TYPE_CHECKING: assert self.transport is not None self.handle_query_or_defer(msg, addr, port, self.transport, v6_flow_scope) def handle_query_or_defer( self, msg: DNSIncoming, addr: _str, port: _int, transport: _WrappedTransport, v6_flow_scope: Union[Tuple[()], Tuple[int, int]], ) -> None: """Deal with incoming query packets. Provides a response if possible.""" if not msg.truncated: self._respond_query(msg, addr, port, transport, v6_flow_scope) return deferred = self._deferred.setdefault(addr, []) # If we get the same packet we ignore it for incoming in reversed(deferred): if incoming.data == msg.data: return deferred.append(msg) delay = millis_to_seconds(random.randint(*_TC_DELAY_RANDOM_INTERVAL)) loop = self.zc.loop assert loop is not None self._cancel_any_timers_for_addr(addr) self._timers[addr] = loop.call_at( loop.time() + delay, self._respond_query, None, addr, port, transport, v6_flow_scope ) def _cancel_any_timers_for_addr(self, addr: _str) -> None: """Cancel any future truncated packet timers for the address.""" if addr in self._timers: self._timers.pop(addr).cancel() def _respond_query( self, msg: Optional[DNSIncoming], addr: _str, port: _int, transport: _WrappedTransport, v6_flow_scope: Union[Tuple[()], Tuple[int, int]], ) -> None: """Respond to a query and reassemble any truncated deferred packets.""" self._cancel_any_timers_for_addr(addr) packets = self._deferred.pop(addr, []) if msg: packets.append(msg) self._query_handler.handle_assembled_query(packets, addr, port, transport, v6_flow_scope) def error_received(self, exc: Exception) -> None: """Likely socket closed or IPv6.""" # We preformat the message string with the socket as we want # log_exception_once to log a warrning message once PER EACH # different socket in case there are problems with multiple # sockets msg_str = f"Error with socket {self.sock_description}): %s" QuietLogger.log_exception_once(exc, msg_str, exc) def connection_made(self, transport: asyncio.BaseTransport) -> None: wrapped_transport = make_wrapped_transport(cast(asyncio.DatagramTransport, transport)) self.transport = wrapped_transport self.sock_description = f"{wrapped_transport.fileno} ({wrapped_transport.sock_name})" def connection_lost(self, exc: Optional[Exception]) -> None: """Handle connection lost.""" 0707010000003B000081A40000000000000000000000016619D4CC00000BA4000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/src/zeroconf/_logger.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine ) Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import logging import sys from typing import Any, Dict, Union, cast log = logging.getLogger(__name__.split('.', maxsplit=1)[0]) log.addHandler(logging.NullHandler()) def set_logger_level_if_unset() -> None: if log.level == logging.NOTSET: log.setLevel(logging.WARN) set_logger_level_if_unset() class QuietLogger: _seen_logs: Dict[str, Union[int, tuple]] = {} @classmethod def log_exception_warning(cls, *logger_data: Any) -> None: exc_info = sys.exc_info() exc_str = str(exc_info[1]) if exc_str not in cls._seen_logs: # log at warning level the first time this is seen cls._seen_logs[exc_str] = exc_info logger = log.warning else: logger = log.debug logger(*(logger_data or ['Exception occurred']), exc_info=True) @classmethod def log_exception_debug(cls, *logger_data: Any) -> None: log_exc_info = False exc_info = sys.exc_info() exc_str = str(exc_info[1]) if exc_str not in cls._seen_logs: # log the trace only on the first time cls._seen_logs[exc_str] = exc_info log_exc_info = True log.debug(*(logger_data or ['Exception occurred']), exc_info=log_exc_info) @classmethod def log_warning_once(cls, *args: Any) -> None: msg_str = args[0] if msg_str not in cls._seen_logs: cls._seen_logs[msg_str] = 0 logger = log.warning else: logger = log.debug cls._seen_logs[msg_str] = cast(int, cls._seen_logs[msg_str]) + 1 logger(*args) @classmethod def log_exception_once(cls, exc: Exception, *args: Any) -> None: msg_str = args[0] if msg_str not in cls._seen_logs: cls._seen_logs[msg_str] = 0 logger = log.warning else: logger = log.debug cls._seen_logs[msg_str] = cast(int, cls._seen_logs[msg_str]) + 1 logger(*args, exc_info=exc) 0707010000003C000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002F00000000python-zeroconf-0.132.2/src/zeroconf/_protocol0707010000003D000081A40000000000000000000000016619D4CC000003CB000000000000000000000000000000000000003B00000000python-zeroconf-0.132.2/src/zeroconf/_protocol/__init__.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ 0707010000003E000081A40000000000000000000000016619D4CC00000C2E000000000000000000000000000000000000003C00000000python-zeroconf-0.132.2/src/zeroconf/_protocol/incoming.pxd import cython cdef cython.uint DNS_COMPRESSION_HEADER_LEN cdef cython.uint MAX_DNS_LABELS cdef cython.uint DNS_COMPRESSION_POINTER_LEN cdef cython.uint MAX_NAME_LENGTH cdef cython.uint _TYPE_A cdef cython.uint _TYPE_CNAME cdef cython.uint _TYPE_PTR cdef cython.uint _TYPE_TXT cdef cython.uint _TYPE_SRV cdef cython.uint _TYPE_HINFO cdef cython.uint _TYPE_AAAA cdef cython.uint _TYPE_NSEC cdef cython.uint _FLAGS_QR_MASK cdef cython.uint _FLAGS_QR_MASK cdef cython.uint _FLAGS_TC cdef cython.uint _FLAGS_QR_QUERY cdef cython.uint _FLAGS_QR_RESPONSE cdef object DECODE_EXCEPTIONS cdef object IncomingDecodeError from .._dns cimport ( DNSAddress, DNSEntry, DNSHinfo, DNSNsec, DNSPointer, DNSQuestion, DNSRecord, DNSService, DNSText, ) from .._utils.time cimport current_time_millis cdef class DNSIncoming: cdef bint _did_read_others cdef public unsigned int flags cdef cython.uint offset cdef public bytes data cdef const unsigned char [:] view cdef unsigned int _data_len cdef cython.dict _name_cache cdef cython.list _questions cdef cython.list _answers cdef public cython.uint id cdef cython.uint _num_questions cdef cython.uint _num_answers cdef cython.uint _num_authorities cdef cython.uint _num_additionals cdef public bint valid cdef public double now cdef public object scope_id cdef public object source cdef bint _has_qu_question @cython.locals( question=DNSQuestion ) cpdef bint has_qu_question(self) cpdef bint is_query(self) cpdef bint is_probe(self) cpdef list answers(self) cpdef bint is_response(self) @cython.locals( off="unsigned int", label_idx="unsigned int", length="unsigned int", link="unsigned int", link_data="unsigned int", link_py_int=object, linked_labels=cython.list ) cdef unsigned int _decode_labels_at_offset(self, unsigned int off, cython.list labels, cython.set seen_pointers) @cython.locals(offset="unsigned int") cdef void _read_header(self) cdef void _initial_parse(self) @cython.locals( end="unsigned int", length="unsigned int", offset="unsigned int" ) cdef void _read_others(self) @cython.locals(offset="unsigned int") cdef _read_questions(self) @cython.locals( length="unsigned int", ) cdef str _read_character_string(self) cdef bytes _read_string(self, unsigned int length) @cython.locals( name_start="unsigned int", offset="unsigned int" ) cdef _read_record(self, object domain, unsigned int type_, unsigned int class_, unsigned int ttl, unsigned int length) @cython.locals( offset="unsigned int", offset_plus_one="unsigned int", offset_plus_two="unsigned int", window="unsigned int", bit="unsigned int", byte="unsigned int", i="unsigned int", bitmap_length="unsigned int", ) cdef list _read_bitmap(self, unsigned int end) cdef str _read_name(self) 0707010000003F000081A40000000000000000000000016619D4CC00003E6C000000000000000000000000000000000000003B00000000python-zeroconf-0.132.2/src/zeroconf/_protocol/incoming.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import struct import sys from typing import Any, Dict, List, Optional, Set, Tuple, Union from .._dns import ( DNSAddress, DNSHinfo, DNSNsec, DNSPointer, DNSQuestion, DNSRecord, DNSService, DNSText, ) from .._exceptions import IncomingDecodeError from .._logger import log from .._utils.time import current_time_millis from ..const import ( _FLAGS_QR_MASK, _FLAGS_QR_QUERY, _FLAGS_QR_RESPONSE, _FLAGS_TC, _TYPE_A, _TYPE_AAAA, _TYPE_CNAME, _TYPE_HINFO, _TYPE_NSEC, _TYPE_PTR, _TYPE_SRV, _TYPE_TXT, _TYPES, ) DNS_COMPRESSION_HEADER_LEN = 1 DNS_COMPRESSION_POINTER_LEN = 2 MAX_DNS_LABELS = 128 MAX_NAME_LENGTH = 253 DECODE_EXCEPTIONS = (IndexError, struct.error, IncomingDecodeError) _seen_logs: Dict[str, Union[int, tuple]] = {} _str = str _int = int class DNSIncoming: """Object representation of an incoming DNS packet""" __slots__ = ( "_did_read_others", 'flags', 'offset', 'data', 'view', '_data_len', '_name_cache', '_questions', '_answers', 'id', '_num_questions', '_num_answers', '_num_authorities', '_num_additionals', 'valid', 'now', 'scope_id', 'source', '_has_qu_question', ) def __init__( self, data: bytes, source: Optional[Tuple[str, int]] = None, scope_id: Optional[int] = None, now: Optional[float] = None, ) -> None: """Constructor from string holding bytes of packet""" self.flags = 0 self.offset = 0 self.data = data self.view = data self._data_len = len(data) self._name_cache: Dict[int, List[str]] = {} self._questions: List[DNSQuestion] = [] self._answers: List[DNSRecord] = [] self.id = 0 self._num_questions = 0 self._num_answers = 0 self._num_authorities = 0 self._num_additionals = 0 self.valid = False self._did_read_others = False self.now = now or current_time_millis() self.source = source self.scope_id = scope_id self._has_qu_question = False try: self._initial_parse() except DECODE_EXCEPTIONS: self._log_exception_debug( 'Received invalid packet from %s at offset %d while unpacking %r', self.source, self.offset, self.data, ) def is_query(self) -> bool: """Returns true if this is a query.""" return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY def is_response(self) -> bool: """Returns true if this is a response.""" return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE def has_qu_question(self) -> bool: """Returns true if any question is a QU question.""" return self._has_qu_question @property def truncated(self) -> bool: """Returns true if this is a truncated.""" return (self.flags & _FLAGS_TC) == _FLAGS_TC @property def questions(self) -> List[DNSQuestion]: """Questions in the packet.""" return self._questions @property def num_questions(self) -> int: """Number of questions in the packet.""" return self._num_questions @property def num_answers(self) -> int: """Number of answers in the packet.""" return self._num_answers @property def num_authorities(self) -> int: """Number of authorities in the packet.""" return self._num_authorities @property def num_additionals(self) -> int: """Number of additionals in the packet.""" return self._num_additionals def _initial_parse(self) -> None: """Parse the data needed to initalize the packet object.""" self._read_header() self._read_questions() if not self._num_questions: self._read_others() self.valid = True @classmethod def _log_exception_debug(cls, *logger_data: Any) -> None: log_exc_info = False exc_info = sys.exc_info() exc_str = str(exc_info[1]) if exc_str not in _seen_logs: # log the trace only on the first time _seen_logs[exc_str] = exc_info log_exc_info = True log.debug(*(logger_data or ['Exception occurred']), exc_info=log_exc_info) def answers(self) -> List[DNSRecord]: """Answers in the packet.""" if not self._did_read_others: try: self._read_others() except DECODE_EXCEPTIONS: self._log_exception_debug( 'Received invalid packet from %s at offset %d while unpacking %r', self.source, self.offset, self.data, ) return self._answers def is_probe(self) -> bool: """Returns true if this is a probe.""" return self._num_authorities > 0 def __repr__(self) -> str: return '<DNSIncoming:{%s}>' % ', '.join( [ 'id=%s' % self.id, 'flags=%s' % self.flags, 'truncated=%s' % self.truncated, 'n_q=%s' % self._num_questions, 'n_ans=%s' % self._num_answers, 'n_auth=%s' % self._num_authorities, 'n_add=%s' % self._num_additionals, 'questions=%s' % self._questions, 'answers=%s' % self.answers(), ] ) def _read_header(self) -> None: """Reads header portion of packet""" view = self.view offset = self.offset self.offset += 12 # The header has 6 unsigned shorts in network order self.id = view[offset] << 8 | view[offset + 1] self.flags = view[offset + 2] << 8 | view[offset + 3] self._num_questions = view[offset + 4] << 8 | view[offset + 5] self._num_answers = view[offset + 6] << 8 | view[offset + 7] self._num_authorities = view[offset + 8] << 8 | view[offset + 9] self._num_additionals = view[offset + 10] << 8 | view[offset + 11] def _read_questions(self) -> None: """Reads questions section of packet""" view = self.view questions = self._questions for _ in range(self._num_questions): name = self._read_name() offset = self.offset self.offset += 4 # The question has 2 unsigned shorts in network order type_ = view[offset] << 8 | view[offset + 1] class_ = view[offset + 2] << 8 | view[offset + 3] question = DNSQuestion(name, type_, class_) if question.unique: # QU questions use the same bit as unique self._has_qu_question = True questions.append(question) def _read_character_string(self) -> str: """Reads a character string from the packet""" length = self.view[self.offset] self.offset += 1 info = self.data[self.offset : self.offset + length].decode('utf-8', 'replace') self.offset += length return info def _read_string(self, length: _int) -> bytes: """Reads a string of a given length from the packet""" info = self.data[self.offset : self.offset + length] self.offset += length return info def _read_others(self) -> None: """Reads the answers, authorities and additionals section of the packet""" self._did_read_others = True view = self.view n = self._num_answers + self._num_authorities + self._num_additionals for _ in range(n): domain = self._read_name() offset = self.offset self.offset += 10 # type_, class_ and length are unsigned shorts in network order # ttl is an unsigned long in network order https://www.rfc-editor.org/errata/eid2130 type_ = view[offset] << 8 | view[offset + 1] class_ = view[offset + 2] << 8 | view[offset + 3] ttl = view[offset + 4] << 24 | view[offset + 5] << 16 | view[offset + 6] << 8 | view[offset + 7] length = view[offset + 8] << 8 | view[offset + 9] end = self.offset + length rec = None try: rec = self._read_record(domain, type_, class_, ttl, length) except DECODE_EXCEPTIONS: # Skip records that fail to decode if we know the length # If the packet is really corrupt read_name and the unpack # above would fail and hit the exception catch in read_others self.offset = end log.debug( 'Unable to parse; skipping record for %s with type %s at offset %d while unpacking %r', domain, _TYPES.get(type_, type_), self.offset, self.data, exc_info=True, ) if rec is not None: self._answers.append(rec) def _read_record( self, domain: _str, type_: _int, class_: _int, ttl: _int, length: _int ) -> Optional[DNSRecord]: """Read known records types and skip unknown ones.""" if type_ == _TYPE_A: return DNSAddress(domain, type_, class_, ttl, self._read_string(4), None, self.now) if type_ in (_TYPE_CNAME, _TYPE_PTR): return DNSPointer(domain, type_, class_, ttl, self._read_name(), self.now) if type_ == _TYPE_TXT: return DNSText(domain, type_, class_, ttl, self._read_string(length), self.now) if type_ == _TYPE_SRV: view = self.view offset = self.offset self.offset += 6 # The SRV record has 3 unsigned shorts in network order priority = view[offset] << 8 | view[offset + 1] weight = view[offset + 2] << 8 | view[offset + 3] port = view[offset + 4] << 8 | view[offset + 5] return DNSService( domain, type_, class_, ttl, priority, weight, port, self._read_name(), self.now, ) if type_ == _TYPE_HINFO: return DNSHinfo( domain, type_, class_, ttl, self._read_character_string(), self._read_character_string(), self.now, ) if type_ == _TYPE_AAAA: return DNSAddress(domain, type_, class_, ttl, self._read_string(16), self.scope_id, self.now) if type_ == _TYPE_NSEC: name_start = self.offset return DNSNsec( domain, type_, class_, ttl, self._read_name(), self._read_bitmap(name_start + length), self.now, ) # Try to ignore types we don't know about # Skip the payload for the resource record so the next # records can be parsed correctly self.offset += length return None def _read_bitmap(self, end: _int) -> List[int]: """Reads an NSEC bitmap from the packet.""" rdtypes = [] view = self.view while self.offset < end: offset = self.offset offset_plus_one = offset + 1 offset_plus_two = offset + 2 window = view[offset] bitmap_length = view[offset_plus_one] bitmap_end = offset_plus_two + bitmap_length for i, byte in enumerate(self.data[offset_plus_two:bitmap_end]): for bit in range(0, 8): if byte & (0x80 >> bit): rdtypes.append(bit + window * 256 + i * 8) self.offset += 2 + bitmap_length return rdtypes def _read_name(self) -> str: """Reads a domain name from the packet.""" labels: List[str] = [] seen_pointers: Set[int] = set() original_offset = self.offset self.offset = self._decode_labels_at_offset(original_offset, labels, seen_pointers) self._name_cache[original_offset] = labels name = ".".join(labels) + "." if len(name) > MAX_NAME_LENGTH: raise IncomingDecodeError( f"DNS name {name} exceeds maximum length of {MAX_NAME_LENGTH} from {self.source}" ) return name def _decode_labels_at_offset(self, off: _int, labels: List[str], seen_pointers: Set[int]) -> int: # This is a tight loop that is called frequently, small optimizations can make a difference. view = self.view while off < self._data_len: length = view[off] if length == 0: return off + DNS_COMPRESSION_HEADER_LEN if length < 0x40: label_idx = off + DNS_COMPRESSION_HEADER_LEN labels.append(self.data[label_idx : label_idx + length].decode('utf-8', 'replace')) off += DNS_COMPRESSION_HEADER_LEN + length continue if length < 0xC0: raise IncomingDecodeError( f"DNS compression type {length} is unknown at {off} from {self.source}" ) # We have a DNS compression pointer link_data = view[off + 1] link = (length & 0x3F) * 256 + link_data link_py_int = link if link > self._data_len: raise IncomingDecodeError( f"DNS compression pointer at {off} points to {link} beyond packet from {self.source}" ) if link == off: raise IncomingDecodeError( f"DNS compression pointer at {off} points to itself from {self.source}" ) if link_py_int in seen_pointers: raise IncomingDecodeError( f"DNS compression pointer at {off} was seen again from {self.source}" ) linked_labels = self._name_cache.get(link_py_int) if not linked_labels: linked_labels = [] seen_pointers.add(link_py_int) self._decode_labels_at_offset(link, linked_labels, seen_pointers) self._name_cache[link_py_int] = linked_labels labels.extend(linked_labels) if len(labels) > MAX_DNS_LABELS: raise IncomingDecodeError( f"Maximum dns labels reached while processing pointer at {off} from {self.source}" ) return off + DNS_COMPRESSION_POINTER_LEN raise IncomingDecodeError(f"Corrupt packet received while decoding name from {self.source}") 07070100000040000081A40000000000000000000000016619D4CC0000100E000000000000000000000000000000000000003C00000000python-zeroconf-0.132.2/src/zeroconf/_protocol/outgoing.pxd import cython from .._dns cimport DNSEntry, DNSPointer, DNSQuestion, DNSRecord from .incoming cimport DNSIncoming cdef cython.uint _CLASS_UNIQUE cdef cython.uint _DNS_PACKET_HEADER_LEN cdef cython.uint _FLAGS_QR_MASK cdef cython.uint _FLAGS_QR_QUERY cdef cython.uint _FLAGS_QR_RESPONSE cdef cython.uint _FLAGS_TC cdef cython.uint _MAX_MSG_ABSOLUTE cdef cython.uint _MAX_MSG_TYPICAL cdef bint TYPE_CHECKING cdef unsigned int SHORT_CACHE_MAX cdef object PACK_BYTE cdef object PACK_SHORT cdef object PACK_LONG cdef unsigned int STATE_INIT cdef unsigned int STATE_FINISHED cdef object LOGGING_IS_ENABLED_FOR cdef object LOGGING_DEBUG cdef cython.tuple BYTE_TABLE cdef cython.tuple SHORT_LOOKUP cdef cython.dict LONG_LOOKUP cdef class DNSOutgoing: cdef public unsigned int flags cdef public bint finished cdef public object id cdef public bint multicast cdef public cython.list packets_data cdef public cython.dict names cdef public cython.list data cdef public unsigned int size cdef public bint allow_long cdef public unsigned int state cdef public cython.list questions cdef public cython.list answers cdef public cython.list authorities cdef public cython.list additionals cpdef void _reset_for_next_packet(self) cdef void _write_byte(self, cython.uint value) cdef void _insert_short_at_start(self, unsigned int value) cdef void _replace_short(self, cython.uint index, cython.uint value) cdef _get_short(self, cython.uint value) cdef void _write_int(self, object value) cdef cython.bint _write_question(self, DNSQuestion question) @cython.locals( d=cython.bytes, data_view=cython.list, index=cython.uint, length=cython.uint ) cdef cython.bint _write_record(self, DNSRecord record, double now) @cython.locals(class_=cython.uint) cdef void _write_record_class(self, DNSEntry record) @cython.locals( start_size_int=object ) cdef cython.bint _check_data_limit_or_rollback(self, cython.uint start_data_length, cython.uint start_size) @cython.locals(questions_written=cython.uint) cdef cython.uint _write_questions_from_offset(self, unsigned int questions_offset) @cython.locals(answers_written=cython.uint) cdef cython.uint _write_answers_from_offset(self, unsigned int answer_offset) @cython.locals(records_written=cython.uint) cdef cython.uint _write_records_from_offset(self, cython.list records, unsigned int offset) cdef bint _has_more_to_add(self, unsigned int questions_offset, unsigned int answer_offset, unsigned int authority_offset, unsigned int additional_offset) cdef void _write_ttl(self, DNSRecord record, double now) @cython.locals( labels=cython.list, label=cython.str, index=cython.uint, start_size=cython.uint, name_length=cython.uint, ) cpdef void write_name(self, cython.str name) cdef void _write_link_to_name(self, unsigned int index) cpdef void write_short(self, cython.uint value) cpdef void write_string(self, cython.bytes value) @cython.locals(utfstr=bytes) cdef void _write_utf(self, cython.str value) @cython.locals( debug_enable=bint, made_progress=bint, has_more_to_add=bint, questions_offset="unsigned int", answer_offset="unsigned int", authority_offset="unsigned int", additional_offset="unsigned int", questions_written="unsigned int", answers_written="unsigned int", authorities_written="unsigned int", additionals_written="unsigned int", ) cpdef packets(self) cpdef void add_question(self, DNSQuestion question) cpdef void add_answer(self, DNSIncoming inp, DNSRecord record) @cython.locals(now_double=double) cpdef void add_answer_at_time(self, DNSRecord record, double now) cpdef void add_authorative_answer(self, DNSPointer record) cpdef void add_additional_answer(self, DNSRecord record) cpdef bint is_query(self) cpdef bint is_response(self) 07070100000041000081A40000000000000000000000016619D4CC000047F8000000000000000000000000000000000000003B00000000python-zeroconf-0.132.2/src/zeroconf/_protocol/outgoing.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import enum import logging from struct import Struct from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union from .._dns import DNSPointer, DNSQuestion, DNSRecord from .._exceptions import NamePartTooLongException from .._logger import log from ..const import ( _CLASS_UNIQUE, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DNS_PACKET_HEADER_LEN, _FLAGS_QR_MASK, _FLAGS_QR_QUERY, _FLAGS_QR_RESPONSE, _FLAGS_TC, _MAX_MSG_ABSOLUTE, _MAX_MSG_TYPICAL, ) from .incoming import DNSIncoming str_ = str float_ = float int_ = int bytes_ = bytes DNSQuestion_ = DNSQuestion DNSRecord_ = DNSRecord PACK_BYTE = Struct('>B').pack PACK_SHORT = Struct('>H').pack PACK_LONG = Struct('>L').pack SHORT_CACHE_MAX = 128 BYTE_TABLE = tuple(PACK_BYTE(i) for i in range(256)) SHORT_LOOKUP = tuple(PACK_SHORT(i) for i in range(SHORT_CACHE_MAX)) LONG_LOOKUP = {i: PACK_LONG(i) for i in (_DNS_OTHER_TTL, _DNS_HOST_TTL, 0)} class State(enum.Enum): init = 0 finished = 1 STATE_INIT = State.init.value STATE_FINISHED = State.finished.value LOGGING_IS_ENABLED_FOR = log.isEnabledFor LOGGING_DEBUG = logging.DEBUG class DNSOutgoing: """Object representation of an outgoing packet""" __slots__ = ( 'flags', 'finished', 'id', 'multicast', 'packets_data', 'names', 'data', 'size', 'allow_long', 'state', 'questions', 'answers', 'authorities', 'additionals', ) def __init__(self, flags: int, multicast: bool = True, id_: int = 0) -> None: self.flags = flags self.finished = False self.id = id_ self.multicast = multicast self.packets_data: List[bytes] = [] # these 3 are per-packet -- see also _reset_for_next_packet() self.names: Dict[str, int] = {} self.data: List[bytes] = [] self.size: int = _DNS_PACKET_HEADER_LEN self.allow_long: bool = True self.state = STATE_INIT self.questions: List[DNSQuestion] = [] self.answers: List[Tuple[DNSRecord, float]] = [] self.authorities: List[DNSPointer] = [] self.additionals: List[DNSRecord] = [] def is_query(self) -> bool: """Returns true if this is a query.""" return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY def is_response(self) -> bool: """Returns true if this is a response.""" return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE def _reset_for_next_packet(self) -> None: self.names = {} self.data = [] self.size = _DNS_PACKET_HEADER_LEN self.allow_long = True def __repr__(self) -> str: return '<DNSOutgoing:{%s}>' % ', '.join( [ 'multicast=%s' % self.multicast, 'flags=%s' % self.flags, 'questions=%s' % self.questions, 'answers=%s' % self.answers, 'authorities=%s' % self.authorities, 'additionals=%s' % self.additionals, ] ) def add_question(self, record: DNSQuestion) -> None: """Adds a question""" self.questions.append(record) def add_answer(self, inp: DNSIncoming, record: DNSRecord) -> None: """Adds an answer""" if not record.suppressed_by(inp): self.add_answer_at_time(record, 0.0) def add_answer_at_time(self, record: Optional[DNSRecord], now: float_) -> None: """Adds an answer if it does not expire by a certain time""" now_double = now if record is not None and (now_double == 0 or not record.is_expired(now_double)): self.answers.append((record, now)) def add_authorative_answer(self, record: DNSPointer) -> None: """Adds an authoritative answer""" self.authorities.append(record) def add_additional_answer(self, record: DNSRecord) -> None: """Adds an additional answer From: RFC 6763, DNS-Based Service Discovery, February 2013 12. DNS Additional Record Generation DNS has an efficiency feature whereby a DNS server may place additional records in the additional section of the DNS message. These additional records are records that the client did not explicitly request, but the server has reasonable grounds to expect that the client might request them shortly, so including them can save the client from having to issue additional queries. This section recommends which additional records SHOULD be generated to improve network efficiency, for both Unicast and Multicast DNS-SD responses. 12.1. PTR Records When including a DNS-SD Service Instance Enumeration or Selective Instance Enumeration (subtype) PTR record in a response packet, the server/responder SHOULD include the following additional records: o The SRV record(s) named in the PTR rdata. o The TXT record(s) named in the PTR rdata. o All address records (type "A" and "AAAA") named in the SRV rdata. 12.2. SRV Records When including an SRV record in a response packet, the server/responder SHOULD include the following additional records: o All address records (type "A" and "AAAA") named in the SRV rdata. """ self.additionals.append(record) def _write_byte(self, value: int_) -> None: """Writes a single byte to the packet""" self.data.append(BYTE_TABLE[value]) self.size += 1 def _get_short(self, value: int_) -> bytes: """Convert an unsigned short to 2 bytes.""" return SHORT_LOOKUP[value] if value < SHORT_CACHE_MAX else PACK_SHORT(value) def _insert_short_at_start(self, value: int_) -> None: """Inserts an unsigned short at the start of the packet""" self.data.insert(0, self._get_short(value)) def _replace_short(self, index: int_, value: int_) -> None: """Replaces an unsigned short in a certain position in the packet""" self.data[index] = self._get_short(value) def write_short(self, value: int_) -> None: """Writes an unsigned short to the packet""" self.data.append(self._get_short(value)) self.size += 2 def _write_int(self, value: Union[float, int]) -> None: """Writes an unsigned integer to the packet""" value_as_int = int(value) long_bytes = LONG_LOOKUP.get(value_as_int) if long_bytes is not None: self.data.append(long_bytes) else: self.data.append(PACK_LONG(value_as_int)) self.size += 4 def write_string(self, value: bytes_) -> None: """Writes a string to the packet""" if TYPE_CHECKING: assert isinstance(value, bytes) self.data.append(value) self.size += len(value) def _write_utf(self, s: str_) -> None: """Writes a UTF-8 string of a given length to the packet""" utfstr = s.encode('utf-8') length = len(utfstr) if length > 64: raise NamePartTooLongException self._write_byte(length) self.write_string(utfstr) def write_character_string(self, value: bytes) -> None: if TYPE_CHECKING: assert isinstance(value, bytes) length = len(value) if length > 256: raise NamePartTooLongException self._write_byte(length) self.write_string(value) def write_name(self, name: str_) -> None: """ Write names to packet 18.14. Name Compression When generating Multicast DNS messages, implementations SHOULD use name compression wherever possible to compress the names of resource records, by replacing some or all of the resource record name with a compact two-byte reference to an appearance of that data somewhere earlier in the message [RFC1035]. """ # split name into each label if name.endswith('.'): name = name[:-1] index = self.names.get(name, 0) if index: self._write_link_to_name(index) return start_size = self.size labels = name.split('.') # Write each new label or a pointer to the existing one in the packet self.names[name] = start_size self._write_utf(labels[0]) name_length = 0 for count in range(1, len(labels)): partial_name = '.'.join(labels[count:]) index = self.names.get(partial_name, 0) if index: self._write_link_to_name(index) return if name_length == 0: name_length = len(name.encode('utf-8')) self.names[partial_name] = start_size + name_length - len(partial_name.encode('utf-8')) self._write_utf(labels[count]) # this is the end of a name self._write_byte(0) def _write_link_to_name(self, index: int_) -> None: # If part of the name already exists in the packet, # create a pointer to it self._write_byte((index >> 8) | 0xC0) self._write_byte(index & 0xFF) def _write_question(self, question: DNSQuestion_) -> bool: """Writes a question to the packet""" start_data_length = len(self.data) start_size = self.size self.write_name(question.name) self.write_short(question.type) self._write_record_class(question) return self._check_data_limit_or_rollback(start_data_length, start_size) def _write_record_class(self, record: Union[DNSQuestion_, DNSRecord_]) -> None: """Write out the record class including the unique/unicast (QU) bit.""" class_ = record.class_ if record.unique is True and self.multicast: self.write_short(class_ | _CLASS_UNIQUE) else: self.write_short(class_) def _write_ttl(self, record: DNSRecord_, now: float_) -> None: """Write out the record ttl.""" self._write_int(record.ttl if now == 0 else record.get_remaining_ttl(now)) def _write_record(self, record: DNSRecord_, now: float_) -> bool: """Writes a record (answer, authoritative answer, additional) to the packet. Returns True on success, or False if we did not because the packet because the record does not fit.""" start_data_length = len(self.data) start_size = self.size self.write_name(record.name) self.write_short(record.type) self._write_record_class(record) self._write_ttl(record, now) index = len(self.data) self.write_short(0) # Will get replaced with the actual size record.write(self) # Adjust size for the short we will write before this record length = 0 for d in self.data[index + 1 :]: length += len(d) # Here we replace the 0 length short we wrote # before with the actual length self._replace_short(index, length) return self._check_data_limit_or_rollback(start_data_length, start_size) def _check_data_limit_or_rollback(self, start_data_length: int_, start_size: int_) -> bool: """Check data limit, if we go over, then rollback and return False.""" len_limit = _MAX_MSG_ABSOLUTE if self.allow_long else _MAX_MSG_TYPICAL self.allow_long = False if self.size <= len_limit: return True if LOGGING_IS_ENABLED_FOR(LOGGING_DEBUG): # pragma: no branch log.debug("Reached data limit (size=%d) > (limit=%d) - rolling back", self.size, len_limit) del self.data[start_data_length:] self.size = start_size start_size_int = start_size rollback_names = [name for name, idx in self.names.items() if idx >= start_size_int] for name in rollback_names: del self.names[name] return False def _write_questions_from_offset(self, questions_offset: int_) -> int: questions_written = 0 for question in self.questions[questions_offset:]: if not self._write_question(question): break questions_written += 1 return questions_written def _write_answers_from_offset(self, answer_offset: int_) -> int: answers_written = 0 for answer, time_ in self.answers[answer_offset:]: if not self._write_record(answer, time_): break answers_written += 1 return answers_written def _write_records_from_offset(self, records: Sequence[DNSRecord], offset: int_) -> int: records_written = 0 for record in records[offset:]: if not self._write_record(record, 0): break records_written += 1 return records_written def _has_more_to_add( self, questions_offset: int_, answer_offset: int_, authority_offset: int_, additional_offset: int_ ) -> bool: """Check if all questions, answers, authority, and additionals have been written to the packet.""" return ( questions_offset < len(self.questions) or answer_offset < len(self.answers) or authority_offset < len(self.authorities) or additional_offset < len(self.additionals) ) def packets(self) -> List[bytes]: """Returns a list of bytestrings containing the packets' bytes No further parts should be added to the packet once this is done. The packets are each restricted to _MAX_MSG_TYPICAL or less in length, except for the case of a single answer which will be written out to a single oversized packet no more than _MAX_MSG_ABSOLUTE in length (and hence will be subject to IP fragmentation potentially).""" packets_data = self.packets_data if self.state == STATE_FINISHED: return packets_data questions_offset = 0 answer_offset = 0 authority_offset = 0 additional_offset = 0 # we have to at least write out the question debug_enable = LOGGING_IS_ENABLED_FOR(LOGGING_DEBUG) is True has_more_to_add = True while has_more_to_add: if debug_enable: log.debug( "offsets = questions=%d, answers=%d, authorities=%d, additionals=%d", questions_offset, answer_offset, authority_offset, additional_offset, ) log.debug( "lengths = questions=%d, answers=%d, authorities=%d, additionals=%d", len(self.questions), len(self.answers), len(self.authorities), len(self.additionals), ) questions_written = self._write_questions_from_offset(questions_offset) answers_written = self._write_answers_from_offset(answer_offset) authorities_written = self._write_records_from_offset(self.authorities, authority_offset) additionals_written = self._write_records_from_offset(self.additionals, additional_offset) made_progress = bool(self.data) self._insert_short_at_start(additionals_written) self._insert_short_at_start(authorities_written) self._insert_short_at_start(answers_written) self._insert_short_at_start(questions_written) questions_offset += questions_written answer_offset += answers_written authority_offset += authorities_written additional_offset += additionals_written if debug_enable: log.debug( "now offsets = questions=%d, answers=%d, authorities=%d, additionals=%d", questions_offset, answer_offset, authority_offset, additional_offset, ) has_more_to_add = self._has_more_to_add( questions_offset, answer_offset, authority_offset, additional_offset ) if has_more_to_add and self.is_query(): # https://datatracker.ietf.org/doc/html/rfc6762#section-7.2 if debug_enable: # pragma: no branch log.debug("Setting TC flag") self._insert_short_at_start(self.flags | _FLAGS_TC) else: self._insert_short_at_start(self.flags) if self.multicast: self._insert_short_at_start(0) else: self._insert_short_at_start(self.id) packets_data.append(b''.join(self.data)) if not made_progress: # Generating an empty packet is not a desirable outcome, but currently # too many internals rely on this behavior. So, we'll just return an # empty packet and log a warning until this can be refactored at a later # date. log.warning("packets() made no progress adding records; returning") break if has_more_to_add: self._reset_for_next_packet() self.state = STATE_FINISHED return packets_data 07070100000042000081A40000000000000000000000016619D4CC00000085000000000000000000000000000000000000003800000000python-zeroconf-0.132.2/src/zeroconf/_record_update.pxd import cython from ._dns cimport DNSRecord cdef class RecordUpdate: cdef public DNSRecord new cdef public DNSRecord old 07070100000043000081A40000000000000000000000016619D4CC000005E2000000000000000000000000000000000000003700000000python-zeroconf-0.132.2/src/zeroconf/_record_update.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from typing import Optional from ._dns import DNSRecord class RecordUpdate: __slots__ = ("new", "old") def __init__(self, new: DNSRecord, old: Optional[DNSRecord] = None): """RecordUpdate represents a change in a DNS record.""" self.new = new self.old = old def __getitem__(self, index: int) -> Optional[DNSRecord]: """Get the new or old record.""" if index == 0: return self.new elif index == 1: return self.old raise IndexError(index) 07070100000044000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002F00000000python-zeroconf-0.132.2/src/zeroconf/_services07070100000045000081A40000000000000000000000016619D4CC0000007F000000000000000000000000000000000000003C00000000python-zeroconf-0.132.2/src/zeroconf/_services/__init__.pxd import cython cdef class Signal: cdef list _handlers cdef class SignalRegistrationInterface: cdef list _handlers 07070100000046000081A40000000000000000000000016619D4CC00000973000000000000000000000000000000000000003B00000000python-zeroconf-0.132.2/src/zeroconf/_services/__init__.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import enum from typing import TYPE_CHECKING, Any, Callable, List if TYPE_CHECKING: from .._core import Zeroconf @enum.unique class ServiceStateChange(enum.Enum): Added = 1 Removed = 2 Updated = 3 class ServiceListener: def add_service(self, zc: 'Zeroconf', type_: str, name: str) -> None: raise NotImplementedError() def remove_service(self, zc: 'Zeroconf', type_: str, name: str) -> None: raise NotImplementedError() def update_service(self, zc: 'Zeroconf', type_: str, name: str) -> None: raise NotImplementedError() class Signal: __slots__ = ('_handlers',) def __init__(self) -> None: self._handlers: List[Callable[..., None]] = [] def fire(self, **kwargs: Any) -> None: for h in self._handlers[:]: h(**kwargs) @property def registration_interface(self) -> 'SignalRegistrationInterface': return SignalRegistrationInterface(self._handlers) class SignalRegistrationInterface: __slots__ = ('_handlers',) def __init__(self, handlers: List[Callable[..., None]]) -> None: self._handlers = handlers def register_handler(self, handler: Callable[..., None]) -> 'SignalRegistrationInterface': self._handlers.append(handler) return self def unregister_handler(self, handler: Callable[..., None]) -> 'SignalRegistrationInterface': self._handlers.remove(handler) return self 07070100000047000081A40000000000000000000000016619D4CC00001033000000000000000000000000000000000000003B00000000python-zeroconf-0.132.2/src/zeroconf/_services/browser.pxd import cython from .._cache cimport DNSCache from .._history cimport QuestionHistory from .._protocol.outgoing cimport DNSOutgoing, DNSPointer, DNSQuestion, DNSRecord from .._record_update cimport RecordUpdate from .._updates cimport RecordUpdateListener from .._utils.time cimport current_time_millis, millis_to_seconds from . cimport Signal, SignalRegistrationInterface cdef bint TYPE_CHECKING cdef object cached_possible_types cdef cython.uint _EXPIRE_REFRESH_TIME_PERCENT, _MAX_MSG_TYPICAL, _DNS_PACKET_HEADER_LEN cdef cython.uint _TYPE_PTR cdef object _CLASS_IN cdef object SERVICE_STATE_CHANGE_ADDED, SERVICE_STATE_CHANGE_REMOVED, SERVICE_STATE_CHANGE_UPDATED cdef cython.set _ADDRESS_RECORD_TYPES cdef float RESCUE_RECORD_RETRY_TTL_PERCENTAGE cdef object _MDNS_PORT, _BROWSER_TIME cdef object QU_QUESTION cdef object _FLAGS_QR_QUERY cdef object heappop, heappush cdef class _ScheduledPTRQuery: cdef public str alias cdef public str name cdef public unsigned int ttl cdef public bint cancelled cdef public double expire_time_millis cdef public double when_millis cdef class _DNSPointerOutgoingBucket: cdef public double now_millis cdef public DNSOutgoing out cdef public cython.uint bytes cpdef add(self, cython.uint max_compressed_size, DNSQuestion question, cython.set answers) @cython.locals(cache=DNSCache, question_history=QuestionHistory, record=DNSRecord, qu_question=bint) cpdef list generate_service_query( object zc, double now_millis, set types_, bint multicast, object question_type ) @cython.locals(answer=DNSPointer, query_buckets=list, question=DNSQuestion, max_compressed_size=cython.uint, max_bucket_size=cython.uint, query_bucket=_DNSPointerOutgoingBucket) cdef list _group_ptr_queries_with_known_answers(double now_millis, bint multicast, cython.dict question_with_known_answers) cdef class QueryScheduler: cdef object _zc cdef set _types cdef str _addr cdef int _port cdef bint _multicast cdef tuple _first_random_delay_interval cdef double _min_time_between_queries_millis cdef object _loop cdef unsigned int _startup_queries_sent cdef public dict _next_scheduled_for_alias cdef public list _query_heap cdef object _next_run cdef double _clock_resolution_millis cdef object _question_type cdef void _schedule_ptr_refresh(self, DNSPointer pointer, double expire_time_millis, double refresh_time_millis) cdef void _schedule_ptr_query(self, _ScheduledPTRQuery scheduled_query) @cython.locals(scheduled=_ScheduledPTRQuery) cpdef void cancel_ptr_refresh(self, DNSPointer pointer) @cython.locals(current=_ScheduledPTRQuery, expire_time=double) cpdef void reschedule_ptr_first_refresh(self, DNSPointer pointer) @cython.locals(ttl_millis='unsigned int', additional_wait=double, next_query_time=double) cpdef void schedule_rescue_query(self, _ScheduledPTRQuery query, double now_millis, float additional_percentage) cpdef void _process_startup_queries(self) @cython.locals(query=_ScheduledPTRQuery, next_scheduled=_ScheduledPTRQuery, next_when=double) cpdef void _process_ready_types(self) cpdef void async_send_ready_queries(self, bint first_request, double now_millis, set ready_types) cdef class _ServiceBrowserBase(RecordUpdateListener): cdef public cython.set types cdef public object zc cdef DNSCache _cache cdef object _loop cdef public cython.dict _pending_handlers cdef public object _service_state_changed cdef public QueryScheduler query_scheduler cdef public bint done cdef public object _query_sender_task cpdef void _enqueue_callback(self, object state_change, object type_, object name) @cython.locals(record_update=RecordUpdate, record=DNSRecord, cache=DNSCache, service=DNSRecord, pointer=DNSPointer) cpdef void async_update_records(self, object zc, double now, cython.list records) cpdef cython.list _names_matching_types(self, object types) cpdef _fire_service_state_changed_event(self, cython.tuple event) cpdef void async_update_records_complete(self) 07070100000048000081A40000000000000000000000016619D4CC00007BF8000000000000000000000000000000000000003A00000000python-zeroconf-0.132.2/src/zeroconf/_services/browser.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import heapq import queue import random import threading import time import warnings from functools import partial from types import TracebackType # noqa # used in type hints from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, Union, cast, ) from .._dns import DNSPointer, DNSQuestion, DNSQuestionType from .._logger import log from .._protocol.outgoing import DNSOutgoing from .._record_update import RecordUpdate from .._services import ( ServiceListener, ServiceStateChange, Signal, SignalRegistrationInterface, ) from .._updates import RecordUpdateListener from .._utils.name import cached_possible_types, service_type_name from .._utils.time import current_time_millis, millis_to_seconds from ..const import ( _ADDRESS_RECORD_TYPES, _BROWSER_TIME, _CLASS_IN, _DNS_PACKET_HEADER_LEN, _EXPIRE_REFRESH_TIME_PERCENT, _FLAGS_QR_QUERY, _MAX_MSG_TYPICAL, _MDNS_ADDR, _MDNS_ADDR6, _MDNS_PORT, _TYPE_PTR, ) # https://datatracker.ietf.org/doc/html/rfc6762#section-5.2 _FIRST_QUERY_DELAY_RANDOM_INTERVAL = (20, 120) # ms _ON_CHANGE_DISPATCH = { ServiceStateChange.Added: "add_service", ServiceStateChange.Removed: "remove_service", ServiceStateChange.Updated: "update_service", } SERVICE_STATE_CHANGE_ADDED = ServiceStateChange.Added SERVICE_STATE_CHANGE_REMOVED = ServiceStateChange.Removed SERVICE_STATE_CHANGE_UPDATED = ServiceStateChange.Updated QU_QUESTION = DNSQuestionType.QU STARTUP_QUERIES = 4 RESCUE_RECORD_RETRY_TTL_PERCENTAGE = 0.1 if TYPE_CHECKING: from .._core import Zeroconf float_ = float int_ = int bool_ = bool str_ = str _QuestionWithKnownAnswers = Dict[DNSQuestion, Set[DNSPointer]] heappop = heapq.heappop heappush = heapq.heappush class _ScheduledPTRQuery: __slots__ = ('alias', 'name', 'ttl', 'cancelled', 'expire_time_millis', 'when_millis') def __init__( self, alias: str, name: str, ttl: int, expire_time_millis: float, when_millis: float ) -> None: """Create a scheduled query.""" self.alias = alias self.name = name self.ttl = ttl # Since queries are stored in a heap we need to track if they are cancelled # so we can remove them from the heap when they are cancelled as it would # be too expensive to search the heap for the record to remove and instead # we just mark it as cancelled and ignore it when we pop it off the heap # when the query is due. self.cancelled = False # Expire time millis is the actual millisecond time the record will expire self.expire_time_millis = expire_time_millis # When millis is the millisecond time the query should be sent # For the first query this is the refresh time which is 75% of the TTL # # For subsequent queries we increase the time by 10% of the TTL # until we reach the expire time and then we stop because it means # we failed to rescue the record. self.when_millis = when_millis def __repr__(self) -> str: """Return a string representation of the scheduled query.""" return ( f"<{self.__class__.__name__} " f"alias={self.alias} " f"name={self.name} " f"ttl={self.ttl} " f"cancelled={self.cancelled} " f"expire_time_millis={self.expire_time_millis} " f"when_millis={self.when_millis}" ">" ) def __lt__(self, other: '_ScheduledPTRQuery') -> bool: """Compare two scheduled queries.""" if type(other) is _ScheduledPTRQuery: return self.when_millis < other.when_millis return NotImplemented def __le__(self, other: '_ScheduledPTRQuery') -> bool: """Compare two scheduled queries.""" if type(other) is _ScheduledPTRQuery: return self.when_millis < other.when_millis or self.__eq__(other) return NotImplemented def __eq__(self, other: Any) -> bool: """Compare two scheduled queries.""" if type(other) is _ScheduledPTRQuery: return self.when_millis == other.when_millis return NotImplemented def __ge__(self, other: '_ScheduledPTRQuery') -> bool: """Compare two scheduled queries.""" if type(other) is _ScheduledPTRQuery: return self.when_millis > other.when_millis or self.__eq__(other) return NotImplemented def __gt__(self, other: '_ScheduledPTRQuery') -> bool: """Compare two scheduled queries.""" if type(other) is _ScheduledPTRQuery: return self.when_millis > other.when_millis return NotImplemented class _DNSPointerOutgoingBucket: """A DNSOutgoing bucket.""" __slots__ = ('now_millis', 'out', 'bytes') def __init__(self, now_millis: float, multicast: bool) -> None: """Create a bucket to wrap a DNSOutgoing.""" self.now_millis = now_millis self.out = DNSOutgoing(_FLAGS_QR_QUERY, multicast) self.bytes = 0 def add(self, max_compressed_size: int_, question: DNSQuestion, answers: Set[DNSPointer]) -> None: """Add a new set of questions and known answers to the outgoing.""" self.out.add_question(question) for answer in answers: self.out.add_answer_at_time(answer, self.now_millis) self.bytes += max_compressed_size def group_ptr_queries_with_known_answers( now: float_, multicast: bool_, question_with_known_answers: _QuestionWithKnownAnswers ) -> List[DNSOutgoing]: """Aggregate queries so that as many known answers as possible fit in the same packet without having known answers spill over into the next packet unless the question and known answers are always going to exceed the packet size. Some responders do not implement multi-packet known answer suppression so we try to keep all the known answers in the same packet as the questions. """ return _group_ptr_queries_with_known_answers(now, multicast, question_with_known_answers) def _group_ptr_queries_with_known_answers( now_millis: float_, multicast: bool_, question_with_known_answers: _QuestionWithKnownAnswers ) -> List[DNSOutgoing]: """Inner wrapper for group_ptr_queries_with_known_answers.""" # This is the maximum size the query + known answers can be with name compression. # The actual size of the query + known answers may be a bit smaller since other # parts may be shared when the final DNSOutgoing packets are constructed. The # goal of this algorithm is to quickly bucket the query + known answers without # the overhead of actually constructing the packets. query_by_size: Dict[DNSQuestion, int] = { question: (question.max_size + sum(answer.max_size_compressed for answer in known_answers)) for question, known_answers in question_with_known_answers.items() } max_bucket_size = _MAX_MSG_TYPICAL - _DNS_PACKET_HEADER_LEN query_buckets: List[_DNSPointerOutgoingBucket] = [] for question in sorted( query_by_size, key=query_by_size.get, # type: ignore reverse=True, ): max_compressed_size = query_by_size[question] answers = question_with_known_answers[question] for query_bucket in query_buckets: if query_bucket.bytes + max_compressed_size <= max_bucket_size: query_bucket.add(max_compressed_size, question, answers) break else: # If a single question and known answers won't fit in a packet # we will end up generating multiple packets, but there will never # be multiple questions query_bucket = _DNSPointerOutgoingBucket(now_millis, multicast) query_bucket.add(max_compressed_size, question, answers) query_buckets.append(query_bucket) return [query_bucket.out for query_bucket in query_buckets] def generate_service_query( zc: 'Zeroconf', now_millis: float_, types_: Set[str], multicast: bool, question_type: Optional[DNSQuestionType], ) -> List[DNSOutgoing]: """Generate a service query for sending with zeroconf.send.""" questions_with_known_answers: _QuestionWithKnownAnswers = {} qu_question = not multicast if question_type is None else question_type is QU_QUESTION question_history = zc.question_history cache = zc.cache for type_ in types_: question = DNSQuestion(type_, _TYPE_PTR, _CLASS_IN) question.unicast = qu_question known_answers = { record for record in cache.get_all_by_details(type_, _TYPE_PTR, _CLASS_IN) if not record.is_stale(now_millis) } if not qu_question and question_history.suppresses(question, now_millis, known_answers): log.debug("Asking %s was suppressed by the question history", question) continue if TYPE_CHECKING: pointer_known_answers = cast(Set[DNSPointer], known_answers) else: pointer_known_answers = known_answers questions_with_known_answers[question] = pointer_known_answers if not qu_question: question_history.add_question_at_time(question, now_millis, known_answers) return _group_ptr_queries_with_known_answers(now_millis, multicast, questions_with_known_answers) def _on_change_dispatcher( listener: ServiceListener, zeroconf: 'Zeroconf', service_type: str, name: str, state_change: ServiceStateChange, ) -> None: """Dispatch a service state change to a listener.""" getattr(listener, _ON_CHANGE_DISPATCH[state_change])(zeroconf, service_type, name) def _service_state_changed_from_listener(listener: ServiceListener) -> Callable[..., None]: """Generate a service_state_changed handlers from a listener.""" assert listener is not None if not hasattr(listener, 'update_service'): warnings.warn( "%r has no update_service method. Provide one (it can be empty if you " "don't care about the updates), it'll become mandatory." % (listener,), FutureWarning, ) return partial(_on_change_dispatcher, listener) class QueryScheduler: """Schedule outgoing PTR queries for Continuous Multicast DNS Querying https://datatracker.ietf.org/doc/html/rfc6762#section-5.2 """ __slots__ = ( '_zc', '_types', '_addr', '_port', '_multicast', '_first_random_delay_interval', '_min_time_between_queries_millis', '_loop', '_startup_queries_sent', '_next_scheduled_for_alias', '_query_heap', '_next_run', '_clock_resolution_millis', '_question_type', ) def __init__( self, zc: "Zeroconf", types: Set[str], addr: Optional[str], port: int, multicast: bool, delay: int, first_random_delay_interval: Tuple[int, int], question_type: Optional[DNSQuestionType], ) -> None: self._zc = zc self._types = types self._addr = addr self._port = port self._multicast = multicast self._first_random_delay_interval = first_random_delay_interval self._min_time_between_queries_millis = delay self._loop: Optional[asyncio.AbstractEventLoop] = None self._startup_queries_sent = 0 self._next_scheduled_for_alias: Dict[str, _ScheduledPTRQuery] = {} self._query_heap: list[_ScheduledPTRQuery] = [] self._next_run: Optional[asyncio.TimerHandle] = None self._clock_resolution_millis = time.get_clock_info('monotonic').resolution * 1000 self._question_type = question_type def start(self, loop: asyncio.AbstractEventLoop) -> None: """Start the scheduler. https://datatracker.ietf.org/doc/html/rfc6762#section-5.2 To avoid accidental synchronization when, for some reason, multiple clients begin querying at exactly the same moment (e.g., because of some common external trigger event), a Multicast DNS querier SHOULD also delay the first query of the series by a randomly chosen amount in the range 20-120 ms. """ start_delay = millis_to_seconds(random.randint(*self._first_random_delay_interval)) self._loop = loop self._next_run = loop.call_later(start_delay, self._process_startup_queries) def stop(self) -> None: """Stop the scheduler.""" if self._next_run is not None: self._next_run.cancel() self._next_run = None self._next_scheduled_for_alias.clear() self._query_heap.clear() def _schedule_ptr_refresh( self, pointer: DNSPointer, expire_time_millis: float_, refresh_time_millis: float_ ) -> None: """Schedule a query for a pointer.""" ttl = int(pointer.ttl) if isinstance(pointer.ttl, float) else pointer.ttl scheduled_ptr_query = _ScheduledPTRQuery( pointer.alias, pointer.name, ttl, expire_time_millis, refresh_time_millis ) self._schedule_ptr_query(scheduled_ptr_query) def _schedule_ptr_query(self, scheduled_query: _ScheduledPTRQuery) -> None: """Schedule a query for a pointer.""" self._next_scheduled_for_alias[scheduled_query.alias] = scheduled_query heappush(self._query_heap, scheduled_query) def cancel_ptr_refresh(self, pointer: DNSPointer) -> None: """Cancel a query for a pointer.""" scheduled = self._next_scheduled_for_alias.pop(pointer.alias, None) if scheduled: scheduled.cancelled = True def reschedule_ptr_first_refresh(self, pointer: DNSPointer) -> None: """Reschedule a query for a pointer.""" current = self._next_scheduled_for_alias.get(pointer.alias) refresh_time_millis = pointer.get_expiration_time(_EXPIRE_REFRESH_TIME_PERCENT) if current is not None: # If the expire time is within self._min_time_between_queries_millis # of the current scheduled time avoid churn by not rescheduling if ( -self._min_time_between_queries_millis <= refresh_time_millis - current.when_millis <= self._min_time_between_queries_millis ): return current.cancelled = True del self._next_scheduled_for_alias[pointer.alias] expire_time_millis = pointer.get_expiration_time(100) self._schedule_ptr_refresh(pointer, expire_time_millis, refresh_time_millis) def schedule_rescue_query( self, query: _ScheduledPTRQuery, now_millis: float_, additional_percentage: float_ ) -> None: """Reschedule a query for a pointer at an additional percentage of expiration.""" ttl_millis = query.ttl * 1000 additional_wait = ttl_millis * additional_percentage next_query_time = now_millis + additional_wait if next_query_time >= query.expire_time_millis: # If we would schedule past the expire time # there is no point in scheduling as we already # tried to rescue the record and failed return scheduled_ptr_query = _ScheduledPTRQuery( query.alias, query.name, query.ttl, query.expire_time_millis, next_query_time ) self._schedule_ptr_query(scheduled_ptr_query) def _process_startup_queries(self) -> None: if TYPE_CHECKING: assert self._loop is not None # This is a safety to ensure we stop sending queries if Zeroconf instance # is stopped without the browser being cancelled if self._zc.done: return now_millis = current_time_millis() # At first we will send STARTUP_QUERIES queries to get the cache populated self.async_send_ready_queries(self._startup_queries_sent == 0, now_millis, self._types) self._startup_queries_sent += 1 # Once we finish sending the initial queries we will # switch to a strategy of sending queries only when we # need to refresh records that are about to expire if self._startup_queries_sent >= STARTUP_QUERIES: self._next_run = self._loop.call_at( millis_to_seconds(now_millis + self._min_time_between_queries_millis), self._process_ready_types, ) return self._next_run = self._loop.call_later(self._startup_queries_sent**2, self._process_startup_queries) def _process_ready_types(self) -> None: """Generate a list of ready types that is due and schedule the next time.""" if TYPE_CHECKING: assert self._loop is not None # This is a safety to ensure we stop sending queries if Zeroconf instance # is stopped without the browser being cancelled if self._zc.done: return now_millis = current_time_millis() # Refresh records that are about to expire (aka # _EXPIRE_REFRESH_TIME_PERCENT which is currently 75% of the TTL) and # additional rescue queries if the 75% query failed to refresh the record # with a minimum time between queries of _min_time_between_queries # which defaults to 10s ready_types: Set[str] = set() next_scheduled: Optional[_ScheduledPTRQuery] = None end_time_millis = now_millis + self._clock_resolution_millis schedule_rescue: List[_ScheduledPTRQuery] = [] while self._query_heap: query = self._query_heap[0] if query.cancelled: heappop(self._query_heap) continue if query.when_millis > end_time_millis: next_scheduled = query break query = heappop(self._query_heap) ready_types.add(query.name) del self._next_scheduled_for_alias[query.alias] # If there is still more than 10% of the TTL remaining # schedule a query again to try to rescue the record # from expiring. If the record is refreshed before # the query, the query will get cancelled. schedule_rescue.append(query) for query in schedule_rescue: self.schedule_rescue_query(query, now_millis, RESCUE_RECORD_RETRY_TTL_PERCENTAGE) if ready_types: self.async_send_ready_queries(False, now_millis, ready_types) next_time_millis = now_millis + self._min_time_between_queries_millis if next_scheduled is not None and next_scheduled.when_millis > next_time_millis: next_when_millis = next_scheduled.when_millis else: next_when_millis = next_time_millis self._next_run = self._loop.call_at(millis_to_seconds(next_when_millis), self._process_ready_types) def async_send_ready_queries( self, first_request: bool, now_millis: float_, ready_types: Set[str] ) -> None: """Send any ready queries.""" # If they did not specify and this is the first request, ask QU questions # https://datatracker.ietf.org/doc/html/rfc6762#section-5.4 since we are # just starting up and we know our cache is likely empty. This ensures # the next outgoing will be sent with the known answers list. question_type = QU_QUESTION if self._question_type is None and first_request else self._question_type outs = generate_service_query(self._zc, now_millis, ready_types, self._multicast, question_type) if outs: for out in outs: self._zc.async_send(out, self._addr, self._port) class _ServiceBrowserBase(RecordUpdateListener): """Base class for ServiceBrowser.""" __slots__ = ( 'types', 'zc', '_cache', '_loop', '_pending_handlers', '_service_state_changed', 'query_scheduler', 'done', '_query_sender_task', ) def __init__( self, zc: 'Zeroconf', type_: Union[str, list], handlers: Optional[Union[ServiceListener, List[Callable[..., None]]]] = None, listener: Optional[ServiceListener] = None, addr: Optional[str] = None, port: int = _MDNS_PORT, delay: int = _BROWSER_TIME, question_type: Optional[DNSQuestionType] = None, ) -> None: """Used to browse for a service for specific type(s). Constructor parameters are as follows: * `zc`: A Zeroconf instance * `type_`: fully qualified service type name * `handler`: ServiceListener or Callable that knows how to process ServiceStateChange events * `listener`: ServiceListener * `addr`: address to send queries (will default to multicast) * `port`: port to send queries (will default to mdns 5353) * `delay`: The initial delay between answering questions * `question_type`: The type of questions to ask (DNSQuestionType.QM or DNSQuestionType.QU) The listener object will have its add_service() and remove_service() methods called when this browser discovers changes in the services availability. """ assert handlers or listener, 'You need to specify at least one handler' self.types: Set[str] = set(type_ if isinstance(type_, list) else [type_]) for check_type_ in self.types: # Will generate BadTypeInNameException on a bad name service_type_name(check_type_, strict=False) self.zc = zc self._cache = zc.cache assert zc.loop is not None self._loop = zc.loop self._pending_handlers: Dict[Tuple[str, str], ServiceStateChange] = {} self._service_state_changed = Signal() self.query_scheduler = QueryScheduler( zc, self.types, addr, port, addr in (None, _MDNS_ADDR, _MDNS_ADDR6), delay, _FIRST_QUERY_DELAY_RANDOM_INTERVAL, question_type, ) self.done = False self._query_sender_task: Optional[asyncio.Task] = None if hasattr(handlers, 'add_service'): listener = cast('ServiceListener', handlers) handlers = None handlers = cast(List[Callable[..., None]], handlers or []) if listener: handlers.append(_service_state_changed_from_listener(listener)) for h in handlers: self.service_state_changed.register_handler(h) def _async_start(self) -> None: """Generate the next time and setup listeners. Must be called by uses of this base class after they have finished setting their properties. """ self.zc.async_add_listener(self, [DNSQuestion(type_, _TYPE_PTR, _CLASS_IN) for type_ in self.types]) # Only start queries after the listener is installed self._query_sender_task = asyncio.ensure_future(self._async_start_query_sender()) @property def service_state_changed(self) -> SignalRegistrationInterface: return self._service_state_changed.registration_interface def _names_matching_types(self, names: Iterable[str]) -> List[Tuple[str, str]]: """Return the type and name for records matching the types we are browsing.""" return [ (type_, name) for name in names for type_ in self.types.intersection(cached_possible_types(name)) ] def _enqueue_callback( self, state_change: ServiceStateChange, type_: str_, name: str_, ) -> None: # Code to ensure we only do a single update message # Precedence is; Added, Remove, Update key = (name, type_) if ( state_change is SERVICE_STATE_CHANGE_ADDED or ( state_change is SERVICE_STATE_CHANGE_REMOVED and self._pending_handlers.get(key) is not SERVICE_STATE_CHANGE_ADDED ) or (state_change is SERVICE_STATE_CHANGE_UPDATED and key not in self._pending_handlers) ): self._pending_handlers[key] = state_change def async_update_records(self, zc: 'Zeroconf', now: float_, records: List[RecordUpdate]) -> None: """Callback invoked by Zeroconf when new information arrives. Updates information required by browser in the Zeroconf cache. Ensures that there is are no unnecessary duplicates in the list. This method will be run in the event loop. """ for record_update in records: record = record_update.new old_record = record_update.old record_type = record.type if record_type is _TYPE_PTR: if TYPE_CHECKING: record = cast(DNSPointer, record) pointer = record for type_ in self.types.intersection(cached_possible_types(pointer.name)): if old_record is None: self._enqueue_callback(SERVICE_STATE_CHANGE_ADDED, type_, pointer.alias) self.query_scheduler.reschedule_ptr_first_refresh(pointer) elif pointer.is_expired(now): self._enqueue_callback(SERVICE_STATE_CHANGE_REMOVED, type_, pointer.alias) self.query_scheduler.cancel_ptr_refresh(pointer) else: self.query_scheduler.reschedule_ptr_first_refresh(pointer) continue # If its expired or already exists in the cache it cannot be updated. if old_record is not None or record.is_expired(now): continue if record_type in _ADDRESS_RECORD_TYPES: cache = self._cache names = {service.name for service in cache.async_entries_with_server(record.name)} # Iterate through the DNSCache and callback any services that use this address for type_, name in self._names_matching_types(names): self._enqueue_callback(SERVICE_STATE_CHANGE_UPDATED, type_, name) continue for type_, name in self._names_matching_types((record.name,)): self._enqueue_callback(SERVICE_STATE_CHANGE_UPDATED, type_, name) def async_update_records_complete(self) -> None: """Called when a record update has completed for all handlers. At this point the cache will have the new records. This method will be run in the event loop. This method is expected to be overridden by subclasses. """ for pending in self._pending_handlers.items(): self._fire_service_state_changed_event(pending) self._pending_handlers.clear() def _fire_service_state_changed_event(self, event: Tuple[Tuple[str, str], ServiceStateChange]) -> None: """Fire a service state changed event. When running with ServiceBrowser, this will happen in the dedicated thread. When running with AsyncServiceBrowser, this will happen in the event loop. """ name_type = event[0] state_change = event[1] self._service_state_changed.fire( zeroconf=self.zc, service_type=name_type[1], name=name_type[0], state_change=state_change, ) def _async_cancel(self) -> None: """Cancel the browser.""" self.done = True self.query_scheduler.stop() self.zc.async_remove_listener(self) assert self._query_sender_task is not None, "Attempted to cancel a browser that was not started" self._query_sender_task.cancel() self._query_sender_task = None async def _async_start_query_sender(self) -> None: """Start scheduling queries.""" if not self.zc.started: await self.zc.async_wait_for_start() self.query_scheduler.start(self._loop) class ServiceBrowser(_ServiceBrowserBase, threading.Thread): """Used to browse for a service of a specific type. The listener object will have its add_service() and remove_service() methods called when this browser discovers changes in the services availability.""" def __init__( self, zc: 'Zeroconf', type_: Union[str, list], handlers: Optional[Union[ServiceListener, List[Callable[..., None]]]] = None, listener: Optional[ServiceListener] = None, addr: Optional[str] = None, port: int = _MDNS_PORT, delay: int = _BROWSER_TIME, question_type: Optional[DNSQuestionType] = None, ) -> None: assert zc.loop is not None if not zc.loop.is_running(): raise RuntimeError("The event loop is not running") threading.Thread.__init__(self) super().__init__(zc, type_, handlers, listener, addr, port, delay, question_type) # Add the queue before the listener is installed in _setup # to ensure that events run in the dedicated thread and do # not block the event loop self.queue: queue.SimpleQueue = queue.SimpleQueue() self.daemon = True self.start() zc.loop.call_soon_threadsafe(self._async_start) self.name = "zeroconf-ServiceBrowser-{}-{}".format( '-'.join([type_[:-7] for type_ in self.types]), getattr(self, 'native_id', self.ident), ) def cancel(self) -> None: """Cancel the browser.""" assert self.zc.loop is not None self.queue.put(None) self.zc.loop.call_soon_threadsafe(self._async_cancel) self.join() def run(self) -> None: """Run the browser thread.""" while True: event = self.queue.get() if event is None: return self._fire_service_state_changed_event(event) def async_update_records_complete(self) -> None: """Called when a record update has completed for all handlers. At this point the cache will have the new records. This method will be run in the event loop. """ for pending in self._pending_handlers.items(): self.queue.put(pending) self._pending_handlers.clear() def __enter__(self) -> 'ServiceBrowser': return self def __exit__( # pylint: disable=useless-return self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: self.cancel() return None 07070100000049000081A40000000000000000000000016619D4CC0000129E000000000000000000000000000000000000003800000000python-zeroconf-0.132.2/src/zeroconf/_services/info.pxd import cython from .._cache cimport DNSCache from .._dns cimport ( DNSAddress, DNSNsec, DNSPointer, DNSQuestion, DNSRecord, DNSService, DNSText, ) from .._history cimport QuestionHistory from .._protocol.outgoing cimport DNSOutgoing from .._record_update cimport RecordUpdate from .._updates cimport RecordUpdateListener from .._utils.ipaddress cimport ( get_ip_address_object_from_record, ip_bytes_and_scope_to_address, str_without_scope_id, ) from .._utils.time cimport current_time_millis cdef object _resolve_all_futures_to_none cdef object _TYPE_SRV cdef object _TYPE_TXT cdef object _TYPE_A cdef object _TYPE_AAAA cdef object _TYPE_PTR cdef object _TYPE_NSEC cdef object _CLASS_IN cdef object _FLAGS_QR_QUERY cdef object service_type_name cdef object QU_QUESTION cdef object QM_QUESTION cdef object _IPVersion_All_value cdef object _IPVersion_V4Only_value cdef cython.set _ADDRESS_RECORD_TYPES cdef unsigned int _DUPLICATE_QUESTION_INTERVAL cdef bint TYPE_CHECKING cdef bint IPADDRESS_SUPPORTS_SCOPE_ID cdef object cached_ip_addresses cdef object randint cdef class ServiceInfo(RecordUpdateListener): cdef public cython.bytes text cdef public str type cdef str _name cdef public str key cdef public cython.list _ipv4_addresses cdef public cython.list _ipv6_addresses cdef public object port cdef public object weight cdef public object priority cdef public str server cdef public str server_key cdef public cython.dict _properties cdef public cython.dict _decoded_properties cdef public object host_ttl cdef public object other_ttl cdef public object interface_index cdef public cython.set _new_records_futures cdef public DNSPointer _dns_pointer_cache cdef public DNSService _dns_service_cache cdef public DNSText _dns_text_cache cdef public cython.list _dns_address_cache cdef public cython.set _get_address_and_nsec_records_cache @cython.locals(record_update=RecordUpdate, update=bint, cache=DNSCache) cpdef void async_update_records(self, object zc, double now, cython.list records) @cython.locals(cache=DNSCache) cpdef bint _load_from_cache(self, object zc, double now) @cython.locals(length="unsigned char", index="unsigned int", key_value=bytes, key_sep_value=tuple) cdef void _unpack_text_into_properties(self) @cython.locals(k=bytes, v=bytes) cdef void _generate_decoded_properties(self) @cython.locals(properties_contain_str=bint) cpdef void _set_properties(self, cython.dict properties) cdef void _set_text(self, cython.bytes text) @cython.locals(record=DNSAddress) cdef _get_ip_addresses_from_cache_lifo(self, object zc, double now, object type) @cython.locals( dns_service_record=DNSService, dns_text_record=DNSText, dns_address_record=DNSAddress ) cdef bint _process_record_threadsafe(self, object zc, DNSRecord record, double now) @cython.locals(cache=DNSCache) cdef cython.list _get_address_records_from_cache_by_type(self, object zc, object _type) cdef void _set_ipv4_addresses_from_cache(self, object zc, double now) cdef void _set_ipv6_addresses_from_cache(self, object zc, double now) cdef cython.list _ip_addresses_by_version_value(self, object version_value) cpdef addresses_by_version(self, object version) cpdef ip_addresses_by_version(self, object version) @cython.locals(cacheable=cython.bint) cdef cython.list _dns_addresses(self, object override_ttls, object version) @cython.locals(cacheable=cython.bint) cdef DNSPointer _dns_pointer(self, object override_ttl) @cython.locals(cacheable=cython.bint) cdef DNSService _dns_service(self, object override_ttl) @cython.locals(cacheable=cython.bint) cdef DNSText _dns_text(self, object override_ttl) cdef DNSNsec _dns_nsec(self, cython.list missing_types, object override_ttl) @cython.locals(cacheable=cython.bint) cdef cython.set _get_address_and_nsec_records(self, object override_ttl) cpdef void async_clear_cache(self) @cython.locals(cache=DNSCache, history=QuestionHistory, out=DNSOutgoing, qu_question=bint) cdef DNSOutgoing _generate_request_query(self, object zc, double now, object question_type) @cython.locals(question=DNSQuestion, answer=DNSRecord) cdef void _add_question_with_known_answers( self, DNSOutgoing out, bint qu_question, QuestionHistory question_history, DNSCache cache, double now, str name, object type_, object class_, bint skip_if_known_answers ) cdef double _get_initial_delay(self) cdef double _get_random_delay(self) 0707010000004A000081A40000000000000000000000016619D4CC00008E31000000000000000000000000000000000000003700000000python-zeroconf-0.132.2/src/zeroconf/_services/info.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import random import sys from ipaddress import IPv4Address, IPv6Address, _BaseAddress from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast from .._cache import DNSCache from .._dns import ( DNSAddress, DNSNsec, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, DNSService, DNSText, ) from .._exceptions import BadTypeInNameException from .._history import QuestionHistory from .._logger import log from .._protocol.outgoing import DNSOutgoing from .._record_update import RecordUpdate from .._updates import RecordUpdateListener from .._utils.asyncio import ( _resolve_all_futures_to_none, get_running_loop, run_coro_with_timeout, wait_for_future_set_or_timeout, ) from .._utils.ipaddress import ( cached_ip_addresses, get_ip_address_object_from_record, ip_bytes_and_scope_to_address, str_without_scope_id, ) from .._utils.name import service_type_name from .._utils.net import IPVersion, _encode_address from .._utils.time import current_time_millis from ..const import ( _ADDRESS_RECORD_TYPES, _CLASS_IN, _CLASS_IN_UNIQUE, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_NSEC, _TYPE_PTR, _TYPE_SRV, _TYPE_TXT, ) IPADDRESS_SUPPORTS_SCOPE_ID = sys.version_info >= (3, 9, 0) _IPVersion_All_value = IPVersion.All.value _IPVersion_V4Only_value = IPVersion.V4Only.value # https://datatracker.ietf.org/doc/html/rfc6762#section-5.2 # The most common case for calling ServiceInfo is from a # ServiceBrowser. After the first request we add a few random # milliseconds to the delay between requests to reduce the chance # that there are multiple ServiceBrowser callbacks running on # the network that are firing at the same time when they # see the same multicast response and decide to refresh # the A/AAAA/SRV records for a host. _AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) bytes_ = bytes float_ = float int_ = int str_ = str QU_QUESTION = DNSQuestionType.QU QM_QUESTION = DNSQuestionType.QM randint = random.randint if TYPE_CHECKING: from .._core import Zeroconf def instance_name_from_service_info(info: "ServiceInfo", strict: bool = True) -> str: """Calculate the instance name from the ServiceInfo.""" # This is kind of funky because of the subtype based tests # need to make subtypes a first class citizen service_name = service_type_name(info.name, strict=strict) if not info.type.endswith(service_name): raise BadTypeInNameException return info.name[: -len(service_name) - 1] class ServiceInfo(RecordUpdateListener): """Service information. Constructor parameters are as follows: * `type_`: fully qualified service type name * `name`: fully qualified service name * `port`: port that the service runs on * `weight`: weight of the service * `priority`: priority of the service * `properties`: dictionary of properties (or a bytes object holding the contents of the `text` field). converted to str and then encoded to bytes using UTF-8. Keys with `None` values are converted to value-less attributes. * `server`: fully qualified name for service host (defaults to name) * `host_ttl`: ttl used for A/SRV records * `other_ttl`: ttl used for PTR/TXT records * `addresses` and `parsed_addresses`: List of IP addresses (either as bytes, network byte order, or in parsed form as text; at most one of those parameters can be provided) * interface_index: scope_id or zone_id for IPv6 link-local addresses i.e. an identifier of the interface where the peer is connected to """ __slots__ = ( "text", "type", "_name", "key", "_ipv4_addresses", "_ipv6_addresses", "port", "weight", "priority", "server", "server_key", "_properties", "_decoded_properties", "host_ttl", "other_ttl", "interface_index", "_new_records_futures", "_dns_pointer_cache", "_dns_service_cache", "_dns_text_cache", "_dns_address_cache", "_get_address_and_nsec_records_cache", ) def __init__( self, type_: str, name: str, port: Optional[int] = None, weight: int = 0, priority: int = 0, properties: Union[bytes, Dict] = b'', server: Optional[str] = None, host_ttl: int = _DNS_HOST_TTL, other_ttl: int = _DNS_OTHER_TTL, *, addresses: Optional[List[bytes]] = None, parsed_addresses: Optional[List[str]] = None, interface_index: Optional[int] = None, ) -> None: # Accept both none, or one, but not both. if addresses is not None and parsed_addresses is not None: raise TypeError("addresses and parsed_addresses cannot be provided together") if not type_.endswith(service_type_name(name, strict=False)): raise BadTypeInNameException self.interface_index = interface_index self.text = b'' self.type = type_ self._name = name self.key = name.lower() self._ipv4_addresses: List[IPv4Address] = [] self._ipv6_addresses: List[IPv6Address] = [] if addresses is not None: self.addresses = addresses elif parsed_addresses is not None: self.addresses = [_encode_address(a) for a in parsed_addresses] self.port = port self.weight = weight self.priority = priority self.server = server if server else None self.server_key = server.lower() if server else None self._properties: Optional[Dict[bytes, Optional[bytes]]] = None self._decoded_properties: Optional[Dict[str, Optional[str]]] = None if isinstance(properties, bytes): self._set_text(properties) else: self._set_properties(properties) self.host_ttl = host_ttl self.other_ttl = other_ttl self._new_records_futures: Optional[Set[asyncio.Future]] = None self._dns_address_cache: Optional[List[DNSAddress]] = None self._dns_pointer_cache: Optional[DNSPointer] = None self._dns_service_cache: Optional[DNSService] = None self._dns_text_cache: Optional[DNSText] = None self._get_address_and_nsec_records_cache: Optional[Set[DNSRecord]] = None @property def name(self) -> str: """The name of the service.""" return self._name @name.setter def name(self, name: str) -> None: """Replace the the name and reset the key.""" self._name = name self.key = name.lower() self._dns_service_cache = None self._dns_pointer_cache = None self._dns_text_cache = None @property def addresses(self) -> List[bytes]: """IPv4 addresses of this service. Only IPv4 addresses are returned for backward compatibility. Use :meth:`addresses_by_version` or :meth:`parsed_addresses` to include IPv6 addresses as well. """ return self.addresses_by_version(IPVersion.V4Only) @addresses.setter def addresses(self, value: List[bytes]) -> None: """Replace the addresses list. This replaces all currently stored addresses, both IPv4 and IPv6. """ self._ipv4_addresses.clear() self._ipv6_addresses.clear() self._dns_address_cache = None self._get_address_and_nsec_records_cache = None for address in value: if IPADDRESS_SUPPORTS_SCOPE_ID and len(address) == 16 and self.interface_index is not None: addr = ip_bytes_and_scope_to_address(address, self.interface_index) else: addr = cached_ip_addresses(address) if addr is None: raise TypeError( "Addresses must either be IPv4 or IPv6 strings, bytes, or integers;" f" got {address!r}. Hint: convert string addresses with socket.inet_pton" ) if addr.version == 4: if TYPE_CHECKING: assert isinstance(addr, IPv4Address) self._ipv4_addresses.append(addr) else: if TYPE_CHECKING: assert isinstance(addr, IPv6Address) self._ipv6_addresses.append(addr) @property def properties(self) -> Dict[bytes, Optional[bytes]]: """Return properties as bytes.""" if self._properties is None: self._unpack_text_into_properties() if TYPE_CHECKING: assert self._properties is not None return self._properties @property def decoded_properties(self) -> Dict[str, Optional[str]]: """Return properties as strings.""" if self._decoded_properties is None: self._generate_decoded_properties() if TYPE_CHECKING: assert self._decoded_properties is not None return self._decoded_properties def async_clear_cache(self) -> None: """Clear the cache for this service info.""" self._dns_address_cache = None self._dns_pointer_cache = None self._dns_service_cache = None self._dns_text_cache = None self._get_address_and_nsec_records_cache = None async def async_wait(self, timeout: float, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: """Calling task waits for a given number of milliseconds or until notified.""" if not self._new_records_futures: self._new_records_futures = set() await wait_for_future_set_or_timeout( loop or asyncio.get_running_loop(), self._new_records_futures, timeout ) def addresses_by_version(self, version: IPVersion) -> List[bytes]: """List addresses matching IP version. Addresses are guaranteed to be returned in LIFO (last in, first out) order with IPv4 addresses first and IPv6 addresses second. This means the first address will always be the most recently added address of the given IP version. """ version_value = version.value if version_value == _IPVersion_All_value: ip_v4_packed = [addr.packed for addr in self._ipv4_addresses] ip_v6_packed = [addr.packed for addr in self._ipv6_addresses] return [*ip_v4_packed, *ip_v6_packed] if version_value == _IPVersion_V4Only_value: return [addr.packed for addr in self._ipv4_addresses] return [addr.packed for addr in self._ipv6_addresses] def ip_addresses_by_version( self, version: IPVersion ) -> Union[List[IPv4Address], List[IPv6Address], List[_BaseAddress]]: """List ip_address objects matching IP version. Addresses are guaranteed to be returned in LIFO (last in, first out) order with IPv4 addresses first and IPv6 addresses second. This means the first address will always be the most recently added address of the given IP version. """ return self._ip_addresses_by_version_value(version.value) def _ip_addresses_by_version_value( self, version_value: int_ ) -> Union[List[IPv4Address], List[IPv6Address]]: """Backend for addresses_by_version that uses the raw value.""" if version_value == _IPVersion_All_value: return [*self._ipv4_addresses, *self._ipv6_addresses] # type: ignore[return-value] if version_value == _IPVersion_V4Only_value: return self._ipv4_addresses return self._ipv6_addresses def parsed_addresses(self, version: IPVersion = IPVersion.All) -> List[str]: """List addresses in their parsed string form. Addresses are guaranteed to be returned in LIFO (last in, first out) order with IPv4 addresses first and IPv6 addresses second. This means the first address will always be the most recently added address of the given IP version. """ return [str_without_scope_id(addr) for addr in self._ip_addresses_by_version_value(version.value)] def parsed_scoped_addresses(self, version: IPVersion = IPVersion.All) -> List[str]: """Equivalent to parsed_addresses, with the exception that IPv6 Link-Local addresses are qualified with %<interface_index> when available Addresses are guaranteed to be returned in LIFO (last in, first out) order with IPv4 addresses first and IPv6 addresses second. This means the first address will always be the most recently added address of the given IP version. """ return [str(addr) for addr in self._ip_addresses_by_version_value(version.value)] def _set_properties(self, properties: Dict[Union[str, bytes], Optional[Union[str, bytes]]]) -> None: """Sets properties and text of this info from a dictionary""" list_: List[bytes] = [] properties_contain_str = False result = b'' for key, value in properties.items(): if isinstance(key, str): key = key.encode('utf-8') properties_contain_str = True record = key if value is not None: if not isinstance(value, bytes): value = str(value).encode('utf-8') properties_contain_str = True record += b'=' + value list_.append(record) for item in list_: result = b''.join((result, bytes((len(item),)), item)) if not properties_contain_str: # If there are no str keys or values, we can use the properties # as-is, without decoding them, otherwise calling # self.properties will lazy decode them, which is expensive. if TYPE_CHECKING: self._properties = cast("Dict[bytes, Optional[bytes]]", properties) else: self._properties = properties self.text = result def _set_text(self, text: bytes) -> None: """Sets properties and text given a text field""" if text == self.text: return self.text = text # Clear the properties cache self._properties = None self._decoded_properties = None def _generate_decoded_properties(self) -> None: """Generates decoded properties from the properties""" self._decoded_properties = { k.decode("ascii", "replace"): None if v is None else v.decode("utf-8", "replace") for k, v in self.properties.items() } def _unpack_text_into_properties(self) -> None: """Unpacks the text field into properties""" text = self.text end = len(text) if end == 0: # Properties should be set atomically # in case another thread is reading them self._properties = {} return index = 0 properties: Dict[bytes, Optional[bytes]] = {} while index < end: length = text[index] index += 1 key_value = text[index : index + length] key_sep_value = key_value.partition(b'=') key = key_sep_value[0] if key not in properties: properties[key] = key_sep_value[2] or None index += length self._properties = properties def get_name(self) -> str: """Name accessor""" return self._name[: len(self._name) - len(self.type) - 1] def _get_ip_addresses_from_cache_lifo( self, zc: 'Zeroconf', now: float_, type: int_ ) -> List[Union[IPv4Address, IPv6Address]]: """Set IPv6 addresses from the cache.""" address_list: List[Union[IPv4Address, IPv6Address]] = [] for record in self._get_address_records_from_cache_by_type(zc, type): if record.is_expired(now): continue ip_addr = get_ip_address_object_from_record(record) if ip_addr is not None and ip_addr not in address_list: address_list.append(ip_addr) address_list.reverse() # Reverse to get LIFO order return address_list def _set_ipv6_addresses_from_cache(self, zc: 'Zeroconf', now: float_) -> None: """Set IPv6 addresses from the cache.""" if TYPE_CHECKING: self._ipv6_addresses = cast( "List[IPv6Address]", self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_AAAA) ) else: self._ipv6_addresses = self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_AAAA) def _set_ipv4_addresses_from_cache(self, zc: 'Zeroconf', now: float_) -> None: """Set IPv4 addresses from the cache.""" if TYPE_CHECKING: self._ipv4_addresses = cast( "List[IPv4Address]", self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_A) ) else: self._ipv4_addresses = self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_A) def async_update_records(self, zc: 'Zeroconf', now: float_, records: List[RecordUpdate]) -> None: """Updates service information from a DNS record. This method will be run in the event loop. """ new_records_futures = self._new_records_futures updated: bool = False for record_update in records: updated |= self._process_record_threadsafe(zc, record_update.new, now) if updated and new_records_futures: _resolve_all_futures_to_none(new_records_futures) def _process_record_threadsafe(self, zc: 'Zeroconf', record: DNSRecord, now: float_) -> bool: """Thread safe record updating. Returns True if a new record was added. """ if record.is_expired(now): return False record_key = record.key record_type = type(record) if record_type is DNSAddress and record_key == self.server_key: dns_address_record = record if TYPE_CHECKING: assert isinstance(dns_address_record, DNSAddress) ip_addr = get_ip_address_object_from_record(dns_address_record) if ip_addr is None: log.warning( "Encountered invalid address while processing %s: %s", dns_address_record, dns_address_record.address, ) return False if ip_addr.version == 4: if TYPE_CHECKING: assert isinstance(ip_addr, IPv4Address) ipv4_addresses = self._ipv4_addresses if ip_addr not in ipv4_addresses: ipv4_addresses.insert(0, ip_addr) return True elif ip_addr != ipv4_addresses[0]: ipv4_addresses.remove(ip_addr) ipv4_addresses.insert(0, ip_addr) return False if TYPE_CHECKING: assert isinstance(ip_addr, IPv6Address) ipv6_addresses = self._ipv6_addresses if ip_addr not in self._ipv6_addresses: ipv6_addresses.insert(0, ip_addr) return True elif ip_addr != self._ipv6_addresses[0]: ipv6_addresses.remove(ip_addr) ipv6_addresses.insert(0, ip_addr) return False if record_key != self.key: return False if record_type is DNSText: dns_text_record = record if TYPE_CHECKING: assert isinstance(dns_text_record, DNSText) self._set_text(dns_text_record.text) return True if record_type is DNSService: dns_service_record = record if TYPE_CHECKING: assert isinstance(dns_service_record, DNSService) old_server_key = self.server_key self._name = dns_service_record.name self.key = dns_service_record.key self.server = dns_service_record.server self.server_key = dns_service_record.server_key self.port = dns_service_record.port self.weight = dns_service_record.weight self.priority = dns_service_record.priority if old_server_key != self.server_key: self._set_ipv4_addresses_from_cache(zc, now) self._set_ipv6_addresses_from_cache(zc, now) return True return False def dns_addresses( self, override_ttl: Optional[int] = None, version: IPVersion = IPVersion.All, ) -> List[DNSAddress]: """Return matching DNSAddress from ServiceInfo.""" return self._dns_addresses(override_ttl, version) def _dns_addresses( self, override_ttl: Optional[int], version: IPVersion, ) -> List[DNSAddress]: """Return matching DNSAddress from ServiceInfo.""" cacheable = version is IPVersion.All and override_ttl is None if self._dns_address_cache is not None and cacheable: return self._dns_address_cache name = self.server or self._name ttl = override_ttl if override_ttl is not None else self.host_ttl class_ = _CLASS_IN_UNIQUE version_value = version.value records = [ DNSAddress( name, _TYPE_AAAA if ip_addr.version == 6 else _TYPE_A, class_, ttl, ip_addr.packed, created=0.0, ) for ip_addr in self._ip_addresses_by_version_value(version_value) ] if cacheable: self._dns_address_cache = records return records def dns_pointer(self, override_ttl: Optional[int] = None) -> DNSPointer: """Return DNSPointer from ServiceInfo.""" return self._dns_pointer(override_ttl) def _dns_pointer(self, override_ttl: Optional[int]) -> DNSPointer: """Return DNSPointer from ServiceInfo.""" cacheable = override_ttl is None if self._dns_pointer_cache is not None and cacheable: return self._dns_pointer_cache record = DNSPointer( self.type, _TYPE_PTR, _CLASS_IN, override_ttl if override_ttl is not None else self.other_ttl, self._name, 0.0, ) if cacheable: self._dns_pointer_cache = record return record def dns_service(self, override_ttl: Optional[int] = None) -> DNSService: """Return DNSService from ServiceInfo.""" return self._dns_service(override_ttl) def _dns_service(self, override_ttl: Optional[int]) -> DNSService: """Return DNSService from ServiceInfo.""" cacheable = override_ttl is None if self._dns_service_cache is not None and cacheable: return self._dns_service_cache port = self.port if TYPE_CHECKING: assert isinstance(port, int) record = DNSService( self._name, _TYPE_SRV, _CLASS_IN_UNIQUE, override_ttl if override_ttl is not None else self.host_ttl, self.priority, self.weight, port, self.server or self._name, 0.0, ) if cacheable: self._dns_service_cache = record return record def dns_text(self, override_ttl: Optional[int] = None) -> DNSText: """Return DNSText from ServiceInfo.""" return self._dns_text(override_ttl) def _dns_text(self, override_ttl: Optional[int]) -> DNSText: """Return DNSText from ServiceInfo.""" cacheable = override_ttl is None if self._dns_text_cache is not None and cacheable: return self._dns_text_cache record = DNSText( self._name, _TYPE_TXT, _CLASS_IN_UNIQUE, override_ttl if override_ttl is not None else self.other_ttl, self.text, 0.0, ) if cacheable: self._dns_text_cache = record return record def dns_nsec(self, missing_types: List[int], override_ttl: Optional[int] = None) -> DNSNsec: """Return DNSNsec from ServiceInfo.""" return self._dns_nsec(missing_types, override_ttl) def _dns_nsec(self, missing_types: List[int], override_ttl: Optional[int]) -> DNSNsec: """Return DNSNsec from ServiceInfo.""" return DNSNsec( self._name, _TYPE_NSEC, _CLASS_IN_UNIQUE, override_ttl if override_ttl is not None else self.host_ttl, self._name, missing_types, 0.0, ) def get_address_and_nsec_records(self, override_ttl: Optional[int] = None) -> Set[DNSRecord]: """Build a set of address records and NSEC records for non-present record types.""" return self._get_address_and_nsec_records(override_ttl) def _get_address_and_nsec_records(self, override_ttl: Optional[int]) -> Set[DNSRecord]: """Build a set of address records and NSEC records for non-present record types.""" cacheable = override_ttl is None if self._get_address_and_nsec_records_cache is not None and cacheable: return self._get_address_and_nsec_records_cache missing_types: Set[int] = _ADDRESS_RECORD_TYPES.copy() records: Set[DNSRecord] = set() for dns_address in self._dns_addresses(override_ttl, IPVersion.All): missing_types.discard(dns_address.type) records.add(dns_address) if missing_types: assert self.server is not None, "Service server must be set for NSEC record." records.add(self._dns_nsec(list(missing_types), override_ttl)) if cacheable: self._get_address_and_nsec_records_cache = records return records def _get_address_records_from_cache_by_type(self, zc: 'Zeroconf', _type: int_) -> List[DNSAddress]: """Get the addresses from the cache.""" if self.server_key is None: return [] cache = zc.cache if TYPE_CHECKING: records = cast("List[DNSAddress]", cache.get_all_by_details(self.server_key, _type, _CLASS_IN)) else: records = cache.get_all_by_details(self.server_key, _type, _CLASS_IN) return records def set_server_if_missing(self) -> None: """Set the server if it is missing. This function is for backwards compatibility. """ if self.server is None: self.server = self._name self.server_key = self.key def load_from_cache(self, zc: 'Zeroconf', now: Optional[float_] = None) -> bool: """Populate the service info from the cache. This method is designed to be threadsafe. """ return self._load_from_cache(zc, now or current_time_millis()) def _load_from_cache(self, zc: 'Zeroconf', now: float_) -> bool: """Populate the service info from the cache. This method is designed to be threadsafe. """ cache = zc.cache original_server_key = self.server_key cached_srv_record = cache.get_by_details(self._name, _TYPE_SRV, _CLASS_IN) if cached_srv_record: self._process_record_threadsafe(zc, cached_srv_record, now) cached_txt_record = cache.get_by_details(self._name, _TYPE_TXT, _CLASS_IN) if cached_txt_record: self._process_record_threadsafe(zc, cached_txt_record, now) if original_server_key == self.server_key: # If there is a srv which changes the server_key, # A and AAAA will already be loaded from the cache # and we do not want to do it twice for record in self._get_address_records_from_cache_by_type(zc, _TYPE_A): self._process_record_threadsafe(zc, record, now) for record in self._get_address_records_from_cache_by_type(zc, _TYPE_AAAA): self._process_record_threadsafe(zc, record, now) return self._is_complete @property def _is_complete(self) -> bool: """The ServiceInfo has all expected properties.""" return bool(self.text is not None and (self._ipv4_addresses or self._ipv6_addresses)) def request( self, zc: 'Zeroconf', timeout: float, question_type: Optional[DNSQuestionType] = None, addr: Optional[str] = None, port: int = _MDNS_PORT, ) -> bool: """Returns true if the service could be discovered on the network, and updates this object with details discovered. While it is not expected during normal operation, this function may raise EventLoopBlocked if the underlying call to `async_request` cannot be completed. :param zc: Zeroconf instance :param timeout: time in milliseconds to wait for a response :param question_type: question type to ask :param addr: address to send the request to :param port: port to send the request to """ assert zc.loop is not None and zc.loop.is_running() if zc.loop == get_running_loop(): raise RuntimeError("Use AsyncServiceInfo.async_request from the event loop") return bool( run_coro_with_timeout( self.async_request(zc, timeout, question_type, addr, port), zc.loop, timeout ) ) def _get_initial_delay(self) -> float_: return _LISTENER_TIME def _get_random_delay(self) -> int_: return randint(*_AVOID_SYNC_DELAY_RANDOM_INTERVAL) async def async_request( self, zc: 'Zeroconf', timeout: float, question_type: Optional[DNSQuestionType] = None, addr: Optional[str] = None, port: int = _MDNS_PORT, ) -> bool: """Returns true if the service could be discovered on the network, and updates this object with details discovered. This method will be run in the event loop. Passing addr and port is optional, and will default to the mDNS multicast address and port. This is useful for directing requests to a specific host that may be able to respond across subnets. :param zc: Zeroconf instance :param timeout: time in milliseconds to wait for a response :param question_type: question type to ask :param addr: address to send the request to :param port: port to send the request to """ if not zc.started: await zc.async_wait_for_start() now = current_time_millis() if self._load_from_cache(zc, now): return True if TYPE_CHECKING: assert zc.loop is not None first_request = True delay = self._get_initial_delay() next_ = now last = now + timeout try: zc.async_add_listener(self, None) while not self._is_complete: if last <= now: return False if next_ <= now: this_question_type = question_type or QU_QUESTION if first_request else QM_QUESTION out = self._generate_request_query(zc, now, this_question_type) first_request = False if out.questions: # All questions may have been suppressed # by the question history, so nothing to send, # but keep waiting for answers in case another # client on the network is asking the same # question or they have not arrived yet. zc.async_send(out, addr, port) next_ = now + delay next_ += self._get_random_delay() if this_question_type is QM_QUESTION and delay < _DUPLICATE_QUESTION_INTERVAL: # If we just asked a QM question, we need to # wait at least the duplicate question interval # before asking another QM question otherwise # its likely to be suppressed by the question # history of the remote responder. delay = _DUPLICATE_QUESTION_INTERVAL await self.async_wait(min(next_, last) - now, zc.loop) now = current_time_millis() finally: zc.async_remove_listener(self) return True def _add_question_with_known_answers( self, out: DNSOutgoing, qu_question: bool, question_history: QuestionHistory, cache: DNSCache, now: float_, name: str_, type_: int_, class_: int_, skip_if_known_answers: bool, ) -> None: """Add a question with known answers if its not suppressed.""" known_answers = { answer for answer in cache.get_all_by_details(name, type_, class_) if not answer.is_stale(now) } if skip_if_known_answers and known_answers: return question = DNSQuestion(name, type_, class_) if qu_question: question.unicast = True elif question_history.suppresses(question, now, known_answers): return else: question_history.add_question_at_time(question, now, known_answers) out.add_question(question) for answer in known_answers: out.add_answer_at_time(answer, now) def _generate_request_query( self, zc: 'Zeroconf', now: float_, question_type: DNSQuestionType ) -> DNSOutgoing: """Generate the request query.""" out = DNSOutgoing(_FLAGS_QR_QUERY) name = self._name server = self.server or name cache = zc.cache history = zc.question_history qu_question = question_type is QU_QUESTION self._add_question_with_known_answers( out, qu_question, history, cache, now, name, _TYPE_SRV, _CLASS_IN, True ) self._add_question_with_known_answers( out, qu_question, history, cache, now, name, _TYPE_TXT, _CLASS_IN, True ) self._add_question_with_known_answers( out, qu_question, history, cache, now, server, _TYPE_A, _CLASS_IN, False ) self._add_question_with_known_answers( out, qu_question, history, cache, now, server, _TYPE_AAAA, _CLASS_IN, False ) return out def __repr__(self) -> str: """String representation""" return '{}({})'.format( type(self).__name__, ', '.join( f'{name}={getattr(self, name)!r}' for name in ( 'type', 'name', 'addresses', 'port', 'weight', 'priority', 'server', 'properties', 'interface_index', ) ), ) class AsyncServiceInfo(ServiceInfo): """An async version of ServiceInfo.""" 0707010000004B000081A40000000000000000000000016619D4CC000002ED000000000000000000000000000000000000003C00000000python-zeroconf-0.132.2/src/zeroconf/_services/registry.pxd import cython from .info cimport ServiceInfo cdef class ServiceRegistry: cdef cython.dict _services cdef public cython.dict types cdef public cython.dict servers cdef public bint has_entries @cython.locals( record_list=cython.list, ) cdef cython.list _async_get_by_index(self, cython.dict records, str key) cdef _add(self, ServiceInfo info) @cython.locals( info=ServiceInfo, old_service_info=ServiceInfo ) cdef _remove(self, cython.list infos) cpdef ServiceInfo async_get_info_name(self, str name) cpdef cython.list async_get_types(self) cpdef cython.list async_get_infos_type(self, str type_) cpdef cython.list async_get_infos_server(self, str server) 0707010000004C000081A40000000000000000000000016619D4CC0000109F000000000000000000000000000000000000003B00000000python-zeroconf-0.132.2/src/zeroconf/_services/registry.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from typing import Dict, List, Optional, Union from .._exceptions import ServiceNameAlreadyRegistered from .info import ServiceInfo _str = str class ServiceRegistry: """A registry to keep track of services. The registry must only be accessed from the event loop as it is not thread safe. """ __slots__ = ("_services", "types", "servers", "has_entries") def __init__( self, ) -> None: """Create the ServiceRegistry class.""" self._services: Dict[str, ServiceInfo] = {} self.types: Dict[str, List] = {} self.servers: Dict[str, List] = {} self.has_entries: bool = False def async_add(self, info: ServiceInfo) -> None: """Add a new service to the registry.""" self._add(info) def async_remove(self, info: Union[List[ServiceInfo], ServiceInfo]) -> None: """Remove a new service from the registry.""" self._remove(info if isinstance(info, list) else [info]) def async_update(self, info: ServiceInfo) -> None: """Update new service in the registry.""" self._remove([info]) self._add(info) def async_get_service_infos(self) -> List[ServiceInfo]: """Return all ServiceInfo.""" return list(self._services.values()) def async_get_info_name(self, name: str) -> Optional[ServiceInfo]: """Return all ServiceInfo for the name.""" return self._services.get(name) def async_get_types(self) -> List[str]: """Return all types.""" return list(self.types) def async_get_infos_type(self, type_: str) -> List[ServiceInfo]: """Return all ServiceInfo matching type.""" return self._async_get_by_index(self.types, type_) def async_get_infos_server(self, server: str) -> List[ServiceInfo]: """Return all ServiceInfo matching server.""" return self._async_get_by_index(self.servers, server) def _async_get_by_index(self, records: Dict[str, List], key: _str) -> List[ServiceInfo]: """Return all ServiceInfo matching the index.""" record_list = records.get(key) if record_list is None: return [] return [self._services[name] for name in record_list] def _add(self, info: ServiceInfo) -> None: """Add a new service under the lock.""" assert info.server_key is not None, "ServiceInfo must have a server" if info.key in self._services: raise ServiceNameAlreadyRegistered info.async_clear_cache() self._services[info.key] = info self.types.setdefault(info.type.lower(), []).append(info.key) self.servers.setdefault(info.server_key, []).append(info.key) self.has_entries = True def _remove(self, infos: List[ServiceInfo]) -> None: """Remove a services under the lock.""" for info in infos: old_service_info = self._services.get(info.key) if old_service_info is None: continue assert old_service_info.server_key is not None self.types[old_service_info.type.lower()].remove(info.key) self.servers[old_service_info.server_key].remove(info.key) del self._services[info.key] self.has_entries = bool(self._services) 0707010000004D000081A40000000000000000000000016619D4CC00000BBB000000000000000000000000000000000000003800000000python-zeroconf-0.132.2/src/zeroconf/_services/types.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import time from typing import Optional, Set, Tuple, Union from .._core import Zeroconf from .._services import ServiceListener from .._utils.net import InterfaceChoice, InterfacesType, IPVersion from ..const import _SERVICE_TYPE_ENUMERATION_NAME from .browser import ServiceBrowser class ZeroconfServiceTypes(ServiceListener): """ Return all of the advertised services on any local networks """ def __init__(self) -> None: """Keep track of found services in a set.""" self.found_services: Set[str] = set() def add_service(self, zc: Zeroconf, type_: str, name: str) -> None: """Service added.""" self.found_services.add(name) def update_service(self, zc: Zeroconf, type_: str, name: str) -> None: """Service updated.""" def remove_service(self, zc: Zeroconf, type_: str, name: str) -> None: """Service removed.""" @classmethod def find( cls, zc: Optional[Zeroconf] = None, timeout: Union[int, float] = 5, interfaces: InterfacesType = InterfaceChoice.All, ip_version: Optional[IPVersion] = None, ) -> Tuple[str, ...]: """ Return all of the advertised services on any local networks. :param zc: Zeroconf() instance. Pass in if already have an instance running or if non-default interfaces are needed :param timeout: seconds to wait for any responses :param interfaces: interfaces to listen on. :param ip_version: IP protocol version to use. :return: tuple of service type strings """ local_zc = zc or Zeroconf(interfaces=interfaces, ip_version=ip_version) listener = cls() browser = ServiceBrowser(local_zc, _SERVICE_TYPE_ENUMERATION_NAME, listener=listener) # wait for responses time.sleep(timeout) browser.cancel() # close down anything we opened if zc is None: local_zc.close() return tuple(sorted(listener.found_services)) 0707010000004E000081A40000000000000000000000016619D4CC00000809000000000000000000000000000000000000003300000000python-zeroconf-0.132.2/src/zeroconf/_transport.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import socket from typing import Tuple class _WrappedTransport: """A wrapper for transports.""" __slots__ = ( 'transport', 'is_ipv6', 'sock', 'fileno', 'sock_name', ) def __init__( self, transport: asyncio.DatagramTransport, is_ipv6: bool, sock: socket.socket, fileno: int, sock_name: Tuple, ) -> None: """Initialize the wrapped transport. These attributes are used when sending packets. """ self.transport = transport self.is_ipv6 = is_ipv6 self.sock = sock self.fileno = fileno self.sock_name = sock_name def make_wrapped_transport(transport: asyncio.DatagramTransport) -> _WrappedTransport: """Make a wrapped transport.""" sock: socket.socket = transport.get_extra_info('socket') return _WrappedTransport( transport=transport, is_ipv6=sock.family == socket.AF_INET6, sock=sock, fileno=sock.fileno(), sock_name=sock.getsockname(), ) 0707010000004F000081A40000000000000000000000016619D4CC000000BD000000000000000000000000000000000000003200000000python-zeroconf-0.132.2/src/zeroconf/_updates.pxd import cython cdef class RecordUpdateListener: cpdef void async_update_records(self, object zc, double now, cython.list records) cpdef void async_update_records_complete(self) 07070100000050000081A40000000000000000000000016619D4CC00000B32000000000000000000000000000000000000003100000000python-zeroconf-0.132.2/src/zeroconf/_updates.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from typing import TYPE_CHECKING, List from ._dns import DNSRecord from ._record_update import RecordUpdate if TYPE_CHECKING: from ._core import Zeroconf float_ = float class RecordUpdateListener: """Base call for all record listeners. All listeners passed to async_add_listener should use RecordUpdateListener as a base class. In the future it will be required. """ def update_record( # pylint: disable=no-self-use self, zc: 'Zeroconf', now: float, record: DNSRecord ) -> None: """Update a single record. This method is deprecated and will be removed in a future version. update_records should be implemented instead. """ raise RuntimeError("update_record is deprecated and will be removed in a future version.") def async_update_records(self, zc: 'Zeroconf', now: float_, records: List[RecordUpdate]) -> None: """Update multiple records in one shot. All records that are received in a single packet are passed to update_records. This implementation is a compatibility shim to ensure older code that uses RecordUpdateListener as a base class will continue to get calls to update_record. This method will raise NotImplementedError in a future version. At this point the cache will not have the new records Records are passed as a list of RecordUpdate. This allows consumers of async_update_records to avoid cache lookups. This method will be run in the event loop. """ for record in records: self.update_record(zc, now, record.new) def async_update_records_complete(self) -> None: """Called when a record update has completed for all handlers. At this point the cache will have the new records. This method will be run in the event loop. """ 07070100000051000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002C00000000python-zeroconf-0.132.2/src/zeroconf/_utils07070100000052000081A40000000000000000000000016619D4CC000003CB000000000000000000000000000000000000003800000000python-zeroconf-0.132.2/src/zeroconf/_utils/__init__.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ 07070100000053000081A40000000000000000000000016619D4CC0000137B000000000000000000000000000000000000003700000000python-zeroconf-0.132.2/src/zeroconf/_utils/asyncio.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import concurrent.futures import contextlib import sys from typing import Any, Awaitable, Coroutine, Optional, Set if sys.version_info[:2] < (3, 11): from async_timeout import timeout as asyncio_timeout else: from asyncio import timeout as asyncio_timeout from .._exceptions import EventLoopBlocked from ..const import _LOADED_SYSTEM_TIMEOUT from .time import millis_to_seconds # The combined timeouts should be lower than _CLOSE_TIMEOUT + _WAIT_FOR_LOOP_TASKS_TIMEOUT _TASK_AWAIT_TIMEOUT = 1 _GET_ALL_TASKS_TIMEOUT = 3 _WAIT_FOR_LOOP_TASKS_TIMEOUT = 3 # Must be larger than _TASK_AWAIT_TIMEOUT def _set_future_none_if_not_done(fut: asyncio.Future) -> None: """Set a future to None if it is not done.""" if not fut.done(): # pragma: no branch fut.set_result(None) def _resolve_all_futures_to_none(futures: Set[asyncio.Future]) -> None: """Resolve all futures to None.""" for fut in futures: _set_future_none_if_not_done(fut) futures.clear() async def wait_for_future_set_or_timeout( loop: asyncio.AbstractEventLoop, future_set: Set[asyncio.Future], timeout: float ) -> None: """Wait for a future or timeout (in milliseconds).""" future = loop.create_future() future_set.add(future) handle = loop.call_later(millis_to_seconds(timeout), _set_future_none_if_not_done, future) try: await future finally: handle.cancel() future_set.discard(future) async def wait_event_or_timeout(event: asyncio.Event, timeout: float) -> None: """Wait for an event or timeout.""" with contextlib.suppress(asyncio.TimeoutError): async with asyncio_timeout(timeout): await event.wait() async def _async_get_all_tasks(loop: asyncio.AbstractEventLoop) -> Set[asyncio.Task]: """Return all tasks running.""" await asyncio.sleep(0) # flush out any call_soon_threadsafe # If there are multiple event loops running, all_tasks is not # safe EVEN WHEN CALLED FROM THE EVENTLOOP # under PyPy so we have to try a few times. for _ in range(3): with contextlib.suppress(RuntimeError): return asyncio.all_tasks(loop) return set() async def _wait_for_loop_tasks(wait_tasks: Set[asyncio.Task]) -> None: """Wait for the event loop thread we started to shutdown.""" await asyncio.wait(wait_tasks, timeout=_TASK_AWAIT_TIMEOUT) async def await_awaitable(aw: Awaitable) -> None: """Wait on an awaitable and the task it returns.""" task = await aw await task def run_coro_with_timeout(aw: Coroutine, loop: asyncio.AbstractEventLoop, timeout: float) -> Any: """Run a coroutine with a timeout. The timeout should only be used as a safeguard to prevent the program from blocking forever. The timeout should never be expected to be reached during normal operation. While not expected during normal operations, the function raises `EventLoopBlocked` if the coroutine takes longer to complete than the timeout. """ try: return asyncio.run_coroutine_threadsafe(aw, loop).result( millis_to_seconds(timeout) + _LOADED_SYSTEM_TIMEOUT ) except concurrent.futures.TimeoutError as ex: raise EventLoopBlocked from ex def shutdown_loop(loop: asyncio.AbstractEventLoop) -> None: """Wait for pending tasks and stop an event loop.""" pending_tasks = set( asyncio.run_coroutine_threadsafe(_async_get_all_tasks(loop), loop).result(_GET_ALL_TASKS_TIMEOUT) ) pending_tasks -= {task for task in pending_tasks if task.done()} if pending_tasks: asyncio.run_coroutine_threadsafe(_wait_for_loop_tasks(pending_tasks), loop).result( _WAIT_FOR_LOOP_TASKS_TIMEOUT ) loop.call_soon_threadsafe(loop.stop) def get_running_loop() -> Optional[asyncio.AbstractEventLoop]: """Check if an event loop is already running.""" with contextlib.suppress(RuntimeError): return asyncio.get_running_loop() return None 07070100000054000081A40000000000000000000000016619D4CC00000150000000000000000000000000000000000000003A00000000python-zeroconf-0.132.2/src/zeroconf/_utils/ipaddress.pxdcdef bint TYPE_CHECKING cdef bint IPADDRESS_SUPPORTS_SCOPE_ID from .._dns cimport DNSAddress cpdef get_ip_address_object_from_record(DNSAddress record) @cython.locals(address_str=str) cpdef str_without_scope_id(object addr) cpdef ip_bytes_and_scope_to_address(object addr, object scope_id) cdef object cached_ip_addresses_wrapper 07070100000055000081A40000000000000000000000016619D4CC00001281000000000000000000000000000000000000003900000000python-zeroconf-0.132.2/src/zeroconf/_utils/ipaddress.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import sys from functools import lru_cache from ipaddress import AddressValueError, IPv4Address, IPv6Address, NetmaskValueError from typing import Any, Optional, Union from .._dns import DNSAddress from ..const import _TYPE_AAAA bytes_ = bytes int_ = int IPADDRESS_SUPPORTS_SCOPE_ID = sys.version_info >= (3, 9, 0) class ZeroconfIPv4Address(IPv4Address): __slots__ = ("_str", "_is_link_local", "_is_unspecified") def __init__(self, *args: Any, **kwargs: Any) -> None: """Initialize a new IPv4 address.""" super().__init__(*args, **kwargs) self._str = super().__str__() self._is_link_local = super().is_link_local self._is_unspecified = super().is_unspecified def __str__(self) -> str: """Return the string representation of the IPv4 address.""" return self._str @property def is_link_local(self) -> bool: """Return True if this is a link-local address.""" return self._is_link_local @property def is_unspecified(self) -> bool: """Return True if this is an unspecified address.""" return self._is_unspecified class ZeroconfIPv6Address(IPv6Address): __slots__ = ("_str", "_is_link_local", "_is_unspecified") def __init__(self, *args: Any, **kwargs: Any) -> None: """Initialize a new IPv6 address.""" super().__init__(*args, **kwargs) self._str = super().__str__() self._is_link_local = super().is_link_local self._is_unspecified = super().is_unspecified def __str__(self) -> str: """Return the string representation of the IPv6 address.""" return self._str @property def is_link_local(self) -> bool: """Return True if this is a link-local address.""" return self._is_link_local @property def is_unspecified(self) -> bool: """Return True if this is an unspecified address.""" return self._is_unspecified @lru_cache(maxsize=512) def _cached_ip_addresses(address: Union[str, bytes, int]) -> Optional[Union[IPv4Address, IPv6Address]]: """Cache IP addresses.""" try: return ZeroconfIPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return ZeroconfIPv6Address(address) except (AddressValueError, NetmaskValueError): return None cached_ip_addresses_wrapper = _cached_ip_addresses cached_ip_addresses = cached_ip_addresses_wrapper def get_ip_address_object_from_record(record: DNSAddress) -> Optional[Union[IPv4Address, IPv6Address]]: """Get the IP address object from the record.""" if IPADDRESS_SUPPORTS_SCOPE_ID and record.type == _TYPE_AAAA and record.scope_id: return ip_bytes_and_scope_to_address(record.address, record.scope_id) return cached_ip_addresses_wrapper(record.address) def ip_bytes_and_scope_to_address(address: bytes_, scope: int_) -> Optional[Union[IPv4Address, IPv6Address]]: """Convert the bytes and scope to an IP address object.""" base_address = cached_ip_addresses_wrapper(address) if base_address is not None and base_address.is_link_local: # Avoid expensive __format__ call by using PyUnicode_Join return cached_ip_addresses_wrapper("".join((str(base_address), "%", str(scope)))) return base_address def str_without_scope_id(addr: Union[IPv4Address, IPv6Address]) -> str: """Return the string representation of the address without the scope id.""" if IPADDRESS_SUPPORTS_SCOPE_ID and addr.version == 6: address_str = str(addr) return address_str.partition('%')[0] return str(addr) __all__ = ( "cached_ip_addresses", "get_ip_address_object_from_record", "ip_bytes_and_scope_to_address", "str_without_scope_id", ) 07070100000056000081A40000000000000000000000016619D4CC00001B10000000000000000000000000000000000000003400000000python-zeroconf-0.132.2/src/zeroconf/_utils/name.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from functools import lru_cache from typing import Set from .._exceptions import BadTypeInNameException from ..const import ( _HAS_A_TO_Z, _HAS_ASCII_CONTROL_CHARS, _HAS_ONLY_A_TO_Z_NUM_HYPHEN, _HAS_ONLY_A_TO_Z_NUM_HYPHEN_UNDERSCORE, _LOCAL_TRAILER, _NONTCP_PROTOCOL_LOCAL_TRAILER, _TCP_PROTOCOL_LOCAL_TRAILER, ) @lru_cache(maxsize=512) def service_type_name(type_: str, *, strict: bool = True) -> str: # pylint: disable=too-many-branches """ Validate a fully qualified service name, instance or subtype. [rfc6763] Returns fully qualified service name. Domain names used by mDNS-SD take the following forms: <sn> . <_tcp|_udp> . local. <Instance> . <sn> . <_tcp|_udp> . local. <sub>._sub . <sn> . <_tcp|_udp> . local. 1) must end with 'local.' This is true because we are implementing mDNS and since the 'm' means multi-cast, the 'local.' domain is mandatory. 2) local is preceded with either '_udp.' or '_tcp.' unless strict is False 3) service name <sn> precedes <_tcp|_udp> unless strict is False The rules for Service Names [RFC6335] state that they may be no more than fifteen characters long (not counting the mandatory underscore), consisting of only letters, digits, and hyphens, must begin and end with a letter or digit, must not contain consecutive hyphens, and must contain at least one letter. The instance name <Instance> and sub type <sub> may be up to 63 bytes. The portion of the Service Instance Name is a user- friendly name consisting of arbitrary Net-Unicode text [RFC5198]. It MUST NOT contain ASCII control characters (byte values 0x00-0x1F and 0x7F) [RFC20] but otherwise is allowed to contain any characters, without restriction, including spaces, uppercase, lowercase, punctuation -- including dots -- accented characters, non-Roman text, and anything else that may be represented using Net-Unicode. :param type_: Type, SubType or service name to validate :return: fully qualified service name (eg: _http._tcp.local.) """ if len(type_) > 256: # https://datatracker.ietf.org/doc/html/rfc6763#section-7.2 raise BadTypeInNameException("Full name (%s) must be > 256 bytes" % type_) if type_.endswith((_TCP_PROTOCOL_LOCAL_TRAILER, _NONTCP_PROTOCOL_LOCAL_TRAILER)): remaining = type_[: -len(_TCP_PROTOCOL_LOCAL_TRAILER)].split('.') trailer = type_[-len(_TCP_PROTOCOL_LOCAL_TRAILER) :] has_protocol = True elif strict: raise BadTypeInNameException( "Type '%s' must end with '%s' or '%s'" % (type_, _TCP_PROTOCOL_LOCAL_TRAILER, _NONTCP_PROTOCOL_LOCAL_TRAILER) ) elif type_.endswith(_LOCAL_TRAILER): remaining = type_[: -len(_LOCAL_TRAILER)].split('.') trailer = type_[-len(_LOCAL_TRAILER) + 1 :] has_protocol = False else: raise BadTypeInNameException(f"Type '{type_}' must end with '{_LOCAL_TRAILER}'") if strict or has_protocol: service_name = remaining.pop() if not service_name: raise BadTypeInNameException("No Service name found") if len(remaining) == 1 and len(remaining[0]) == 0: raise BadTypeInNameException("Type '%s' must not start with '.'" % type_) if service_name[0] != '_': raise BadTypeInNameException("Service name (%s) must start with '_'" % service_name) test_service_name = service_name[1:] if strict and len(test_service_name) > 15: # https://datatracker.ietf.org/doc/html/rfc6763#section-7.2 raise BadTypeInNameException("Service name (%s) must be <= 15 bytes" % test_service_name) if '--' in test_service_name: raise BadTypeInNameException("Service name (%s) must not contain '--'" % test_service_name) if '-' in (test_service_name[0], test_service_name[-1]): raise BadTypeInNameException( "Service name (%s) may not start or end with '-'" % test_service_name ) if not _HAS_A_TO_Z.search(test_service_name): raise BadTypeInNameException( "Service name (%s) must contain at least one letter (eg: 'A-Z')" % test_service_name ) allowed_characters_re = ( _HAS_ONLY_A_TO_Z_NUM_HYPHEN if strict else _HAS_ONLY_A_TO_Z_NUM_HYPHEN_UNDERSCORE ) if not allowed_characters_re.search(test_service_name): raise BadTypeInNameException( "Service name (%s) must contain only these characters: " "A-Z, a-z, 0-9, hyphen ('-')%s" % (test_service_name, "" if strict else ", underscore ('_')") ) else: service_name = '' if remaining and remaining[-1] == '_sub': remaining.pop() if len(remaining) == 0 or len(remaining[0]) == 0: raise BadTypeInNameException("_sub requires a subtype name") if len(remaining) > 1: remaining = ['.'.join(remaining)] if remaining: length = len(remaining[0].encode('utf-8')) if length > 63: raise BadTypeInNameException("Too long: '%s'" % remaining[0]) if _HAS_ASCII_CONTROL_CHARS.search(remaining[0]): raise BadTypeInNameException( "Ascii control character 0x00-0x1F and 0x7F illegal in '%s'" % remaining[0] ) return service_name + trailer def possible_types(name: str) -> Set[str]: """Build a set of all possible types from a fully qualified name.""" labels = name.split('.') label_count = len(labels) types = set() for count in range(label_count): parts = labels[label_count - count - 4 :] if not parts[0].startswith('_'): break types.add('.'.join(parts)) return types cached_possible_types = lru_cache(maxsize=256)(possible_types) 07070100000057000081A40000000000000000000000016619D4CC00003B94000000000000000000000000000000000000003300000000python-zeroconf-0.132.2/src/zeroconf/_utils/net.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import enum import errno import ipaddress import socket import struct import sys from typing import Any, List, Optional, Sequence, Tuple, Union, cast import ifaddr from .._logger import log from ..const import _IPPROTO_IPV6, _MDNS_ADDR, _MDNS_ADDR6, _MDNS_PORT @enum.unique class InterfaceChoice(enum.Enum): Default = 1 All = 2 InterfacesType = Union[Sequence[Union[str, int, Tuple[Tuple[str, int, int], int]]], InterfaceChoice] @enum.unique class ServiceStateChange(enum.Enum): Added = 1 Removed = 2 Updated = 3 @enum.unique class IPVersion(enum.Enum): V4Only = 1 V6Only = 2 All = 3 # utility functions def _is_v6_address(addr: bytes) -> bool: return len(addr) == 16 def _encode_address(address: str) -> bytes: is_ipv6 = ':' in address address_family = socket.AF_INET6 if is_ipv6 else socket.AF_INET return socket.inet_pton(address_family, address) def get_all_addresses() -> List[str]: return list({addr.ip for iface in ifaddr.get_adapters() for addr in iface.ips if addr.is_IPv4}) def get_all_addresses_v6() -> List[Tuple[Tuple[str, int, int], int]]: # IPv6 multicast uses positive indexes for interfaces # TODO: What about multi-address interfaces? return list( {(addr.ip, iface.index) for iface in ifaddr.get_adapters() for addr in iface.ips if addr.is_IPv6} ) def ip6_to_address_and_index(adapters: List[Any], ip: str) -> Tuple[Tuple[str, int, int], int]: if '%' in ip: ip = ip[: ip.index('%')] # Strip scope_id. ipaddr = ipaddress.ip_address(ip) for adapter in adapters: for adapter_ip in adapter.ips: # IPv6 addresses are represented as tuples if isinstance(adapter_ip.ip, tuple) and ipaddress.ip_address(adapter_ip.ip[0]) == ipaddr: return (cast(Tuple[str, int, int], adapter_ip.ip), cast(int, adapter.index)) raise RuntimeError('No adapter found for IP address %s' % ip) def interface_index_to_ip6_address(adapters: List[Any], index: int) -> Tuple[str, int, int]: for adapter in adapters: if adapter.index == index: for adapter_ip in adapter.ips: # IPv6 addresses are represented as tuples if isinstance(adapter_ip.ip, tuple): return cast(Tuple[str, int, int], adapter_ip.ip) raise RuntimeError('No adapter found for index %s' % index) def ip6_addresses_to_indexes( interfaces: Sequence[Union[str, int, Tuple[Tuple[str, int, int], int]]] ) -> List[Tuple[Tuple[str, int, int], int]]: """Convert IPv6 interface addresses to interface indexes. IPv4 addresses are ignored. :param interfaces: List of IP addresses and indexes. :returns: List of indexes. """ result = [] adapters = ifaddr.get_adapters() for iface in interfaces: if isinstance(iface, int): result.append((interface_index_to_ip6_address(adapters, iface), iface)) elif isinstance(iface, str) and ipaddress.ip_address(iface).version == 6: result.append(ip6_to_address_and_index(adapters, iface)) return result def normalize_interface_choice( choice: InterfacesType, ip_version: IPVersion = IPVersion.V4Only ) -> List[Union[str, Tuple[Tuple[str, int, int], int]]]: """Convert the interfaces choice into internal representation. :param choice: `InterfaceChoice` or list of interface addresses or indexes (IPv6 only). :param ip_address: IP version to use (ignored if `choice` is a list). :returns: List of IP addresses (for IPv4) and indexes (for IPv6). """ result: List[Union[str, Tuple[Tuple[str, int, int], int]]] = [] if choice is InterfaceChoice.Default: if ip_version != IPVersion.V4Only: # IPv6 multicast uses interface 0 to mean the default result.append((('', 0, 0), 0)) if ip_version != IPVersion.V6Only: result.append('0.0.0.0') elif choice is InterfaceChoice.All: if ip_version != IPVersion.V4Only: result.extend(get_all_addresses_v6()) if ip_version != IPVersion.V6Only: result.extend(get_all_addresses()) if not result: raise RuntimeError( 'No interfaces to listen on, check that any interfaces have IP version %s' % ip_version ) elif isinstance(choice, list): # First, take IPv4 addresses. result = [i for i in choice if isinstance(i, str) and ipaddress.ip_address(i).version == 4] # Unlike IP_ADD_MEMBERSHIP, IPV6_JOIN_GROUP requires interface indexes. result += ip6_addresses_to_indexes(choice) else: raise TypeError("choice must be a list or InterfaceChoice, got %r" % choice) return result def disable_ipv6_only_or_raise(s: socket.socket) -> None: """Make V6 sockets work for both V4 and V6 (required for Windows).""" try: s.setsockopt(_IPPROTO_IPV6, socket.IPV6_V6ONLY, False) except OSError: log.error('Support for dual V4-V6 sockets is not present, use IPVersion.V4 or IPVersion.V6') raise def set_so_reuseport_if_available(s: socket.socket) -> None: """Set SO_REUSEADDR on a socket if available.""" # SO_REUSEADDR should be equivalent to SO_REUSEPORT for # multicast UDP sockets (p 731, "TCP/IP Illustrated, # Volume 2"), but some BSD-derived systems require # SO_REUSEPORT to be specified explicitly. Also, not all # versions of Python have SO_REUSEPORT available. # Catch OSError and socket.error for kernel versions <3.9 because lacking # SO_REUSEPORT support. if not hasattr(socket, 'SO_REUSEPORT'): return try: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # pylint: disable=no-member except OSError as err: if err.errno != errno.ENOPROTOOPT: raise def set_mdns_port_socket_options_for_ip_version( s: socket.socket, bind_addr: Union[Tuple[str], Tuple[str, int, int]], ip_version: IPVersion ) -> None: """Set ttl/hops and loop for mdns port.""" if ip_version != IPVersion.V6Only: ttl = struct.pack(b'B', 255) loop = struct.pack(b'B', 1) # OpenBSD needs the ttl and loop values for the IP_MULTICAST_TTL and # IP_MULTICAST_LOOP socket options as an unsigned char. try: s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop) except OSError as e: if bind_addr[0] != '' or get_errno(e) != errno.EINVAL: # Fails to set on MacOS raise if ip_version != IPVersion.V4Only: # However, char doesn't work here (at least on Linux) s.setsockopt(_IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, 255) s.setsockopt(_IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, True) def new_socket( bind_addr: Union[Tuple[str], Tuple[str, int, int]], port: int = _MDNS_PORT, ip_version: IPVersion = IPVersion.V4Only, apple_p2p: bool = False, ) -> Optional[socket.socket]: log.debug( 'Creating new socket with port %s, ip_version %s, apple_p2p %s and bind_addr %r', port, ip_version, apple_p2p, bind_addr, ) socket_family = socket.AF_INET if ip_version == IPVersion.V4Only else socket.AF_INET6 s = socket.socket(socket_family, socket.SOCK_DGRAM) if ip_version == IPVersion.All: disable_ipv6_only_or_raise(s) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) set_so_reuseport_if_available(s) if port == _MDNS_PORT: set_mdns_port_socket_options_for_ip_version(s, bind_addr, ip_version) if apple_p2p: # SO_RECV_ANYIF = 0x1104 # https://opensource.apple.com/source/xnu/xnu-4570.41.2/bsd/sys/socket.h s.setsockopt(socket.SOL_SOCKET, 0x1104, 1) bind_tup = (bind_addr[0], port, *bind_addr[1:]) try: s.bind(bind_tup) except OSError as ex: if ex.errno == errno.EADDRNOTAVAIL: log.warning( 'Address not available when binding to %s, ' 'it is expected to happen on some systems', bind_tup, ) return None raise log.debug('Created socket %s', s) return s def add_multicast_member( listen_socket: socket.socket, interface: Union[str, Tuple[Tuple[str, int, int], int]], ) -> bool: # This is based on assumptions in normalize_interface_choice is_v6 = isinstance(interface, tuple) err_einval = {errno.EINVAL} if sys.platform == 'win32': # No WSAEINVAL definition in typeshed err_einval |= {cast(Any, errno).WSAEINVAL} # pylint: disable=no-member log.debug('Adding %r (socket %d) to multicast group', interface, listen_socket.fileno()) try: if is_v6: try: mdns_addr6_bytes = socket.inet_pton(socket.AF_INET6, _MDNS_ADDR6) except OSError: log.info( 'Unable to translate IPv6 address when adding %s to multicast group, ' 'this can happen if IPv6 is disabled on the system', interface, ) return False iface_bin = struct.pack('@I', cast(int, interface[1])) _value = mdns_addr6_bytes + iface_bin listen_socket.setsockopt(_IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, _value) else: _value = socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(cast(str, interface)) listen_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, _value) except OSError as e: _errno = get_errno(e) if _errno == errno.EADDRINUSE: log.info( 'Address in use when adding %s to multicast group, ' 'it is expected to happen on some systems', interface, ) return False if _errno == errno.EADDRNOTAVAIL: log.info( 'Address not available when adding %s to multicast ' 'group, it is expected to happen on some systems', interface, ) return False if _errno in err_einval: log.info('Interface of %s does not support multicast, ' 'it is expected in WSL', interface) return False if _errno == errno.ENOPROTOOPT: log.info( 'Failed to set socket option on %s, this can happen if ' 'the network adapter is in a disconnected state', interface, ) return False if is_v6 and _errno == errno.ENODEV: log.info( 'Address in use when adding %s to multicast group, ' 'it is expected to happen when the device does not have ipv6', interface, ) return False raise return True def new_respond_socket( interface: Union[str, Tuple[Tuple[str, int, int], int]], apple_p2p: bool = False, ) -> Optional[socket.socket]: is_v6 = isinstance(interface, tuple) respond_socket = new_socket( ip_version=(IPVersion.V6Only if is_v6 else IPVersion.V4Only), apple_p2p=apple_p2p, bind_addr=cast(Tuple[Tuple[str, int, int], int], interface)[0] if is_v6 else (cast(str, interface),), ) if not respond_socket: return None log.debug('Configuring socket %s with multicast interface %s', respond_socket, interface) if is_v6: iface_bin = struct.pack('@I', cast(int, interface[1])) respond_socket.setsockopt(_IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, iface_bin) else: respond_socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(cast(str, interface)) ) return respond_socket def create_sockets( interfaces: InterfacesType = InterfaceChoice.All, unicast: bool = False, ip_version: IPVersion = IPVersion.V4Only, apple_p2p: bool = False, ) -> Tuple[Optional[socket.socket], List[socket.socket]]: if unicast: listen_socket = None else: listen_socket = new_socket(ip_version=ip_version, apple_p2p=apple_p2p, bind_addr=('',)) normalized_interfaces = normalize_interface_choice(interfaces, ip_version) # If we are using InterfaceChoice.Default we can use # a single socket to listen and respond. if not unicast and interfaces is InterfaceChoice.Default: for i in normalized_interfaces: add_multicast_member(cast(socket.socket, listen_socket), i) return listen_socket, [cast(socket.socket, listen_socket)] respond_sockets = [] for i in normalized_interfaces: if not unicast: if add_multicast_member(cast(socket.socket, listen_socket), i): respond_socket = new_respond_socket(i, apple_p2p=apple_p2p) else: respond_socket = None else: respond_socket = new_socket( port=0, ip_version=ip_version, apple_p2p=apple_p2p, bind_addr=i[0] if isinstance(i, tuple) else (i,), ) if respond_socket is not None: respond_sockets.append(respond_socket) return listen_socket, respond_sockets def get_errno(e: Exception) -> int: assert isinstance(e, socket.error) return cast(int, e.args[0]) def can_send_to(ipv6_socket: bool, address: str) -> bool: """Check if the address type matches the socket type. This function does not validate if the address is a valid ipv6 or ipv4 address. """ return ":" in address if ipv6_socket else ":" not in address def autodetect_ip_version(interfaces: InterfacesType) -> IPVersion: """Auto detect the IP version when it is not provided.""" if isinstance(interfaces, list): has_v6 = any( isinstance(i, int) or (isinstance(i, str) and ipaddress.ip_address(i).version == 6) for i in interfaces ) has_v4 = any(isinstance(i, str) and ipaddress.ip_address(i).version == 4 for i in interfaces) if has_v4 and has_v6: return IPVersion.All if has_v6: return IPVersion.V6Only return IPVersion.V4Only 07070100000058000081A40000000000000000000000016619D4CC0000004C000000000000000000000000000000000000003500000000python-zeroconf-0.132.2/src/zeroconf/_utils/time.pxd cpdef double current_time_millis() cpdef millis_to_seconds(double millis) 07070100000059000081A40000000000000000000000016619D4CC0000056E000000000000000000000000000000000000003400000000python-zeroconf-0.132.2/src/zeroconf/_utils/time.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import time _float = float def current_time_millis() -> _float: """Current time in milliseconds. The current implemention uses `time.monotonic` but may change in the future. The design requires the time to match asyncio.loop.time() """ return time.monotonic() * 1000 def millis_to_seconds(millis: _float) -> _float: """Convert milliseconds to seconds.""" return millis / 1000.0 0707010000005A000081A40000000000000000000000016619D4CC00002BB2000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/src/zeroconf/asyncio.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import contextlib from types import TracebackType # noqa # used in type hints from typing import Awaitable, Callable, Dict, List, Optional, Tuple, Type, Union from ._core import Zeroconf from ._dns import DNSQuestionType from ._services import ServiceListener from ._services.browser import _ServiceBrowserBase from ._services.info import AsyncServiceInfo, ServiceInfo from ._services.types import ZeroconfServiceTypes from ._utils.net import InterfaceChoice, InterfacesType, IPVersion from .const import _BROWSER_TIME, _MDNS_PORT, _SERVICE_TYPE_ENUMERATION_NAME __all__ = [ "AsyncZeroconf", "AsyncServiceInfo", "AsyncServiceBrowser", "AsyncZeroconfServiceTypes", ] class AsyncServiceBrowser(_ServiceBrowserBase): """Used to browse for a service for specific type(s). Constructor parameters are as follows: * `zc`: A Zeroconf instance * `type_`: fully qualified service type name * `handler`: ServiceListener or Callable that knows how to process ServiceStateChange events * `listener`: ServiceListener * `addr`: address to send queries (will default to multicast) * `port`: port to send queries (will default to mdns 5353) * `delay`: The initial delay between answering questions * `question_type`: The type of questions to ask (DNSQuestionType.QM or DNSQuestionType.QU) The listener object will have its add_service() and remove_service() methods called when this browser discovers changes in the services availability. """ def __init__( self, zeroconf: 'Zeroconf', type_: Union[str, list], handlers: Optional[Union[ServiceListener, List[Callable[..., None]]]] = None, listener: Optional[ServiceListener] = None, addr: Optional[str] = None, port: int = _MDNS_PORT, delay: int = _BROWSER_TIME, question_type: Optional[DNSQuestionType] = None, ) -> None: super().__init__(zeroconf, type_, handlers, listener, addr, port, delay, question_type) self._async_start() async def async_cancel(self) -> None: """Cancel the browser.""" self._async_cancel() async def __aenter__(self) -> 'AsyncServiceBrowser': return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: await self.async_cancel() return None class AsyncZeroconfServiceTypes(ZeroconfServiceTypes): """An async version of ZeroconfServiceTypes.""" @classmethod async def async_find( cls, aiozc: Optional['AsyncZeroconf'] = None, timeout: Union[int, float] = 5, interfaces: InterfacesType = InterfaceChoice.All, ip_version: Optional[IPVersion] = None, ) -> Tuple[str, ...]: """ Return all of the advertised services on any local networks. :param aiozc: AsyncZeroconf() instance. Pass in if already have an instance running or if non-default interfaces are needed :param timeout: seconds to wait for any responses :param interfaces: interfaces to listen on. :param ip_version: IP protocol version to use. :return: tuple of service type strings """ local_zc = aiozc or AsyncZeroconf(interfaces=interfaces, ip_version=ip_version) listener = cls() async_browser = AsyncServiceBrowser( local_zc.zeroconf, _SERVICE_TYPE_ENUMERATION_NAME, listener=listener ) # wait for responses await asyncio.sleep(timeout) await async_browser.async_cancel() # close down anything we opened if aiozc is None: await local_zc.async_close() return tuple(sorted(listener.found_services)) class AsyncZeroconf: """Implementation of Zeroconf Multicast DNS Service Discovery Supports registration, unregistration, queries and browsing. The async version is currently a wrapper around Zeroconf which is now also async. It is expected that an asyncio event loop is already running before creating the AsyncZeroconf object. """ def __init__( self, interfaces: InterfacesType = InterfaceChoice.All, unicast: bool = False, ip_version: Optional[IPVersion] = None, apple_p2p: bool = False, zc: Optional[Zeroconf] = None, ) -> None: """Creates an instance of the Zeroconf class, establishing multicast communications, and listening. :param interfaces: :class:`InterfaceChoice` or a list of IP addresses (IPv4 and IPv6) and interface indexes (IPv6 only). IPv6 notes for non-POSIX systems: * `InterfaceChoice.All` is an alias for `InterfaceChoice.Default` on Python versions before 3.8. Also listening on loopback (``::1``) doesn't work, use a real address. :param ip_version: IP versions to support. If `choice` is a list, the default is detected from it. Otherwise defaults to V4 only for backward compatibility. :param apple_p2p: use AWDL interface (only macOS) """ self.zeroconf = zc or Zeroconf( interfaces=interfaces, unicast=unicast, ip_version=ip_version, apple_p2p=apple_p2p, ) self.async_browsers: Dict[ServiceListener, AsyncServiceBrowser] = {} async def async_register_service( self, info: ServiceInfo, ttl: Optional[int] = None, allow_name_change: bool = False, cooperating_responders: bool = False, strict: bool = True, ) -> Awaitable: """Registers service information to the network with a default TTL. Zeroconf will then respond to requests for information for that service. The name of the service may be changed if needed to make it unique on the network. Additionally multiple cooperating responders can register the same service on the network for resilience (if you want this behavior set `cooperating_responders` to `True`). The service will be broadcast in a task. This task is returned and therefore can be awaited if necessary. """ return await self.zeroconf.async_register_service( info, ttl, allow_name_change, cooperating_responders, strict ) async def async_unregister_all_services(self) -> None: """Unregister all registered services. Unlike async_register_service and async_unregister_service, this method does not return a future and is always expected to be awaited since its only called at shutdown. """ await self.zeroconf.async_unregister_all_services() async def async_unregister_service(self, info: ServiceInfo) -> Awaitable: """Unregister a service. The service will be broadcast in a task. This task is returned and therefore can be awaited if necessary. """ return await self.zeroconf.async_unregister_service(info) async def async_update_service(self, info: ServiceInfo) -> Awaitable: """Registers service information to the network with a default TTL. Zeroconf will then respond to requests for information for that service. The service will be broadcast in a task. This task is returned and therefore can be awaited if necessary. """ return await self.zeroconf.async_update_service(info) async def async_close(self) -> None: """Ends the background threads, and prevent this instance from servicing further queries.""" if not self.zeroconf.done: with contextlib.suppress(asyncio.TimeoutError): await asyncio.wait_for(self.zeroconf.async_wait_for_start(), timeout=1) await self.async_remove_all_service_listeners() await self.async_unregister_all_services() await self.zeroconf._async_close() # pylint: disable=protected-access async def async_get_service_info( self, type_: str, name: str, timeout: int = 3000, question_type: Optional[DNSQuestionType] = None ) -> Optional[AsyncServiceInfo]: """Returns network's service information for a particular name and type, or None if no service matches by the timeout, which defaults to 3 seconds. :param type_: fully qualified service type name :param name: the name of the service :param timeout: milliseconds to wait for a response :param question_type: The type of questions to ask (DNSQuestionType.QM or DNSQuestionType.QU) """ return await self.zeroconf.async_get_service_info(type_, name, timeout, question_type) async def async_add_service_listener(self, type_: str, listener: ServiceListener) -> None: """Adds a listener for a particular service type. This object will then have its add_service and remove_service methods called when services of that type become available and unavailable.""" await self.async_remove_service_listener(listener) self.async_browsers[listener] = AsyncServiceBrowser(self.zeroconf, type_, listener) async def async_remove_service_listener(self, listener: ServiceListener) -> None: """Removes a listener from the set that is currently listening.""" if listener in self.async_browsers: await self.async_browsers[listener].async_cancel() del self.async_browsers[listener] async def async_remove_all_service_listeners(self) -> None: """Removes a listener from the set that is currently listening.""" await asyncio.gather( *(self.async_remove_service_listener(listener) for listener in list(self.async_browsers)) ) async def __aenter__(self) -> 'AsyncZeroconf': return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> Optional[bool]: await self.async_close() return None 0707010000005B000081A40000000000000000000000016619D4CC0000117F000000000000000000000000000000000000002E00000000python-zeroconf-0.132.2/src/zeroconf/const.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import re import socket # Some timing constants _UNREGISTER_TIME = 125 # ms _CHECK_TIME = 175 # ms _REGISTER_TIME = 225 # ms _LISTENER_TIME = 200 # ms _BROWSER_TIME = 10000 # ms _DUPLICATE_PACKET_SUPPRESSION_INTERVAL = 1000 # ms _DUPLICATE_QUESTION_INTERVAL = 999 # ms # Must be 1ms less than _DUPLICATE_PACKET_SUPPRESSION_INTERVAL _CACHE_CLEANUP_INTERVAL = 10 # s _LOADED_SYSTEM_TIMEOUT = 10 # s _STARTUP_TIMEOUT = 9 # s must be lower than _LOADED_SYSTEM_TIMEOUT _ONE_SECOND = 1000 # ms # If the system is loaded or the event # loop was blocked by another task that was doing I/O in the loop # (shouldn't happen but it does in practice) we need to give # a buffer timeout to ensure a coroutine can finish before # the future times out # Some DNS constants _MDNS_ADDR = '224.0.0.251' _MDNS_ADDR6 = 'ff02::fb' _MDNS_PORT = 5353 _DNS_PORT = 53 _DNS_HOST_TTL = 120 # two minute for host records (A, SRV etc) as-per RFC6762 _DNS_OTHER_TTL = 4500 # 75 minutes for non-host records (PTR, TXT etc) as-per RFC6762 # Currently we enforce a minimum TTL for PTR records to avoid # ServiceBrowsers generating excessive queries refresh queries. # Apple uses a 15s minimum TTL, however we do not have the same # level of rate limit and safe guards so we use 1/4 of the recommended value _DNS_PTR_MIN_TTL = _DNS_OTHER_TTL / 4 _DNS_PACKET_HEADER_LEN = 12 _MAX_MSG_TYPICAL = 1460 # unused _MAX_MSG_ABSOLUTE = 8966 _FLAGS_QR_MASK = 0x8000 # query response mask _FLAGS_QR_QUERY = 0x0000 # query _FLAGS_QR_RESPONSE = 0x8000 # response _FLAGS_AA = 0x0400 # Authoritative answer _FLAGS_TC = 0x0200 # Truncated _FLAGS_RD = 0x0100 # Recursion desired _FLAGS_RA = 0x8000 # Recursion available _FLAGS_Z = 0x0040 # Zero _FLAGS_AD = 0x0020 # Authentic data _FLAGS_CD = 0x0010 # Checking disabled _CLASS_IN = 1 _CLASS_CS = 2 _CLASS_CH = 3 _CLASS_HS = 4 _CLASS_NONE = 254 _CLASS_ANY = 255 _CLASS_MASK = 0x7FFF _CLASS_UNIQUE = 0x8000 _CLASS_IN_UNIQUE = _CLASS_IN | _CLASS_UNIQUE _TYPE_A = 1 _TYPE_NS = 2 _TYPE_MD = 3 _TYPE_MF = 4 _TYPE_CNAME = 5 _TYPE_SOA = 6 _TYPE_MB = 7 _TYPE_MG = 8 _TYPE_MR = 9 _TYPE_NULL = 10 _TYPE_WKS = 11 _TYPE_PTR = 12 _TYPE_HINFO = 13 _TYPE_MINFO = 14 _TYPE_MX = 15 _TYPE_TXT = 16 _TYPE_AAAA = 28 _TYPE_SRV = 33 _TYPE_NSEC = 47 _TYPE_ANY = 255 # Mapping constants to names _CLASSES = { _CLASS_IN: "in", _CLASS_CS: "cs", _CLASS_CH: "ch", _CLASS_HS: "hs", _CLASS_NONE: "none", _CLASS_ANY: "any", } _TYPES = { _TYPE_A: "a", _TYPE_NS: "ns", _TYPE_MD: "md", _TYPE_MF: "mf", _TYPE_CNAME: "cname", _TYPE_SOA: "soa", _TYPE_MB: "mb", _TYPE_MG: "mg", _TYPE_MR: "mr", _TYPE_NULL: "null", _TYPE_WKS: "wks", _TYPE_PTR: "ptr", _TYPE_HINFO: "hinfo", _TYPE_MINFO: "minfo", _TYPE_MX: "mx", _TYPE_TXT: "txt", _TYPE_AAAA: "quada", _TYPE_SRV: "srv", _TYPE_ANY: "any", _TYPE_NSEC: "nsec", } _ADDRESS_RECORD_TYPES = {_TYPE_A, _TYPE_AAAA} _HAS_A_TO_Z = re.compile(r'[A-Za-z]') _HAS_ONLY_A_TO_Z_NUM_HYPHEN = re.compile(r'^[A-Za-z0-9\-]+$') _HAS_ONLY_A_TO_Z_NUM_HYPHEN_UNDERSCORE = re.compile(r'^[A-Za-z0-9\-\_]+$') _HAS_ASCII_CONTROL_CHARS = re.compile(r'[\x00-\x1f\x7f]') _EXPIRE_REFRESH_TIME_PERCENT = 75 _LOCAL_TRAILER = '.local.' _TCP_PROTOCOL_LOCAL_TRAILER = '._tcp.local.' _NONTCP_PROTOCOL_LOCAL_TRAILER = '._udp.local.' # https://datatracker.ietf.org/doc/html/rfc6763#section-9 _SERVICE_TYPE_ENUMERATION_NAME = "_services._dns-sd._udp.local." _IPPROTO_IPV6 = socket.IPPROTO_IPV6 0707010000005C000081A40000000000000000000000016619D4CC00000000000000000000000000000000000000000000002E00000000python-zeroconf-0.132.2/src/zeroconf/py.typed0707010000005D000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000001E00000000python-zeroconf-0.132.2/tests0707010000005E000081A40000000000000000000000016619D4CC00000E2C000000000000000000000000000000000000002A00000000python-zeroconf-0.132.2/tests/__init__.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import asyncio import socket import time from functools import lru_cache from typing import List, Optional, Set from unittest import mock import ifaddr from zeroconf import DNSIncoming, DNSQuestion, DNSRecord, Zeroconf from zeroconf._history import QuestionHistory _MONOTONIC_RESOLUTION = time.get_clock_info("monotonic").resolution class QuestionHistoryWithoutSuppression(QuestionHistory): def suppresses(self, question: DNSQuestion, now: float, known_answers: Set[DNSRecord]) -> bool: return False def _inject_responses(zc: Zeroconf, msgs: List[DNSIncoming]) -> None: """Inject a DNSIncoming response.""" assert zc.loop is not None async def _wait_for_response(): for msg in msgs: zc.record_manager.async_updates_from_response(msg) asyncio.run_coroutine_threadsafe(_wait_for_response(), zc.loop).result() def _inject_response(zc: Zeroconf, msg: DNSIncoming) -> None: """Inject a DNSIncoming response.""" _inject_responses(zc, [msg]) def _wait_for_start(zc: Zeroconf) -> None: """Wait for all sockets to be up and running.""" assert zc.loop is not None asyncio.run_coroutine_threadsafe(zc.async_wait_for_start(), zc.loop).result() @lru_cache(maxsize=None) def has_working_ipv6(): """Return True if if the system can bind an IPv6 address.""" if not socket.has_ipv6: return False sock = None try: sock = socket.socket(socket.AF_INET6) sock.bind(('::1', 0)) except Exception: return False finally: if sock: sock.close() for iface in ifaddr.get_adapters(): for addr in iface.ips: if addr.is_IPv6 and iface.index is not None: return True return False def _clear_cache(zc: Zeroconf) -> None: zc.cache.cache.clear() zc.question_history.clear() def time_changed_millis(millis: Optional[float] = None) -> None: """Call all scheduled events for a time.""" loop = asyncio.get_running_loop() loop_time = loop.time() if millis is not None: mock_seconds_into_future = millis / 1000 else: mock_seconds_into_future = loop_time with mock.patch("time.monotonic", return_value=mock_seconds_into_future): for task in list(loop._scheduled): # type: ignore[attr-defined] if not isinstance(task, asyncio.TimerHandle): continue if task.cancelled(): continue future_seconds = task.when() - (loop_time + _MONOTONIC_RESOLUTION) if mock_seconds_into_future >= future_seconds: task._run() task.cancel() 0707010000005F000081A40000000000000000000000016619D4CC00000407000000000000000000000000000000000000002A00000000python-zeroconf-0.132.2/tests/conftest.py#!/usr/bin/env python """ conftest for zeroconf tests. """ import threading from unittest.mock import patch import pytest from zeroconf import _core, const from zeroconf._handlers import query_handler @pytest.fixture(autouse=True) def verify_threads_ended(): """Verify that the threads are not running after the test.""" threads_before = frozenset(threading.enumerate()) yield threads = frozenset(threading.enumerate()) - threads_before assert not threads @pytest.fixture def run_isolated(): """Change the mDNS port to run the test in isolation.""" with patch.object(query_handler, "_MDNS_PORT", 5454), patch.object( _core, "_MDNS_PORT", 5454 ), patch.object(const, "_MDNS_PORT", 5454): yield @pytest.fixture def disable_duplicate_packet_suppression(): """Disable duplicate packet suppress. Some tests run too slowly because of the duplicate packet suppression. """ with patch.object(const, "_DUPLICATE_PACKET_SUPPRESSION_INTERVAL", 0): yield 07070100000060000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002700000000python-zeroconf-0.132.2/tests/services07070100000061000081A40000000000000000000000016619D4CC000003CB000000000000000000000000000000000000003300000000python-zeroconf-0.132.2/tests/services/__init__.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ 07070100000062000081A40000000000000000000000016619D4CC0000E5CD000000000000000000000000000000000000003700000000python-zeroconf-0.132.2/tests/services/test_browser.py#!/usr/bin/env python """ Unit tests for zeroconf._services.browser. """ import asyncio import logging import os import socket import time import unittest from threading import Event from typing import Iterable, List, Set, cast from unittest.mock import patch import pytest import zeroconf as r import zeroconf._services.browser as _services_browser from zeroconf import ( DNSPointer, DNSQuestion, Zeroconf, _engine, const, current_time_millis, millis_to_seconds, ) from zeroconf._services import ServiceStateChange from zeroconf._services.browser import ServiceBrowser, _ScheduledPTRQuery from zeroconf._services.info import ServiceInfo from zeroconf.asyncio import AsyncServiceBrowser, AsyncZeroconf from .. import ( QuestionHistoryWithoutSuppression, _inject_response, _wait_for_start, has_working_ipv6, time_changed_millis, ) log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) def mock_incoming_msg(records: Iterable[r.DNSRecord]) -> r.DNSIncoming: generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) for record in records: generated.add_answer_at_time(record, 0) return r.DNSIncoming(generated.packets()[0]) def test_service_browser_cancel_multiple_times(): """Test we can cancel a ServiceBrowser multiple times before close.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_hap._tcp.local." class MyServiceListener(r.ServiceListener): pass listener = MyServiceListener() browser = r.ServiceBrowser(zc, type_, None, listener) browser.cancel() browser.cancel() browser.cancel() zc.close() def test_service_browser_cancel_context_manager(): """Test we can cancel a ServiceBrowser with it being used as a context manager.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_hap._tcp.local." class MyServiceListener(r.ServiceListener): pass listener = MyServiceListener() browser = r.ServiceBrowser(zc, type_, None, listener) assert cast(bool, browser.done) is False with browser: pass # ensure call_soon_threadsafe in ServiceBrowser.cancel is run assert zc.loop is not None asyncio.run_coroutine_threadsafe(asyncio.sleep(0), zc.loop).result() assert cast(bool, browser.done) is True zc.close() def test_service_browser_cancel_multiple_times_after_close(): """Test we can cancel a ServiceBrowser multiple times after close.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_hap._tcp.local." class MyServiceListener(r.ServiceListener): pass listener = MyServiceListener() browser = r.ServiceBrowser(zc, type_, None, listener) zc.close() browser.cancel() browser.cancel() browser.cancel() def test_service_browser_started_after_zeroconf_closed(): """Test starting a ServiceBrowser after close raises RuntimeError.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_hap._tcp.local." class MyServiceListener(r.ServiceListener): pass listener = MyServiceListener() zc.close() with pytest.raises(RuntimeError): r.ServiceBrowser(zc, type_, None, listener) def test_multiple_instances_running_close(): """Test we can shutdown multiple instances.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) zc2 = Zeroconf(interfaces=['127.0.0.1']) zc3 = Zeroconf(interfaces=['127.0.0.1']) assert zc.loop != zc2.loop assert zc.loop != zc3.loop class MyServiceListener(r.ServiceListener): pass listener = MyServiceListener() zc2.add_service_listener("zca._hap._tcp.local.", listener) zc.close() zc2.remove_service_listener(listener) zc2.close() zc3.close() class TestServiceBrowser(unittest.TestCase): def test_update_record(self): enable_ipv6 = has_working_ipv6() and not os.environ.get('SKIP_IPV6') service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_server = 'ash-1.local.' service_text = b'path=/~matt1/' service_address = '10.0.1.2' service_v6_address = "2001:db8::1" service_v6_second_address = "6001:db8::1" service_added_count = 0 service_removed_count = 0 service_updated_count = 0 service_add_event = Event() service_removed_event = Event() service_updated_event = Event() class MyServiceListener(r.ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal service_added_count service_added_count += 1 service_add_event.set() def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal service_removed_count service_removed_count += 1 service_removed_event.set() def update_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal service_updated_count service_updated_count += 1 service_info = zc.get_service_info(type_, name) assert socket.inet_aton(service_address) in service_info.addresses if enable_ipv6: assert socket.inet_pton( socket.AF_INET6, service_v6_address ) in service_info.addresses_by_version(r.IPVersion.V6Only) assert socket.inet_pton( socket.AF_INET6, service_v6_second_address ) in service_info.addresses_by_version(r.IPVersion.V6Only) assert service_info.text == service_text assert service_info.server.lower() == service_server.lower() service_updated_event.set() def mock_record_update_incoming_msg(service_state_change: r.ServiceStateChange) -> r.DNSIncoming: generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) assert generated.is_response() is True if service_state_change == r.ServiceStateChange.Removed: ttl = 0 else: ttl = 120 generated.add_answer_at_time( r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, service_text ), 0, ) generated.add_answer_at_time( r.DNSService( service_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, ttl, 0, 0, 80, service_server, ), 0, ) # Send the IPv6 address first since we previously # had a bug where the IPv4 would be missing if the # IPv6 was seen first if enable_ipv6: generated.add_answer_at_time( r.DNSAddress( service_server, const._TYPE_AAAA, const._CLASS_IN | const._CLASS_UNIQUE, ttl, socket.inet_pton(socket.AF_INET6, service_v6_address), ), 0, ) generated.add_answer_at_time( r.DNSAddress( service_server, const._TYPE_AAAA, const._CLASS_IN | const._CLASS_UNIQUE, ttl, socket.inet_pton(socket.AF_INET6, service_v6_second_address), ), 0, ) generated.add_answer_at_time( r.DNSAddress( service_server, const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, ttl, socket.inet_aton(service_address), ), 0, ) generated.add_answer_at_time( r.DNSPointer(service_type, const._TYPE_PTR, const._CLASS_IN, ttl, service_name), 0 ) return r.DNSIncoming(generated.packets()[0]) zeroconf = r.Zeroconf(interfaces=['127.0.0.1']) service_browser = r.ServiceBrowser(zeroconf, service_type, listener=MyServiceListener()) try: wait_time = 3 # service added _inject_response(zeroconf, mock_record_update_incoming_msg(r.ServiceStateChange.Added)) service_add_event.wait(wait_time) assert service_added_count == 1 assert service_updated_count == 0 assert service_removed_count == 0 # service SRV updated service_updated_event.clear() service_server = 'ash-2.local.' _inject_response(zeroconf, mock_record_update_incoming_msg(r.ServiceStateChange.Updated)) service_updated_event.wait(wait_time) assert service_added_count == 1 assert service_updated_count == 1 assert service_removed_count == 0 # service TXT updated service_updated_event.clear() service_text = b'path=/~matt2/' _inject_response(zeroconf, mock_record_update_incoming_msg(r.ServiceStateChange.Updated)) service_updated_event.wait(wait_time) assert service_added_count == 1 assert service_updated_count == 2 assert service_removed_count == 0 # service TXT updated - duplicate update should not trigger another service_updated service_updated_event.clear() service_text = b'path=/~matt2/' _inject_response(zeroconf, mock_record_update_incoming_msg(r.ServiceStateChange.Updated)) service_updated_event.wait(wait_time) assert service_added_count == 1 assert service_updated_count == 2 assert service_removed_count == 0 # service A updated service_updated_event.clear() service_address = '10.0.1.3' # Verify we match on uppercase service_server = service_server.upper() _inject_response(zeroconf, mock_record_update_incoming_msg(r.ServiceStateChange.Updated)) service_updated_event.wait(wait_time) assert service_added_count == 1 assert service_updated_count == 3 assert service_removed_count == 0 # service all updated service_updated_event.clear() service_server = 'ash-3.local.' service_text = b'path=/~matt3/' service_address = '10.0.1.3' _inject_response(zeroconf, mock_record_update_incoming_msg(r.ServiceStateChange.Updated)) service_updated_event.wait(wait_time) assert service_added_count == 1 assert service_updated_count == 4 assert service_removed_count == 0 # service removed _inject_response(zeroconf, mock_record_update_incoming_msg(r.ServiceStateChange.Removed)) service_removed_event.wait(wait_time) assert service_added_count == 1 assert service_updated_count == 4 assert service_removed_count == 1 finally: assert len(zeroconf.listeners) == 1 service_browser.cancel() time.sleep(0.2) assert len(zeroconf.listeners) == 0 zeroconf.remove_all_service_listeners() zeroconf.close() class TestServiceBrowserMultipleTypes(unittest.TestCase): def test_update_record(self): service_names = ['name2._type2._tcp.local.', 'name._type._tcp.local.', 'name._type._udp.local'] service_types = ['_type2._tcp.local.', '_type._tcp.local.', '_type._udp.local.'] service_added_count = 0 service_removed_count = 0 service_add_event = Event() service_removed_event = Event() class MyServiceListener(r.ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal service_added_count service_added_count += 1 if service_added_count == 3: service_add_event.set() def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal service_removed_count service_removed_count += 1 if service_removed_count == 3: service_removed_event.set() def mock_record_update_incoming_msg( service_state_change: r.ServiceStateChange, service_type: str, service_name: str, ttl: int ) -> r.DNSIncoming: generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSPointer(service_type, const._TYPE_PTR, const._CLASS_IN, ttl, service_name), 0 ) return r.DNSIncoming(generated.packets()[0]) zeroconf = r.Zeroconf(interfaces=['127.0.0.1']) service_browser = r.ServiceBrowser(zeroconf, service_types, listener=MyServiceListener()) try: wait_time = 3 # all three services added _inject_response( zeroconf, mock_record_update_incoming_msg( r.ServiceStateChange.Added, service_types[0], service_names[0], 120 ), ) _inject_response( zeroconf, mock_record_update_incoming_msg( r.ServiceStateChange.Added, service_types[1], service_names[1], 120 ), ) time.sleep(0.1) called_with_refresh_time_check = False def _mock_get_expiration_time(self, percent): nonlocal called_with_refresh_time_check if percent == const._EXPIRE_REFRESH_TIME_PERCENT: called_with_refresh_time_check = True return 0 return self.created + (percent * self.ttl * 10) # Set an expire time that will force a refresh with patch("zeroconf.DNSRecord.get_expiration_time", new=_mock_get_expiration_time): _inject_response( zeroconf, mock_record_update_incoming_msg( r.ServiceStateChange.Added, service_types[0], service_names[0], 120 ), ) # Add the last record after updating the first one # to ensure the service_add_event only gets set # after the update _inject_response( zeroconf, mock_record_update_incoming_msg( r.ServiceStateChange.Added, service_types[2], service_names[2], 120 ), ) service_add_event.wait(wait_time) assert called_with_refresh_time_check is True assert service_added_count == 3 assert service_removed_count == 0 _inject_response( zeroconf, mock_record_update_incoming_msg( r.ServiceStateChange.Updated, service_types[0], service_names[0], 0 ), ) # all three services removed _inject_response( zeroconf, mock_record_update_incoming_msg( r.ServiceStateChange.Removed, service_types[0], service_names[0], 0 ), ) _inject_response( zeroconf, mock_record_update_incoming_msg( r.ServiceStateChange.Removed, service_types[1], service_names[1], 0 ), ) _inject_response( zeroconf, mock_record_update_incoming_msg( r.ServiceStateChange.Removed, service_types[2], service_names[2], 0 ), ) service_removed_event.wait(wait_time) assert service_added_count == 3 assert service_removed_count == 3 except TypeError: # Cannot be patched with cython as get_expiration_time is immutable pass finally: assert len(zeroconf.listeners) == 1 service_browser.cancel() time.sleep(0.2) assert len(zeroconf.listeners) == 0 zeroconf.remove_all_service_listeners() zeroconf.close() def test_first_query_delay(): """Verify the first query is delayed. https://datatracker.ietf.org/doc/html/rfc6762#section-5.2 """ type_ = "_http._tcp.local." zeroconf_browser = Zeroconf(interfaces=['127.0.0.1']) _wait_for_start(zeroconf_browser) # we are going to patch the zeroconf send to check query transmission old_send = zeroconf_browser.async_send first_query_time = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT): """Sends an outgoing packet.""" nonlocal first_query_time if first_query_time is None: first_query_time = current_time_millis() old_send(out, addr=addr, port=port) # patch the zeroconf send with patch.object(zeroconf_browser, "async_send", send): # dummy service callback def on_service_state_change(zeroconf, service_type, state_change, name): pass start_time = current_time_millis() browser = ServiceBrowser(zeroconf_browser, type_, [on_service_state_change]) time.sleep(millis_to_seconds(_services_browser._FIRST_QUERY_DELAY_RANDOM_INTERVAL[1] + 5)) try: assert ( current_time_millis() - start_time > _services_browser._FIRST_QUERY_DELAY_RANDOM_INTERVAL[0] ) finally: browser.cancel() zeroconf_browser.close() @pytest.mark.asyncio async def test_asking_default_is_asking_qm_questions_after_the_first_qu(): """Verify the service browser's first questions are QU and refresh queries are QM.""" service_added = asyncio.Event() service_removed = asyncio.Event() unexpected_ttl = asyncio.Event() got_query = asyncio.Event() type_ = "_http._tcp.local." registration_name = "xxxyyy.%s" % type_ def on_service_state_change(zeroconf, service_type, state_change, name): if name == registration_name: if state_change is ServiceStateChange.Added: service_added.set() elif state_change is ServiceStateChange.Removed: service_removed.set() aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_browser = aiozc.zeroconf zeroconf_browser.question_history = QuestionHistoryWithoutSuppression() await zeroconf_browser.async_wait_for_start() # we are going to patch the zeroconf send to check packet sizes old_send = zeroconf_browser.async_send expected_ttl = const._DNS_OTHER_TTL questions: List[List[DNSQuestion]] = [] def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" pout = r.DNSIncoming(out.packets()[0]) questions.append(pout.questions) got_query.set() old_send(out, addr=addr, port=port, v6_flow_scope=v6_flow_scope) assert len(zeroconf_browser.engine.protocols) == 2 aio_zeroconf_registrar = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_registrar = aio_zeroconf_registrar.zeroconf await aio_zeroconf_registrar.zeroconf.async_wait_for_start() assert len(zeroconf_registrar.engine.protocols) == 2 # patch the zeroconf send so we can capture what is being sent with patch.object(zeroconf_browser, "async_send", send): service_added = asyncio.Event() service_removed = asyncio.Event() browser = AsyncServiceBrowser(zeroconf_browser, type_, [on_service_state_change]) info = ServiceInfo( type_, registration_name, 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aio_zeroconf_registrar.async_register_service(info) await task loop = asyncio.get_running_loop() try: await asyncio.wait_for(service_added.wait(), 1) assert service_added.is_set() # Make sure the startup queries are sent original_now = loop.time() now_millis = original_now * 1000 for query_count in range(_services_browser.STARTUP_QUERIES): now_millis += (2**query_count) * 1000 time_changed_millis(now_millis) got_query.clear() now_millis = original_now * 1000 assert not unexpected_ttl.is_set() # Move time forward past when the TTL is no longer # fresh (AKA 75% of the TTL) now_millis += (expected_ttl * 1000) * 0.80 time_changed_millis(now_millis) await asyncio.wait_for(got_query.wait(), 1) assert not unexpected_ttl.is_set() assert len(questions) == _services_browser.STARTUP_QUERIES + 1 # The first question should be QU to try to # populate the known answers and limit the impact # of the QM questions that follow. We still # have to ask QM questions for the startup queries # because some devices will not respond to QU assert questions[0][0].unicast is True # The remaining questions should be QM questions for question in questions[1:]: assert question[0].unicast is False # Don't remove service, allow close() to cleanup finally: await aio_zeroconf_registrar.async_close() await asyncio.wait_for(service_removed.wait(), 1) assert service_removed.is_set() await browser.async_cancel() await aiozc.async_close() @pytest.mark.asyncio async def test_ttl_refresh_cancelled_rescue_query(): """Verify seeing a name again cancels the rescue query.""" service_added = asyncio.Event() service_removed = asyncio.Event() unexpected_ttl = asyncio.Event() got_query = asyncio.Event() type_ = "_http._tcp.local." registration_name = "xxxyyy.%s" % type_ def on_service_state_change(zeroconf, service_type, state_change, name): if name == registration_name: if state_change is ServiceStateChange.Added: service_added.set() elif state_change is ServiceStateChange.Removed: service_removed.set() aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_browser = aiozc.zeroconf zeroconf_browser.question_history = QuestionHistoryWithoutSuppression() await zeroconf_browser.async_wait_for_start() # we are going to patch the zeroconf send to check packet sizes old_send = zeroconf_browser.async_send expected_ttl = const._DNS_OTHER_TTL packets = [] def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" pout = r.DNSIncoming(out.packets()[0]) packets.append(pout) got_query.set() old_send(out, addr=addr, port=port, v6_flow_scope=v6_flow_scope) assert len(zeroconf_browser.engine.protocols) == 2 aio_zeroconf_registrar = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_registrar = aio_zeroconf_registrar.zeroconf await aio_zeroconf_registrar.zeroconf.async_wait_for_start() assert len(zeroconf_registrar.engine.protocols) == 2 # patch the zeroconf send so we can capture what is being sent with patch.object(zeroconf_browser, "async_send", send): service_added = asyncio.Event() service_removed = asyncio.Event() browser = AsyncServiceBrowser(zeroconf_browser, type_, [on_service_state_change]) info = ServiceInfo( type_, registration_name, 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aio_zeroconf_registrar.async_register_service(info) await task loop = asyncio.get_running_loop() try: await asyncio.wait_for(service_added.wait(), 1) assert service_added.is_set() # Make sure the startup queries are sent original_now = loop.time() now_millis = original_now * 1000 for query_count in range(_services_browser.STARTUP_QUERIES): now_millis += (2**query_count) * 1000 time_changed_millis(now_millis) now_millis = original_now * 1000 assert not unexpected_ttl.is_set() await asyncio.wait_for(got_query.wait(), 1) got_query.clear() assert len(packets) == _services_browser.STARTUP_QUERIES packets.clear() # Move time forward past when the TTL is no longer # fresh (AKA 75% of the TTL) now_millis += (expected_ttl * 1000) * 0.80 # Inject a response that will reschedule # the rescue query so it does not happen with patch("time.monotonic", return_value=now_millis / 1000): zeroconf_browser.record_manager.async_updates_from_response( mock_incoming_msg([info.dns_pointer()]), ) time_changed_millis(now_millis) await asyncio.sleep(0) # Verify we did not send a rescue query assert not packets # We should still get a rescue query once the rescheduled # query time is reached now_millis += (expected_ttl * 1000) * 0.76 time_changed_millis(now_millis) await asyncio.wait_for(got_query.wait(), 1) assert len(packets) == 1 # Don't remove service, allow close() to cleanup finally: await aio_zeroconf_registrar.async_close() await asyncio.wait_for(service_removed.wait(), 1) assert service_removed.is_set() await browser.async_cancel() await aiozc.async_close() @pytest.mark.asyncio async def test_asking_qm_questions(): """Verify explictly asking QM questions.""" type_ = "_quservice._tcp.local." aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_browser = aiozc.zeroconf await zeroconf_browser.async_wait_for_start() # we are going to patch the zeroconf send to check query transmission old_send = zeroconf_browser.async_send first_outgoing = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT): """Sends an outgoing packet.""" nonlocal first_outgoing if first_outgoing is None: first_outgoing = out old_send(out, addr=addr, port=port) # patch the zeroconf send with patch.object(zeroconf_browser, "async_send", send): # dummy service callback def on_service_state_change(zeroconf, service_type, state_change, name): pass browser = AsyncServiceBrowser( zeroconf_browser, type_, [on_service_state_change], question_type=r.DNSQuestionType.QM ) await asyncio.sleep(millis_to_seconds(_services_browser._FIRST_QUERY_DELAY_RANDOM_INTERVAL[1] + 5)) try: assert first_outgoing.questions[0].unicast is False # type: ignore[union-attr] finally: await browser.async_cancel() await aiozc.async_close() @pytest.mark.asyncio async def test_asking_qu_questions(): """Verify the service browser can ask QU questions.""" type_ = "_quservice._tcp.local." aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_browser = aiozc.zeroconf await zeroconf_browser.async_wait_for_start() # we are going to patch the zeroconf send to check query transmission old_send = zeroconf_browser.async_send first_outgoing = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT): """Sends an outgoing packet.""" nonlocal first_outgoing if first_outgoing is None: first_outgoing = out old_send(out, addr=addr, port=port) # patch the zeroconf send with patch.object(zeroconf_browser, "async_send", send): # dummy service callback def on_service_state_change(zeroconf, service_type, state_change, name): pass browser = AsyncServiceBrowser( zeroconf_browser, type_, [on_service_state_change], question_type=r.DNSQuestionType.QU ) await asyncio.sleep(millis_to_seconds(_services_browser._FIRST_QUERY_DELAY_RANDOM_INTERVAL[1] + 5)) try: assert first_outgoing.questions[0].unicast is True # type: ignore[union-attr] finally: await browser.async_cancel() await aiozc.async_close() def test_legacy_record_update_listener(): """Test a RecordUpdateListener that does not implement update_records.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) with pytest.raises(RuntimeError): r.RecordUpdateListener().update_record( zc, 0, r.DNSRecord('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL) ) updates = [] class LegacyRecordUpdateListener(r.RecordUpdateListener): """A RecordUpdateListener that does not implement update_records.""" def update_record(self, zc: 'Zeroconf', now: float, record: r.DNSRecord) -> None: nonlocal updates updates.append(record) listener = LegacyRecordUpdateListener() zc.add_listener(listener, None) # dummy service callback def on_service_state_change(zeroconf, service_type, state_change, name): pass # start a browser type_ = "_homeassistant._tcp.local." name = "MyTestHome" browser = ServiceBrowser(zc, type_, [on_service_state_change]) info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) zc.register_service(info_service) time.sleep(0.001) browser.cancel() assert len(updates) assert len([isinstance(update, r.DNSPointer) and update.name == type_ for update in updates]) >= 1 zc.remove_listener(listener) # Removing a second time should not throw zc.remove_listener(listener) zc.close() def test_service_browser_is_aware_of_port_changes(): """Test that the ServiceBrowser is aware of port changes.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_hap._tcp.local." registration_name = "xxxyyy.%s" % type_ callbacks = [] # dummy service callback def on_service_state_change(zeroconf, service_type, state_change, name): """Dummy callback.""" nonlocal callbacks if name == registration_name: callbacks.append((service_type, state_change, name)) browser = ServiceBrowser(zc, type_, [on_service_state_change]) desc = {'path': '/~paulsm/'} address_parsed = "10.0.1.2" address = socket.inet_aton(address_parsed) info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address]) _inject_response( zc, mock_incoming_msg([info.dns_pointer(), info.dns_service(), info.dns_text(), *info.dns_addresses()]), ) time.sleep(0.1) assert callbacks == [('_hap._tcp.local.', ServiceStateChange.Added, 'xxxyyy._hap._tcp.local.')] service_info = zc.get_service_info(type_, registration_name) assert service_info is not None assert service_info.port == 80 info.port = 400 info._dns_service_cache = None # we are mutating the record so clear the cache _inject_response( zc, mock_incoming_msg([info.dns_service()]), ) time.sleep(0.1) assert callbacks == [ ('_hap._tcp.local.', ServiceStateChange.Added, 'xxxyyy._hap._tcp.local.'), ('_hap._tcp.local.', ServiceStateChange.Updated, 'xxxyyy._hap._tcp.local.'), ] service_info = zc.get_service_info(type_, registration_name) assert service_info is not None assert service_info.port == 400 browser.cancel() zc.close() def test_service_browser_listeners_update_service(): """Test that the ServiceBrowser ServiceListener that implements update_service.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_hap._tcp.local." registration_name = "xxxyyy.%s" % type_ callbacks = [] class MyServiceListener(r.ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("add", type_, name)) def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("remove", type_, name)) def update_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("update", type_, name)) listener = MyServiceListener() browser = r.ServiceBrowser(zc, type_, None, listener) desc = {'path': '/~paulsm/'} address_parsed = "10.0.1.2" address = socket.inet_aton(address_parsed) info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address]) _inject_response( zc, mock_incoming_msg([info.dns_pointer(), info.dns_service(), info.dns_text(), *info.dns_addresses()]), ) time.sleep(0.2) info._dns_service_cache = None # we are mutating the record so clear the cache info.port = 400 _inject_response( zc, mock_incoming_msg([info.dns_service()]), ) time.sleep(0.2) assert callbacks == [ ('add', type_, registration_name), ('update', type_, registration_name), ] browser.cancel() zc.close() def test_service_browser_listeners_no_update_service(): """Test that the ServiceBrowser ServiceListener that does not implement update_service.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_hap._tcp.local." registration_name = "xxxyyy.%s" % type_ callbacks = [] class MyServiceListener(r.ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("add", type_, name)) def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("remove", type_, name)) listener = MyServiceListener() browser = r.ServiceBrowser(zc, type_, None, listener) desc = {'path': '/~paulsm/'} address_parsed = "10.0.1.2" address = socket.inet_aton(address_parsed) info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address]) _inject_response( zc, mock_incoming_msg([info.dns_pointer(), info.dns_service(), info.dns_text(), *info.dns_addresses()]), ) time.sleep(0.2) info.port = 400 info._dns_service_cache = None # we are mutating the record so clear the cache _inject_response( zc, mock_incoming_msg([info.dns_service()]), ) time.sleep(0.2) assert callbacks == [ ('add', type_, registration_name), ] browser.cancel() zc.close() def test_service_browser_uses_non_strict_names(): """Verify we can look for technically invalid names as we cannot change what others do.""" # dummy service callback def on_service_state_change(zeroconf, service_type, state_change, name): pass zc = r.Zeroconf(interfaces=['127.0.0.1']) browser = ServiceBrowser(zc, ["_tivo-videostream._tcp.local."], [on_service_state_change]) browser.cancel() # Still fail on completely invalid with pytest.raises(r.BadTypeInNameException): browser = ServiceBrowser(zc, ["tivo-videostream._tcp.local."], [on_service_state_change]) zc.close() def test_group_ptr_queries_with_known_answers(): questions_with_known_answers: _services_browser._QuestionWithKnownAnswers = {} now = current_time_millis() for i in range(120): name = f"_hap{i}._tcp._local." questions_with_known_answers[DNSQuestion(name, const._TYPE_PTR, const._CLASS_IN)] = { DNSPointer( name, const._TYPE_PTR, const._CLASS_IN, 4500, f"zoo{counter}.{name}", ) for counter in range(i) } outs = _services_browser.group_ptr_queries_with_known_answers(now, True, questions_with_known_answers) for out in outs: packets = out.packets() # If we generate multiple packets there must # only be one question assert len(packets) == 1 or len(out.questions) == 1 # This test uses asyncio because it needs to access the cache directly # which is not threadsafe @pytest.mark.asyncio async def test_generate_service_query_suppress_duplicate_questions(): """Generate a service query for sending with zeroconf.send.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf now = current_time_millis() name = "_suppresstest._tcp.local." question = r.DNSQuestion(name, const._TYPE_PTR, const._CLASS_IN) answer = r.DNSPointer( name, const._TYPE_PTR, const._CLASS_IN, 10000, f'known-to-other.{name}', ) other_known_answers: Set[r.DNSRecord] = {answer} zc.question_history.add_question_at_time(question, now, other_known_answers) assert zc.question_history.suppresses(question, now, other_known_answers) # The known answer list is different, do not suppress outs = _services_browser.generate_service_query(zc, now, {name}, multicast=True, question_type=None) assert outs zc.cache.async_add_records([answer]) # The known answer list contains all the asked questions in the history # we should suppress outs = _services_browser.generate_service_query(zc, now, {name}, multicast=True, question_type=None) assert not outs # We do not suppress once the question history expires outs = _services_browser.generate_service_query( zc, now + 1000, {name}, multicast=True, question_type=None ) assert outs # We do not suppress QU queries ever outs = _services_browser.generate_service_query(zc, now, {name}, multicast=False, question_type=None) assert outs zc.question_history.async_expire(now + 2000) # No suppression after clearing the history outs = _services_browser.generate_service_query(zc, now, {name}, multicast=True, question_type=None) assert outs # The previous query we just sent is still remembered and # the next one is suppressed outs = _services_browser.generate_service_query(zc, now, {name}, multicast=True, question_type=None) assert not outs await aiozc.async_close() @pytest.mark.asyncio async def test_query_scheduler(): delay = const._BROWSER_TIME types_ = {"_hap._tcp.local.", "_http._tcp.local."} aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.zeroconf.async_wait_for_start() zc = aiozc.zeroconf sends: List[r.DNSIncoming] = [] def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" pout = r.DNSIncoming(out.packets()[0]) sends.append(pout) query_scheduler = _services_browser.QueryScheduler(zc, types_, None, 0, True, delay, (0, 0), None) loop = asyncio.get_running_loop() # patch the zeroconf send so we can capture what is being sent with patch.object(zc, "async_send", send): query_scheduler.start(loop) original_now = loop.time() now_millis = original_now * 1000 for query_count in range(_services_browser.STARTUP_QUERIES): now_millis += (2**query_count) * 1000 time_changed_millis(now_millis) ptr_record = r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, "zoomer._hap._tcp.local.", ) ptr2_record = r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, "disappear._hap._tcp.local.", ) query_scheduler.reschedule_ptr_first_refresh(ptr_record) expected_when_time = ptr_record.get_expiration_time(const._EXPIRE_REFRESH_TIME_PERCENT) expected_expire_time = ptr_record.get_expiration_time(100) ptr_query = _ScheduledPTRQuery( ptr_record.alias, ptr_record.name, int(ptr_record.ttl), expected_expire_time, expected_when_time ) assert query_scheduler._query_heap == [ptr_query] query_scheduler.reschedule_ptr_first_refresh(ptr2_record) expected_when_time = ptr2_record.get_expiration_time(const._EXPIRE_REFRESH_TIME_PERCENT) expected_expire_time = ptr2_record.get_expiration_time(100) ptr2_query = _ScheduledPTRQuery( ptr2_record.alias, ptr2_record.name, int(ptr2_record.ttl), expected_expire_time, expected_when_time, ) assert query_scheduler._query_heap == [ptr_query, ptr2_query] # Simulate PTR one goodbye query_scheduler.cancel_ptr_refresh(ptr_record) ptr_query.cancelled = True assert query_scheduler._query_heap == [ptr_query, ptr2_query] assert query_scheduler._query_heap[0].cancelled is True assert query_scheduler._query_heap[1].cancelled is False # Move time forward past when the TTL is no longer # fresh (AKA 75% of the TTL) now_millis += (ptr2_record.ttl * 1000) * 0.80 time_changed_millis(now_millis) assert len(query_scheduler._query_heap) == 1 first_heap = query_scheduler._query_heap[0] assert first_heap.cancelled is False assert first_heap.alias == ptr2_record.alias # Move time forward past when the record expires now_millis += (ptr2_record.ttl * 1000) * 0.20 time_changed_millis(now_millis) assert len(query_scheduler._query_heap) == 0 await aiozc.async_close() @pytest.mark.asyncio async def test_query_scheduler_rescue_records(): delay = const._BROWSER_TIME types_ = {"_hap._tcp.local.", "_http._tcp.local."} aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.zeroconf.async_wait_for_start() zc = aiozc.zeroconf sends: List[r.DNSIncoming] = [] def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" pout = r.DNSIncoming(out.packets()[0]) sends.append(pout) query_scheduler = _services_browser.QueryScheduler(zc, types_, None, 0, True, delay, (0, 0), None) loop = asyncio.get_running_loop() # patch the zeroconf send so we can capture what is being sent with patch.object(zc, "async_send", send): query_scheduler.start(loop) original_now = loop.time() now_millis = original_now * 1000 for query_count in range(_services_browser.STARTUP_QUERIES): now_millis += (2**query_count) * 1000 time_changed_millis(now_millis) ptr_record = r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, "zoomer._hap._tcp.local.", ) query_scheduler.reschedule_ptr_first_refresh(ptr_record) expected_when_time = ptr_record.get_expiration_time(const._EXPIRE_REFRESH_TIME_PERCENT) expected_expire_time = ptr_record.get_expiration_time(100) ptr_query = _ScheduledPTRQuery( ptr_record.alias, ptr_record.name, int(ptr_record.ttl), expected_expire_time, expected_when_time ) assert query_scheduler._query_heap == [ptr_query] assert query_scheduler._query_heap[0].cancelled is False # Move time forward past when the TTL is no longer # fresh (AKA 75% of the TTL) now_millis += (ptr_record.ttl * 1000) * 0.76 time_changed_millis(now_millis) assert len(query_scheduler._query_heap) == 1 new_when = query_scheduler._query_heap[0].when_millis assert query_scheduler._query_heap[0].cancelled is False assert new_when >= expected_when_time # Move time forward again, but not enough to expire the # record to make sure we try to rescue it now_millis += (ptr_record.ttl * 1000) * 0.11 time_changed_millis(now_millis) assert len(query_scheduler._query_heap) == 1 second_new_when = query_scheduler._query_heap[0].when_millis assert query_scheduler._query_heap[0].cancelled is False assert second_new_when >= new_when # Move time forward again, enough that we will no longer # try to rescue the record now_millis += (ptr_record.ttl * 1000) * 0.11 time_changed_millis(now_millis) assert len(query_scheduler._query_heap) == 0 await aiozc.async_close() def test_service_browser_matching(): """Test that the ServiceBrowser matching does not match partial names.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_http._tcp.local." registration_name = "xxxyyy.%s" % type_ not_match_type_ = "_asustor-looksgood_http._tcp.local." not_match_registration_name = "xxxyyy.%s" % not_match_type_ callbacks = [] class MyServiceListener(r.ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("add", type_, name)) def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("remove", type_, name)) def update_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("update", type_, name)) listener = MyServiceListener() browser = r.ServiceBrowser(zc, type_, None, listener) desc = {'path': '/~paulsm/'} address_parsed = "10.0.1.2" address = socket.inet_aton(address_parsed) info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address]) should_not_match = ServiceInfo( not_match_type_, not_match_registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address] ) _inject_response( zc, mock_incoming_msg([info.dns_pointer(), info.dns_service(), info.dns_text(), *info.dns_addresses()]), ) _inject_response( zc, mock_incoming_msg( [ should_not_match.dns_pointer(), should_not_match.dns_service(), should_not_match.dns_text(), *should_not_match.dns_addresses(), ] ), ) time.sleep(0.2) info.port = 400 info._dns_service_cache = None # we are mutating the record so clear the cache _inject_response( zc, mock_incoming_msg([info.dns_service()]), ) should_not_match.port = 400 _inject_response( zc, mock_incoming_msg([should_not_match.dns_service()]), ) time.sleep(0.2) assert callbacks == [ ('add', type_, registration_name), ('update', type_, registration_name), ] browser.cancel() zc.close() @patch.object(_engine, "_CACHE_CLEANUP_INTERVAL", 0.01) def test_service_browser_expire_callbacks(): """Test that the ServiceBrowser matching does not match partial names.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_old._tcp.local." registration_name = "uniquezip323.%s" % type_ callbacks = [] class MyServiceListener(r.ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("add", type_, name)) def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("remove", type_, name)) def update_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("update", type_, name)) listener = MyServiceListener() browser = r.ServiceBrowser(zc, type_, None, listener) desc = {'path': '/~paul2/'} address_parsed = "10.0.1.3" address = socket.inet_aton(address_parsed) info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "newname-2.local.", host_ttl=1, other_ttl=1, addresses=[address], ) _inject_response( zc, mock_incoming_msg([info.dns_pointer(), info.dns_service(), info.dns_text(), *info.dns_addresses()]), ) # Force the ttl to be 1 second now = current_time_millis() for cache_record in zc.cache.cache.values(): for record in cache_record: record.set_created_ttl(now, 1) time.sleep(0.3) info.port = 400 info._dns_service_cache = None # we are mutating the record so clear the cache _inject_response( zc, mock_incoming_msg([info.dns_service()]), ) for _ in range(10): time.sleep(0.05) if len(callbacks) == 2: break assert callbacks == [ ('add', type_, registration_name), ('update', type_, registration_name), ] for _ in range(25): time.sleep(0.05) if len(callbacks) == 3: break assert callbacks == [ ('add', type_, registration_name), ('update', type_, registration_name), ('remove', type_, registration_name), ] browser.cancel() zc.close() def test_scheduled_ptr_query_dunder_methods(): query75 = _ScheduledPTRQuery("zoomy._hap._tcp.local.", "_hap._tcp.local.", 120, 120, 75) query80 = _ScheduledPTRQuery("zoomy._hap._tcp.local.", "_hap._tcp.local.", 120, 120, 80) query75_2 = _ScheduledPTRQuery("zoomy._hap._tcp.local.", "_hap._tcp.local.", 120, 140, 75) other = object() stringified = str(query75) assert "zoomy._hap._tcp.local." in stringified assert "120" in stringified assert "75" in stringified assert "ScheduledPTRQuery" in stringified assert query75 == query75 assert query75 != query80 assert query75 == query75_2 assert query75 < query80 assert query75 <= query80 assert query80 > query75 assert query80 >= query75 assert query75 != other with pytest.raises(TypeError): query75 < other # type: ignore[operator] with pytest.raises(TypeError): query75 <= other # type: ignore[operator] with pytest.raises(TypeError): query75 > other # type: ignore[operator] with pytest.raises(TypeError): query75 >= other # type: ignore[operator] @pytest.mark.asyncio async def test_close_zeroconf_without_browser_before_start_up_queries(): """Test that we stop sending startup queries if zeroconf is closed out from under the browser.""" service_added = asyncio.Event() type_ = "_http._tcp.local." registration_name = "xxxyyy.%s" % type_ def on_service_state_change(zeroconf, service_type, state_change, name): if name == registration_name: if state_change is ServiceStateChange.Added: service_added.set() aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_browser = aiozc.zeroconf zeroconf_browser.question_history = QuestionHistoryWithoutSuppression() await zeroconf_browser.async_wait_for_start() sends: list[r.DNSIncoming] = [] def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" pout = r.DNSIncoming(out.packets()[0]) sends.append(pout) assert len(zeroconf_browser.engine.protocols) == 2 aio_zeroconf_registrar = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_registrar = aio_zeroconf_registrar.zeroconf await aio_zeroconf_registrar.zeroconf.async_wait_for_start() assert len(zeroconf_registrar.engine.protocols) == 2 # patch the zeroconf send so we can capture what is being sent with patch.object(zeroconf_browser, "async_send", send): service_added = asyncio.Event() browser = AsyncServiceBrowser(zeroconf_browser, type_, [on_service_state_change]) info = ServiceInfo( type_, registration_name, 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aio_zeroconf_registrar.async_register_service(info) await task loop = asyncio.get_running_loop() try: await asyncio.wait_for(service_added.wait(), 1) assert service_added.is_set() await aiozc.async_close() sends.clear() # Make sure the startup queries are sent original_now = loop.time() now_millis = original_now * 1000 for query_count in range(_services_browser.STARTUP_QUERIES): now_millis += (2**query_count) * 1000 time_changed_millis(now_millis) # We should not send any queries after close assert not sends finally: await aio_zeroconf_registrar.async_close() await browser.async_cancel() @pytest.mark.asyncio async def test_close_zeroconf_without_browser_after_start_up_queries(): """Test that we stop sending rescue queries if zeroconf is closed out from under the browser.""" service_added = asyncio.Event() type_ = "_http._tcp.local." registration_name = "xxxyyy.%s" % type_ def on_service_state_change(zeroconf, service_type, state_change, name): if name == registration_name: if state_change is ServiceStateChange.Added: service_added.set() aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_browser = aiozc.zeroconf zeroconf_browser.question_history = QuestionHistoryWithoutSuppression() await zeroconf_browser.async_wait_for_start() sends: list[r.DNSIncoming] = [] def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" pout = r.DNSIncoming(out.packets()[0]) sends.append(pout) assert len(zeroconf_browser.engine.protocols) == 2 aio_zeroconf_registrar = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_registrar = aio_zeroconf_registrar.zeroconf await aio_zeroconf_registrar.zeroconf.async_wait_for_start() assert len(zeroconf_registrar.engine.protocols) == 2 # patch the zeroconf send so we can capture what is being sent with patch.object(zeroconf_browser, "async_send", send): service_added = asyncio.Event() browser = AsyncServiceBrowser(zeroconf_browser, type_, [on_service_state_change]) expected_ttl = const._DNS_OTHER_TTL info = ServiceInfo( type_, registration_name, 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aio_zeroconf_registrar.async_register_service(info) await task loop = asyncio.get_running_loop() try: await asyncio.wait_for(service_added.wait(), 1) assert service_added.is_set() sends.clear() # Make sure the startup queries are sent original_now = loop.time() now_millis = original_now * 1000 for query_count in range(_services_browser.STARTUP_QUERIES): now_millis += (2**query_count) * 1000 time_changed_millis(now_millis) # We should not send any queries after close assert sends await aiozc.async_close() sends.clear() now_millis = original_now * 1000 # Move time forward past when the TTL is no longer # fresh (AKA 75% of the TTL) now_millis += (expected_ttl * 1000) * 0.80 time_changed_millis(now_millis) # We should not send the query after close assert not sends finally: await aio_zeroconf_registrar.async_close() await browser.async_cancel() 07070100000063000081A40000000000000000000000016619D4CC0000E6D6000000000000000000000000000000000000003400000000python-zeroconf-0.132.2/tests/services/test_info.py#!/usr/bin/env python """ Unit tests for zeroconf._services.info. """ import asyncio import logging import os import socket import sys import threading import unittest from ipaddress import ip_address from threading import Event from typing import Iterable, List, Optional from unittest.mock import patch import pytest import zeroconf as r from zeroconf import DNSAddress, RecordUpdate, const from zeroconf._services import info from zeroconf._services.info import ServiceInfo from zeroconf._utils.net import IPVersion from zeroconf.asyncio import AsyncZeroconf from .. import _inject_response, has_working_ipv6 log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) class TestServiceInfo(unittest.TestCase): def test_get_name(self): """Verify the name accessor can strip the type.""" desc = {'path': '/~paulsm/'} service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_server = 'ash-1.local.' service_address = socket.inet_aton("10.0.1.2") info = ServiceInfo( service_type, service_name, 22, 0, 0, desc, service_server, addresses=[service_address] ) assert info.get_name() == "name" def test_service_info_rejects_non_matching_updates(self): """Verify records with the wrong name are rejected.""" zc = r.Zeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_server = 'ash-1.local.' service_address = socket.inet_aton("10.0.1.2") ttl = 120 now = r.current_time_millis() info = ServiceInfo( service_type, service_name, 22, 0, 0, desc, service_server, addresses=[service_address] ) # Verify backwards compatiblity with calling with None info.async_update_records(zc, now, []) # Matching updates info.async_update_records( zc, now, [ RecordUpdate( r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), None, ) ], ) assert info.properties[b"ci"] == b"2" info.async_update_records( zc, now, [ RecordUpdate( r.DNSService( service_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, ttl, 0, 0, 80, 'ASH-2.local.', ), None, ) ], ) assert info.server_key == 'ash-2.local.' assert info.server == 'ASH-2.local.' new_address = socket.inet_aton("10.0.1.3") info.async_update_records( zc, now, [ RecordUpdate( r.DNSAddress( 'ASH-2.local.', const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, ttl, new_address, ), None, ) ], ) assert new_address in info.addresses # Non-matching updates info.async_update_records( zc, now, [ RecordUpdate( r.DNSText( "incorrect.name.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, b'\x04ff=0\x04ci=3\x04sf=0\x0bsh=6fLM5A==', ), None, ) ], ) assert info.properties[b"ci"] == b"2" info.async_update_records( zc, now, [ RecordUpdate( r.DNSService( "incorrect.name.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, ttl, 0, 0, 80, 'ASH-2.local.', ), None, ) ], ) assert info.server_key == 'ash-2.local.' assert info.server == 'ASH-2.local.' new_address = socket.inet_aton("10.0.1.4") info.async_update_records( zc, now, [ RecordUpdate( r.DNSAddress( "incorrect.name.", const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, ttl, new_address, ), None, ) ], ) assert new_address not in info.addresses zc.close() def test_service_info_rejects_expired_records(self): """Verify records that are expired are rejected.""" zc = r.Zeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_server = 'ash-1.local.' service_address = socket.inet_aton("10.0.1.2") ttl = 120 now = r.current_time_millis() info = ServiceInfo( service_type, service_name, 22, 0, 0, desc, service_server, addresses=[service_address] ) # Matching updates info.async_update_records( zc, now, [ RecordUpdate( r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), None, ) ], ) assert info.properties[b"ci"] == b"2" # Expired record expired_record = r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, b'\x04ff=0\x04ci=3\x04sf=0\x0bsh=6fLM5A==', ) expired_record.set_created_ttl(1000, 1) info.async_update_records(zc, now, [RecordUpdate(expired_record, None)]) assert info.properties[b"ci"] == b"2" zc.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_get_info_partial(self): zc = r.Zeroconf(interfaces=['127.0.0.1']) service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_server = 'ash-1.local.' service_text = b'path=/~matt1/' service_address = '10.0.1.2' service_address_v6_ll = 'fe80::52e:c2f2:bc5f:e9c6' service_scope_id = 12 service_info = None send_event = Event() service_info_event = Event() last_sent: Optional[r.DNSOutgoing] = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" nonlocal last_sent last_sent = out send_event.set() # patch the zeroconf send with patch.object(zc, "async_send", send): def mock_incoming_msg(records: Iterable[r.DNSRecord]) -> r.DNSIncoming: generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) for record in records: generated.add_answer_at_time(record, 0) return r.DNSIncoming(generated.packets()[0]) def get_service_info_helper(zc, type, name): nonlocal service_info service_info = zc.get_service_info(type, name) service_info_event.set() try: ttl = 120 helper_thread = threading.Thread( target=get_service_info_helper, args=(zc, service_type, service_name) ) helper_thread.start() wait_time = 1 # Expect query for SRV, TXT, A, AAAA send_event.wait(wait_time) assert last_sent is not None assert len(last_sent.questions) == 4 assert r.DNSQuestion(service_name, const._TYPE_SRV, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_TXT, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_A, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_AAAA, const._CLASS_IN) in last_sent.questions assert service_info is None # Expect query for SRV, A, AAAA last_sent = None send_event.clear() _inject_response( zc, mock_incoming_msg( [ r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, service_text, ) ] ), ) send_event.wait(wait_time) assert last_sent is not None assert len(last_sent.questions) == 3 # type: ignore[unreachable] assert r.DNSQuestion(service_name, const._TYPE_SRV, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_A, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_AAAA, const._CLASS_IN) in last_sent.questions assert service_info is None # Expect query for A, AAAA last_sent = None send_event.clear() _inject_response( zc, mock_incoming_msg( [ r.DNSService( service_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, ttl, 0, 0, 80, service_server, ) ] ), ) send_event.wait(wait_time) assert last_sent is not None assert len(last_sent.questions) == 2 assert r.DNSQuestion(service_server, const._TYPE_A, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_server, const._TYPE_AAAA, const._CLASS_IN) in last_sent.questions last_sent = None assert service_info is None # Expect no further queries last_sent = None send_event.clear() _inject_response( zc, mock_incoming_msg( [ r.DNSAddress( service_server, const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, ttl, socket.inet_pton(socket.AF_INET, service_address), ), r.DNSAddress( service_server, const._TYPE_AAAA, const._CLASS_IN | const._CLASS_UNIQUE, ttl, socket.inet_pton(socket.AF_INET6, service_address_v6_ll), scope_id=service_scope_id, ), ] ), ) send_event.wait(wait_time) assert last_sent is None assert service_info is not None finally: helper_thread.join() zc.remove_all_service_listeners() zc.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_get_info_suppressed_by_question_history(self): zc = r.Zeroconf(interfaces=['127.0.0.1']) service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_info = None send_event = Event() service_info_event = Event() last_sent: Optional[r.DNSOutgoing] = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" nonlocal last_sent last_sent = out send_event.set() # patch the zeroconf send with patch.object(zc, "async_send", send): def mock_incoming_msg(records: Iterable[r.DNSRecord]) -> r.DNSIncoming: generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) for record in records: generated.add_answer_at_time(record, 0) return r.DNSIncoming(generated.packets()[0]) def get_service_info_helper(zc, type, name): nonlocal service_info service_info = zc.get_service_info(type, name) service_info_event.set() try: helper_thread = threading.Thread( target=get_service_info_helper, args=(zc, service_type, service_name) ) helper_thread.start() wait_time = (const._LISTENER_TIME + info._AVOID_SYNC_DELAY_RANDOM_INTERVAL[1] + 5) / 1000 # Expect query for SRV, TXT, A, AAAA send_event.wait(wait_time) assert last_sent is not None assert len(last_sent.questions) == 4 assert r.DNSQuestion(service_name, const._TYPE_SRV, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_TXT, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_A, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_AAAA, const._CLASS_IN) in last_sent.questions assert service_info is None # Expect query for SRV only as A, AAAA, and TXT are suppressed # by the question history last_sent = None send_event.clear() for _ in range(3): send_event.wait( wait_time * 0.25 ) # Wait long enough to be inside the question history window now = r.current_time_millis() zc.question_history.add_question_at_time( r.DNSQuestion(service_name, const._TYPE_A, const._CLASS_IN), now, set() ) zc.question_history.add_question_at_time( r.DNSQuestion(service_name, const._TYPE_AAAA, const._CLASS_IN), now, set() ) zc.question_history.add_question_at_time( r.DNSQuestion(service_name, const._TYPE_TXT, const._CLASS_IN), now, set() ) send_event.wait(wait_time * 0.25) assert last_sent is not None assert len(last_sent.questions) == 1 # type: ignore[unreachable] assert r.DNSQuestion(service_name, const._TYPE_SRV, const._CLASS_IN) in last_sent.questions assert service_info is None wait_time = ( const._DUPLICATE_QUESTION_INTERVAL + info._AVOID_SYNC_DELAY_RANDOM_INTERVAL[1] + 5 ) / 1000 # Expect no queries as all are suppressed by the question history last_sent = None send_event.clear() for _ in range(3): send_event.wait( wait_time * 0.25 ) # Wait long enough to be inside the question history window now = r.current_time_millis() zc.question_history.add_question_at_time( r.DNSQuestion(service_name, const._TYPE_A, const._CLASS_IN), now, set() ) zc.question_history.add_question_at_time( r.DNSQuestion(service_name, const._TYPE_AAAA, const._CLASS_IN), now, set() ) zc.question_history.add_question_at_time( r.DNSQuestion(service_name, const._TYPE_TXT, const._CLASS_IN), now, set() ) zc.question_history.add_question_at_time( r.DNSQuestion(service_name, const._TYPE_SRV, const._CLASS_IN), now, set() ) send_event.wait(wait_time * 0.25) # All questions are suppressed so no query should be sent assert last_sent is None assert service_info is None finally: helper_thread.join() zc.remove_all_service_listeners() zc.close() def test_get_info_single(self): zc = r.Zeroconf(interfaces=['127.0.0.1']) service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_server = 'ash-1.local.' service_text = b'path=/~matt1/' service_address = '10.0.1.2' service_info = None send_event = Event() service_info_event = Event() last_sent = None # type: Optional[r.DNSOutgoing] def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" nonlocal last_sent last_sent = out send_event.set() # patch the zeroconf send with patch.object(zc, "async_send", send): def mock_incoming_msg(records: Iterable[r.DNSRecord]) -> r.DNSIncoming: generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) for record in records: generated.add_answer_at_time(record, 0) return r.DNSIncoming(generated.packets()[0]) def get_service_info_helper(zc, type, name): nonlocal service_info service_info = zc.get_service_info(type, name) service_info_event.set() try: ttl = 120 helper_thread = threading.Thread( target=get_service_info_helper, args=(zc, service_type, service_name) ) helper_thread.start() wait_time = 1 # Expext query for SRV, TXT, A, AAAA send_event.wait(wait_time) assert last_sent is not None assert len(last_sent.questions) == 4 assert r.DNSQuestion(service_name, const._TYPE_SRV, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_TXT, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_A, const._CLASS_IN) in last_sent.questions assert r.DNSQuestion(service_name, const._TYPE_AAAA, const._CLASS_IN) in last_sent.questions assert service_info is None # Expext no further queries last_sent = None send_event.clear() _inject_response( zc, mock_incoming_msg( [ r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, service_text, ), r.DNSService( service_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, ttl, 0, 0, 80, service_server, ), r.DNSAddress( service_server, const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, ttl, socket.inet_pton(socket.AF_INET, service_address), ), ] ), ) send_event.wait(wait_time) assert last_sent is None assert service_info is not None finally: helper_thread.join() zc.remove_all_service_listeners() zc.close() def test_service_info_duplicate_properties_txt_records(self): """Verify the first property is always used when there are duplicates in a txt record.""" zc = r.Zeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_server = 'ash-1.local.' service_address = socket.inet_aton("10.0.1.2") ttl = 120 now = r.current_time_millis() info = ServiceInfo( service_type, service_name, 22, 0, 0, desc, service_server, addresses=[service_address] ) info.async_update_records( zc, now, [ r.RecordUpdate( r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==\x04dd=0\x04jl=2\x04qq=0\x0brr=6fLM5A==\x04ci=3', ), None, ) ], ) assert info.properties[b"dd"] == b"0" assert info.properties[b"jl"] == b"2" assert info.properties[b"ci"] == b"2" zc.close() def test_multiple_addresses(): type_ = "_http._tcp.local." registration_name = "xxxyyy.%s" % type_ desc = {'path': '/~paulsm/'} address_parsed = "10.0.1.2" address = socket.inet_aton(address_parsed) # New kwarg way info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address, address]) assert info.addresses == [address, address] assert info.parsed_addresses() == [address_parsed, address_parsed] assert info.parsed_scoped_addresses() == [address_parsed, address_parsed] info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", parsed_addresses=[address_parsed, address_parsed], ) assert info.addresses == [address, address] assert info.parsed_addresses() == [address_parsed, address_parsed] assert info.parsed_scoped_addresses() == [address_parsed, address_parsed] ipaddress_supports_scope_id = sys.version_info >= (3, 9, 0) if has_working_ipv6() and not os.environ.get('SKIP_IPV6'): address_v6_parsed = "2001:db8::1" address_v6 = socket.inet_pton(socket.AF_INET6, address_v6_parsed) address_v6_ll_parsed = "fe80::52e:c2f2:bc5f:e9c6" address_v6_ll_scoped_parsed = "fe80::52e:c2f2:bc5f:e9c6%12" address_v6_ll = socket.inet_pton(socket.AF_INET6, address_v6_ll_parsed) interface_index = 12 infos = [ ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address, address_v6, address_v6_ll], interface_index=interface_index, ), ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", parsed_addresses=[address_parsed, address_v6_parsed, address_v6_ll_parsed], interface_index=interface_index, ), ] for info in infos: assert info.addresses == [address] assert info.addresses_by_version(r.IPVersion.All) == [address, address_v6, address_v6_ll] assert info.ip_addresses_by_version(r.IPVersion.All) == [ ip_address(address), ip_address(address_v6), ip_address(address_v6_ll_scoped_parsed) if ipaddress_supports_scope_id else ip_address(address_v6_ll), ] assert info.addresses_by_version(r.IPVersion.V4Only) == [address] assert info.ip_addresses_by_version(r.IPVersion.V4Only) == [ip_address(address)] assert info.addresses_by_version(r.IPVersion.V6Only) == [address_v6, address_v6_ll] assert info.ip_addresses_by_version(r.IPVersion.V6Only) == [ ip_address(address_v6), ip_address(address_v6_ll_scoped_parsed) if ipaddress_supports_scope_id else ip_address(address_v6_ll), ] assert info.parsed_addresses() == [address_parsed, address_v6_parsed, address_v6_ll_parsed] assert info.parsed_addresses(r.IPVersion.V4Only) == [address_parsed] assert info.parsed_addresses(r.IPVersion.V6Only) == [address_v6_parsed, address_v6_ll_parsed] assert info.parsed_scoped_addresses() == [ address_parsed, address_v6_parsed, address_v6_ll_scoped_parsed if ipaddress_supports_scope_id else address_v6_ll_parsed, ] assert info.parsed_scoped_addresses(r.IPVersion.V4Only) == [address_parsed] assert info.parsed_scoped_addresses(r.IPVersion.V6Only) == [ address_v6_parsed, address_v6_ll_scoped_parsed if ipaddress_supports_scope_id else address_v6_ll_parsed, ] @unittest.skipIf(sys.version_info < (3, 9, 0), 'Requires newer python') def test_scoped_addresses_from_cache(): type_ = "_http._tcp.local." registration_name = f"scoped.{type_}" zeroconf = r.Zeroconf(interfaces=['127.0.0.1']) host = "scoped.local." zeroconf.cache.async_add_records( [ r.DNSPointer( type_, const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, 120, registration_name, ), r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 120, 0, 0, 80, host, ), r.DNSAddress( host, const._TYPE_AAAA, const._CLASS_IN | const._CLASS_UNIQUE, 120, socket.inet_pton(socket.AF_INET6, "fe80::52e:c2f2:bc5f:e9c6"), scope_id=12, ), ] ) # New kwarg way info = ServiceInfo(type_, registration_name) info.load_from_cache(zeroconf) assert info.parsed_scoped_addresses() == ["fe80::52e:c2f2:bc5f:e9c6%12"] assert info.ip_addresses_by_version(r.IPVersion.V6Only) == [ip_address("fe80::52e:c2f2:bc5f:e9c6%12")] zeroconf.close() # This test uses asyncio because it needs to access the cache directly # which is not threadsafe @pytest.mark.asyncio async def test_multiple_a_addresses_newest_address_first(): """Test that info.addresses returns the newest seen address first.""" type_ = "_http._tcp.local." registration_name = "multiarec.%s" % type_ desc = {'path': '/~paulsm/'} aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) cache = aiozc.zeroconf.cache host = "multahost.local." record1 = r.DNSAddress(host, const._TYPE_A, const._CLASS_IN, 1000, b'\x7f\x00\x00\x01') record2 = r.DNSAddress(host, const._TYPE_A, const._CLASS_IN, 1000, b'\x7f\x00\x00\x02') cache.async_add_records([record1, record2]) # New kwarg way info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, host) info.load_from_cache(aiozc.zeroconf) assert info.addresses == [b'\x7f\x00\x00\x02', b'\x7f\x00\x00\x01'] await aiozc.async_close() @pytest.mark.asyncio async def test_invalid_a_addresses(caplog): type_ = "_http._tcp.local." registration_name = "multiarec.%s" % type_ desc = {'path': '/~paulsm/'} aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) cache = aiozc.zeroconf.cache host = "multahost.local." record1 = r.DNSAddress(host, const._TYPE_A, const._CLASS_IN, 1000, b'a') record2 = r.DNSAddress(host, const._TYPE_A, const._CLASS_IN, 1000, b'b') cache.async_add_records([record1, record2]) # New kwarg way info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, host) info.load_from_cache(aiozc.zeroconf) assert not info.addresses assert "Encountered invalid address while processing record" in caplog.text await aiozc.async_close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_filter_address_by_type_from_service_info(): """Verify dns_addresses can filter by ipversion.""" desc = {'path': '/~paulsm/'} type_ = "_homeassistant._tcp.local." name = "MyTestHome" registration_name = f"{name}.{type_}" ipv4 = socket.inet_aton("10.0.1.2") ipv6 = socket.inet_pton(socket.AF_INET6, "2001:db8::1") info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[ipv4, ipv6]) def dns_addresses_to_addresses(dns_address: List[DNSAddress]) -> List[bytes]: return [address.address for address in dns_address] assert dns_addresses_to_addresses(info.dns_addresses()) == [ipv4, ipv6] assert dns_addresses_to_addresses(info.dns_addresses(version=r.IPVersion.All)) == [ipv4, ipv6] assert dns_addresses_to_addresses(info.dns_addresses(version=r.IPVersion.V4Only)) == [ipv4] assert dns_addresses_to_addresses(info.dns_addresses(version=r.IPVersion.V6Only)) == [ipv6] def test_changing_name_updates_serviceinfo_key(): """Verify a name change will adjust the underlying key value.""" type_ = "_homeassistant._tcp.local." name = "MyTestHome" info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) assert info_service.key == "mytesthome._homeassistant._tcp.local." info_service.name = "YourTestHome._homeassistant._tcp.local." assert info_service.key == "yourtesthome._homeassistant._tcp.local." def test_serviceinfo_address_updates(): """Verify adding/removing/setting addresses on ServiceInfo.""" type_ = "_homeassistant._tcp.local." name = "MyTestHome" # Verify addresses and parsed_addresses are mutually exclusive with pytest.raises(TypeError): info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], parsed_addresses=["10.0.1.2"], ) info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) info_service.addresses = [socket.inet_aton("10.0.1.3")] assert info_service.addresses == [socket.inet_aton("10.0.1.3")] def test_serviceinfo_accepts_bytes_or_string_dict(): """Verify a bytes or string dict can be passed to ServiceInfo.""" type_ = "_homeassistant._tcp.local." name = "MyTestHome" addresses = [socket.inet_aton("10.0.1.2")] server_name = "ash-2.local." info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {b'path': b'/~paulsm/'}, server_name, addresses=addresses ) assert info_service.dns_text().text == b'\x0epath=/~paulsm/' info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, server_name, addresses=addresses, ) assert info_service.dns_text().text == b'\x0epath=/~paulsm/' info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {b'path': '/~paulsm/'}, server_name, addresses=addresses, ) assert info_service.dns_text().text == b'\x0epath=/~paulsm/' info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': b'/~paulsm/'}, server_name, addresses=addresses, ) assert info_service.dns_text().text == b'\x0epath=/~paulsm/' def test_asking_qu_questions(): """Verify explictly asking QU questions.""" type_ = "_quservice._tcp.local." zeroconf = r.Zeroconf(interfaces=['127.0.0.1']) # we are going to patch the zeroconf send to check query transmission old_send = zeroconf.async_send first_outgoing = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT): """Sends an outgoing packet.""" nonlocal first_outgoing if first_outgoing is None: first_outgoing = out old_send(out, addr=addr, port=port) # patch the zeroconf send with patch.object(zeroconf, "async_send", send): zeroconf.get_service_info(f"name.{type_}", type_, 500, question_type=r.DNSQuestionType.QU) assert first_outgoing.questions[0].unicast is True # type: ignore[union-attr] zeroconf.close() def test_asking_qm_questions(): """Verify explictly asking QM questions.""" type_ = "_quservice._tcp.local." zeroconf = r.Zeroconf(interfaces=['127.0.0.1']) # we are going to patch the zeroconf send to check query transmission old_send = zeroconf.async_send first_outgoing = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT): """Sends an outgoing packet.""" nonlocal first_outgoing if first_outgoing is None: first_outgoing = out old_send(out, addr=addr, port=port) # patch the zeroconf send with patch.object(zeroconf, "async_send", send): zeroconf.get_service_info(f"name.{type_}", type_, 500, question_type=r.DNSQuestionType.QM) assert first_outgoing.questions[0].unicast is False # type: ignore[union-attr] zeroconf.close() def test_request_timeout(): """Test that the timeout does not throw an exception and finishes close to the actual timeout.""" zeroconf = r.Zeroconf(interfaces=['127.0.0.1']) start_time = r.current_time_millis() assert zeroconf.get_service_info("_notfound.local.", "notthere._notfound.local.") is None end_time = r.current_time_millis() zeroconf.close() # 3000ms for the default timeout # 1000ms for loaded systems + schedule overhead assert (end_time - start_time) < 3000 + 1000 @pytest.mark.asyncio async def test_we_try_four_times_with_random_delay(): """Verify we try four times even with the random delay.""" type_ = "_typethatisnothere._tcp.local." aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) # we are going to patch the zeroconf send to check query transmission request_count = 0 def async_send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT): """Sends an outgoing packet.""" nonlocal request_count request_count += 1 # patch the zeroconf send with patch.object(aiozc.zeroconf, "async_send", async_send): await aiozc.async_get_service_info(f"willnotbefound.{type_}", type_) await aiozc.async_close() assert request_count == 4 @pytest.mark.asyncio async def test_release_wait_when_new_recorded_added(): """Test that async_request returns as soon as new matching records are added to the cache.""" type_ = "_http._tcp.local." registration_name = "multiarec.%s" % type_ desc = {'path': '/~paulsm/'} aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahost.local." # New kwarg way info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, host) task = asyncio.create_task(info.async_request(aiozc.zeroconf, timeout=200)) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSNsec( registration_name, const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, registration_name, [const._TYPE_AAAA], ), 0, ) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x01', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) await aiozc.zeroconf.async_wait_for_start() await asyncio.sleep(0) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) assert await asyncio.wait_for(task, timeout=2) assert info.addresses == [b'\x7f\x00\x00\x01'] await aiozc.async_close() @pytest.mark.asyncio async def test_port_changes_are_seen(): """Test that port changes are seen by async_request.""" type_ = "_http._tcp.local." registration_name = "multiarec.%s" % type_ desc = {'path': '/~paulsm/'} aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahost.local." # New kwarg way generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSNsec( registration_name, const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, registration_name, [const._TYPE_AAAA], ), 0, ) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x01', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) await aiozc.zeroconf.async_wait_for_start() await asyncio.sleep(0) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 90, 90, 81, host, ), 0, ) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name, 80, 10, 10, desc, host) await info.async_request(aiozc.zeroconf, timeout=200) assert info.port == 81 assert info.priority == 90 assert info.weight == 90 await aiozc.async_close() @pytest.mark.asyncio async def test_port_changes_are_seen_with_directed_request(): """Test that port changes are seen by async_request with a directed request.""" type_ = "_http._tcp.local." registration_name = "multiarec.%s" % type_ desc = {'path': '/~paulsm/'} aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahost.local." # New kwarg way generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSNsec( registration_name, const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, registration_name, [const._TYPE_AAAA], ), 0, ) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x01', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) await aiozc.zeroconf.async_wait_for_start() await asyncio.sleep(0) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 90, 90, 81, host, ), 0, ) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name, 80, 10, 10, desc, host) await info.async_request(aiozc.zeroconf, timeout=200, addr="127.0.0.1", port=5353) assert info.port == 81 assert info.priority == 90 assert info.weight == 90 await aiozc.async_close() @pytest.mark.asyncio async def test_ipv4_changes_are_seen(): """Test that ipv4 changes are seen by async_request.""" type_ = "_http._tcp.local." registration_name = "multiaipv4rec.%s" % type_ aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahost.local." # New kwarg way generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSNsec( registration_name, const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, registration_name, [const._TYPE_AAAA], ), 0, ) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x01', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) await aiozc.zeroconf.async_wait_for_start() await asyncio.sleep(0) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) info.load_from_cache(aiozc.zeroconf) assert info.addresses_by_version(IPVersion.V4Only) == [b'\x7f\x00\x00\x01'] generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x02', ), 0, ) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) info.load_from_cache(aiozc.zeroconf) assert info.addresses_by_version(IPVersion.V4Only) == [b'\x7f\x00\x00\x02', b'\x7f\x00\x00\x01'] await info.async_request(aiozc.zeroconf, timeout=200) assert info.addresses_by_version(IPVersion.V4Only) == [b'\x7f\x00\x00\x02', b'\x7f\x00\x00\x01'] await aiozc.async_close() @pytest.mark.asyncio async def test_ipv6_changes_are_seen(): """Test that ipv6 changes are seen by async_request.""" type_ = "_http._tcp.local." registration_name = "multiaipv6rec.%s" % type_ aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahost.local." # New kwarg way generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSNsec( registration_name, const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, registration_name, [const._TYPE_A], ), 0, ) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_AAAA, const._CLASS_IN, 10000, b'\xde\xad\xbe\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) await aiozc.zeroconf.async_wait_for_start() await asyncio.sleep(0) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) info.load_from_cache(aiozc.zeroconf) assert info.addresses_by_version(IPVersion.V6Only) == [ b'\xde\xad\xbe\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ] generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_AAAA, const._CLASS_IN, 10000, b'\x00\xad\xbe\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ), 0, ) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) info.load_from_cache(aiozc.zeroconf) assert info.addresses_by_version(IPVersion.V6Only) == [ b'\x00\xad\xbe\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'\xde\xad\xbe\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ] await info.async_request(aiozc.zeroconf, timeout=200) assert info.addresses_by_version(IPVersion.V6Only) == [ b'\x00\xad\xbe\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'\xde\xad\xbe\xef\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ] await aiozc.async_close() @pytest.mark.asyncio async def test_bad_ip_addresses_ignored_in_cache(): """Test that bad ip address in the cache are ignored async_request.""" type_ = "_http._tcp.local." registration_name = "multiarec.%s" % type_ aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahost.local." # New kwarg way generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x01', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) # Manually add a bad record to the cache aiozc.zeroconf.cache.async_add_records([DNSAddress(host, const._TYPE_A, const._CLASS_IN, 10000, b'\x00')]) await aiozc.zeroconf.async_wait_for_start() await asyncio.sleep(0) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) info.load_from_cache(aiozc.zeroconf) assert info.addresses_by_version(IPVersion.V4Only) == [b'\x7f\x00\x00\x01'] @pytest.mark.asyncio async def test_service_name_change_as_seen_has_ip_in_cache(): """Test that service name changes are seen by async_request when the ip is in the cache.""" type_ = "_http._tcp.local." registration_name = "multiarec.%s" % type_ aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahost.local." # New kwarg way generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSNsec( registration_name, const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, registration_name, [const._TYPE_AAAA], ), 0, ) generated.add_answer_at_time( r.DNSAddress( registration_name, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x01', ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x02', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) await aiozc.zeroconf.async_wait_for_start() await asyncio.sleep(0) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) await info.async_request(aiozc.zeroconf, timeout=200) assert info.addresses_by_version(IPVersion.V4Only) == [] generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) await info.async_request(aiozc.zeroconf, timeout=200) assert info.addresses_by_version(IPVersion.V4Only) == [b'\x7f\x00\x00\x02'] await aiozc.async_close() @pytest.mark.asyncio async def test_service_name_change_as_seen_ip_not_in_cache(): """Test that service name changes are seen by async_request when the ip is not in the cache.""" type_ = "_http._tcp.local." registration_name = "multiarec.%s" % type_ aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahost.local." # New kwarg way generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSNsec( registration_name, const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, registration_name, [const._TYPE_AAAA], ), 0, ) generated.add_answer_at_time( r.DNSAddress( registration_name, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x01', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) await aiozc.zeroconf.async_wait_for_start() await asyncio.sleep(0) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) await info.async_request(aiozc.zeroconf, timeout=200) assert info.addresses_by_version(IPVersion.V4Only) == [] generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x02', ), 0, ) aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) info = ServiceInfo(type_, registration_name) await info.async_request(aiozc.zeroconf, timeout=200) assert info.addresses_by_version(IPVersion.V4Only) == [b'\x7f\x00\x00\x02'] await aiozc.async_close() @pytest.mark.asyncio @patch.object(info, "_LISTENER_TIME", 10000000) async def test_release_wait_when_new_recorded_added_concurrency(): """Test that concurrent async_request returns as soon as new matching records are added to the cache.""" type_ = "_http._tcp.local." registration_name = "multiareccon.%s" % type_ desc = {'path': '/~paulsm/'} aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) host = "multahostcon.local." await aiozc.zeroconf.async_wait_for_start() # New kwarg way info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, host) tasks = [asyncio.create_task(info.async_request(aiozc.zeroconf, timeout=200000)) for _ in range(10)] await asyncio.sleep(0.1) for task in tasks: assert not task.done() generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSNsec( registration_name, const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, registration_name, [const._TYPE_AAAA], ), 0, ) generated.add_answer_at_time( r.DNSService( registration_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, 10000, 0, 0, 80, host, ), 0, ) generated.add_answer_at_time( r.DNSAddress( host, const._TYPE_A, const._CLASS_IN, 10000, b'\x7f\x00\x00\x01', ), 0, ) generated.add_answer_at_time( r.DNSText( registration_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 10000, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) await asyncio.sleep(0) for task in tasks: assert not task.done() aiozc.zeroconf.record_manager.async_updates_from_response(r.DNSIncoming(generated.packets()[0])) _, pending = await asyncio.wait(tasks, timeout=2) assert not pending assert info.addresses == [b'\x7f\x00\x00\x01'] await aiozc.async_close() @pytest.mark.asyncio async def test_service_info_nsec_records(): """Test we can generate nsec records from ServiceInfo.""" type_ = "_http._tcp.local." registration_name = "multiareccon.%s" % type_ desc = {'path': '/~paulsm/'} host = "multahostcon.local." info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, host) nsec_record = info.dns_nsec([const._TYPE_A, const._TYPE_AAAA], 50) assert nsec_record.name == registration_name assert nsec_record.type == const._TYPE_NSEC assert nsec_record.ttl == 50 assert nsec_record.rdtypes == [const._TYPE_A, const._TYPE_AAAA] 07070100000064000081A40000000000000000000000016619D4CC0000103D000000000000000000000000000000000000003800000000python-zeroconf-0.132.2/tests/services/test_registry.py#!/usr/bin/env python """Unit tests for zeroconf._services.registry.""" import socket import unittest import zeroconf as r from zeroconf import ServiceInfo class TestServiceRegistry(unittest.TestCase): def test_only_register_once(self): type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) registry = r.ServiceRegistry() registry.async_add(info) self.assertRaises(r.ServiceNameAlreadyRegistered, registry.async_add, info) registry.async_remove(info) registry.async_add(info) def test_register_same_server(self): type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" name2 = "xxxyyy2" registration_name = f"{name}.{type_}" registration_name2 = f"{name2}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "same.local.", addresses=[socket.inet_aton("10.0.1.2")] ) info2 = ServiceInfo( type_, registration_name2, 80, 0, 0, desc, "same.local.", addresses=[socket.inet_aton("10.0.1.2")] ) registry = r.ServiceRegistry() registry.async_add(info) registry.async_add(info2) assert registry.async_get_infos_server("same.local.") == [info, info2] registry.async_remove(info) assert registry.async_get_infos_server("same.local.") == [info2] registry.async_remove(info2) assert registry.async_get_infos_server("same.local.") == [] def test_unregister_multiple_times(self): """Verify we can unregister a service multiple times. In production unregister_service and unregister_all_services may happen at the same time during shutdown. We want to treat this as non-fatal since its expected to happen and it is unlikely that the callers know about each other. """ type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) registry = r.ServiceRegistry() registry.async_add(info) self.assertRaises(r.ServiceNameAlreadyRegistered, registry.async_add, info) registry.async_remove(info) registry.async_remove(info) def test_lookups(self): type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) registry = r.ServiceRegistry() registry.async_add(info) assert registry.async_get_service_infos() == [info] assert registry.async_get_info_name(registration_name) == info assert registry.async_get_infos_type(type_) == [info] assert registry.async_get_infos_server("ash-2.local.") == [info] assert registry.async_get_types() == [type_] def test_lookups_upper_case_by_lower_case(self): type_ = "_test-SRVC-type._tcp.local." name = "Xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ASH-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) registry = r.ServiceRegistry() registry.async_add(info) assert registry.async_get_service_infos() == [info] assert registry.async_get_info_name(registration_name.lower()) == info assert registry.async_get_infos_type(type_.lower()) == [info] assert registry.async_get_infos_server("ash-2.local.") == [info] assert registry.async_get_types() == [type_.lower()] 07070100000065000081A40000000000000000000000016619D4CC00001245000000000000000000000000000000000000003500000000python-zeroconf-0.132.2/tests/services/test_types.py#!/usr/bin/env python """Unit tests for zeroconf._services.types.""" import logging import os import socket import sys import unittest import zeroconf as r from zeroconf import ServiceInfo, Zeroconf, ZeroconfServiceTypes from .. import _clear_cache, has_working_ipv6 log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) def test_integration_with_listener(disable_duplicate_packet_suppression): type_ = "_test-listen-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) zeroconf_registrar.registry.async_add(info) try: service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'], timeout=2) assert type_ in service_types _clear_cache(zeroconf_registrar) service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=2) assert type_ in service_types finally: zeroconf_registrar.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_integration_with_listener_v6_records(disable_duplicate_packet_suppression): type_ = "_test-listenv6rec-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" addr = "2606:2800:220:1:248:1893:25c8:1946" # example.com zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_pton(socket.AF_INET6, addr)], ) zeroconf_registrar.registry.async_add(info) try: service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'], timeout=2) assert type_ in service_types _clear_cache(zeroconf_registrar) service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=2) assert type_ in service_types finally: zeroconf_registrar.close() @unittest.skipIf(not has_working_ipv6() or sys.platform == 'win32', 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_integration_with_listener_ipv6(disable_duplicate_packet_suppression): type_ = "_test-listenv6ip-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" addr = "2606:2800:220:1:248:1893:25c8:1946" # example.com zeroconf_registrar = Zeroconf(ip_version=r.IPVersion.V6Only) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_pton(socket.AF_INET6, addr)], ) zeroconf_registrar.registry.async_add(info) try: service_types = ZeroconfServiceTypes.find(ip_version=r.IPVersion.V6Only, timeout=2) assert type_ in service_types _clear_cache(zeroconf_registrar) service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=2) assert type_ in service_types finally: zeroconf_registrar.close() def test_integration_with_subtype_and_listener(disable_duplicate_packet_suppression): subtype_ = "_subtype._sub" type_ = "_listen._tcp.local." name = "xxxyyy" # Note: discovery returns only DNS-SD type not subtype discovery_type = f"{subtype_}.{type_}" registration_name = f"{name}.{type_}" zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} info = ServiceInfo( discovery_type, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) zeroconf_registrar.registry.async_add(info) try: service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'], timeout=2) assert discovery_type in service_types _clear_cache(zeroconf_registrar) service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=2) assert discovery_type in service_types finally: zeroconf_registrar.close() 07070100000066000081A40000000000000000000000016619D4CC0000B046000000000000000000000000000000000000002E00000000python-zeroconf-0.132.2/tests/test_asyncio.py#!/usr/bin/env python """Unit tests for aio.py.""" import asyncio import logging import os import socket import threading from typing import cast from unittest.mock import ANY, call, patch import pytest import zeroconf._services.browser as _services_browser from zeroconf import ( DNSAddress, DNSIncoming, DNSOutgoing, DNSPointer, DNSQuestion, DNSService, DNSText, NotRunningException, ServiceStateChange, Zeroconf, const, ) from zeroconf._exceptions import ( BadTypeInNameException, NonUniqueNameException, ServiceNameAlreadyRegistered, ) from zeroconf._services import ServiceListener from zeroconf._services.info import ServiceInfo from zeroconf._utils.time import current_time_millis from zeroconf.asyncio import ( AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconf, AsyncZeroconfServiceTypes, ) from zeroconf.const import _LISTENER_TIME from . import ( QuestionHistoryWithoutSuppression, _clear_cache, has_working_ipv6, time_changed_millis, ) log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) @pytest.fixture(autouse=True) def verify_threads_ended(): """Verify that the threads are not running after the test.""" threads_before = frozenset(threading.enumerate()) yield threads_after = frozenset(threading.enumerate()) non_executor_threads = frozenset( thread for thread in threads_after if "asyncio" not in thread.name and "ThreadPoolExecutor" not in thread.name ) threads = non_executor_threads - threads_before assert not threads @pytest.mark.asyncio async def test_async_basic_usage() -> None: """Test we can create and close the instance.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.async_close() @pytest.mark.asyncio async def test_async_close_twice() -> None: """Test we can close twice.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.async_close() await aiozc.async_close() @pytest.mark.asyncio async def test_async_with_sync_passed_in() -> None: """Test we can create and close the instance when passing in a sync Zeroconf.""" zc = Zeroconf(interfaces=['127.0.0.1']) aiozc = AsyncZeroconf(zc=zc) assert aiozc.zeroconf is zc await aiozc.async_close() @pytest.mark.asyncio async def test_async_with_sync_passed_in_closed_in_async() -> None: """Test caller closes the sync version in async.""" zc = Zeroconf(interfaces=['127.0.0.1']) aiozc = AsyncZeroconf(zc=zc) assert aiozc.zeroconf is zc zc.close() await aiozc.async_close() @pytest.mark.asyncio async def test_sync_within_event_loop_executor() -> None: """Test sync version still works from an executor within an event loop.""" def sync_code(): zc = Zeroconf(interfaces=['127.0.0.1']) assert zc.get_service_info("_neverused._tcp.local.", "xneverused._neverused._tcp.local.", 10) is None zc.close() await asyncio.get_event_loop().run_in_executor(None, sync_code) @pytest.mark.asyncio async def test_async_service_registration() -> None: """Test registering services broadcasts the registration by default.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test1-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" calls = [] class MyListener(ServiceListener): def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("add", type, name)) def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("remove", type, name)) def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("update", type, name)) listener = MyListener() aiozc.zeroconf.add_service_listener(type_, listener) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aiozc.async_register_service(info) await task new_info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.3")], ) task = await aiozc.async_update_service(new_info) await task assert new_info.dns_service().server_key == "ash-2.local." new_info.server = "ash-3.local." task = await aiozc.async_update_service(new_info) await task assert new_info.dns_service().server_key == "ash-3.local." task = await aiozc.async_unregister_service(new_info) await task await aiozc.async_close() assert calls == [ ('add', type_, registration_name), ('update', type_, registration_name), ('update', type_, registration_name), ('remove', type_, registration_name), ] @pytest.mark.asyncio async def test_async_service_registration_with_server_missing() -> None: """Test registering a service with the server not specified. For backwards compatibility, the server should be set to the name that was passed in. """ aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test1-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" calls = [] class MyListener(ServiceListener): def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("add", type, name)) def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("remove", type, name)) def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("update", type, name)) listener = MyListener() aiozc.zeroconf.add_service_listener(type_, listener) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, addresses=[socket.inet_aton("10.0.1.2")], ) task = await aiozc.async_register_service(info) await task assert info.server == registration_name assert info.server_key == registration_name new_info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.3")], ) task = await aiozc.async_update_service(new_info) await task task = await aiozc.async_unregister_service(new_info) await task await aiozc.async_close() assert calls == [ ('add', type_, registration_name), ('update', type_, registration_name), ('remove', type_, registration_name), ] @pytest.mark.asyncio async def test_async_service_registration_same_server_different_ports() -> None: """Test registering services with the same server with different srv records.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test1-srvc-type._tcp.local." name = "xxxyyy" name2 = "xxxyyy2" registration_name = f"{name}.{type_}" registration_name2 = f"{name2}.{type_}" calls = [] class MyListener(ServiceListener): def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("add", type, name)) def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("remove", type, name)) def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("update", type, name)) listener = MyListener() aiozc.zeroconf.add_service_listener(type_, listener) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) info2 = ServiceInfo( type_, registration_name2, 81, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) tasks = [] tasks.append(await aiozc.async_register_service(info)) tasks.append(await aiozc.async_register_service(info2)) await asyncio.gather(*tasks) task = await aiozc.async_unregister_service(info) await task entries = aiozc.zeroconf.cache.async_entries_with_server("ash-2.local.") assert len(entries) == 1 assert info2.dns_service() in entries await aiozc.async_close() assert calls == [ ('add', type_, registration_name), ('add', type_, registration_name2), ('remove', type_, registration_name), ('remove', type_, registration_name2), ] @pytest.mark.asyncio async def test_async_service_registration_same_server_same_ports() -> None: """Test registering services with the same server with the exact same srv record.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test1-srvc-type._tcp.local." name = "xxxyyy" name2 = "xxxyyy2" registration_name = f"{name}.{type_}" registration_name2 = f"{name2}.{type_}" calls = [] class MyListener(ServiceListener): def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("add", type, name)) def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("remove", type, name)) def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("update", type, name)) listener = MyListener() aiozc.zeroconf.add_service_listener(type_, listener) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) info2 = ServiceInfo( type_, registration_name2, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) tasks = [] tasks.append(await aiozc.async_register_service(info)) tasks.append(await aiozc.async_register_service(info2)) await asyncio.gather(*tasks) task = await aiozc.async_unregister_service(info) await task entries = aiozc.zeroconf.cache.async_entries_with_server("ash-2.local.") assert len(entries) == 1 assert info2.dns_service() in entries await aiozc.async_close() assert calls == [ ('add', type_, registration_name), ('add', type_, registration_name2), ('remove', type_, registration_name), ('remove', type_, registration_name2), ] @pytest.mark.asyncio async def test_async_service_registration_name_conflict() -> None: """Test registering services throws on name conflict.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test-srvc2-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aiozc.async_register_service(info) await task with pytest.raises(NonUniqueNameException): task = await aiozc.async_register_service(info) await task with pytest.raises(ServiceNameAlreadyRegistered): task = await aiozc.async_register_service(info, cooperating_responders=True) await task conflicting_info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-3.local.", addresses=[socket.inet_aton("10.0.1.3")], ) with pytest.raises(NonUniqueNameException): task = await aiozc.async_register_service(conflicting_info) await task await aiozc.async_close() @pytest.mark.asyncio async def test_async_service_registration_name_does_not_match_type() -> None: """Test registering services throws when the name does not match the type.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test-srvc3-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) info.type = "_wrong._tcp.local." with pytest.raises(BadTypeInNameException): task = await aiozc.async_register_service(info) await task await aiozc.async_close() @pytest.mark.asyncio async def test_async_service_registration_name_strict_check() -> None: """Test registering services throws when the name does not comply.""" zc = Zeroconf(interfaces=['127.0.0.1']) aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_ibisip_http._tcp.local." name = "CustomerInformationService-F4D4895E9EEB" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) with pytest.raises(BadTypeInNameException): await zc.async_check_service(info, allow_name_change=False) with pytest.raises(BadTypeInNameException): task = await aiozc.async_register_service(info) await task await zc.async_check_service(info, allow_name_change=False, strict=False) task = await aiozc.async_register_service(info, strict=False) await task await aiozc.async_unregister_service(info) await aiozc.async_close() @pytest.mark.asyncio async def test_async_tasks() -> None: """Test awaiting broadcast tasks""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test-srvc4-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" calls = [] class MyListener(ServiceListener): def add_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("add", type, name)) def remove_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("remove", type, name)) def update_service(self, zeroconf: Zeroconf, type: str, name: str) -> None: calls.append(("update", type, name)) listener = MyListener() aiozc.zeroconf.add_service_listener(type_, listener) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aiozc.async_register_service(info) assert isinstance(task, asyncio.Task) await task new_info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.3")], ) task = await aiozc.async_update_service(new_info) assert isinstance(task, asyncio.Task) await task task = await aiozc.async_unregister_service(new_info) assert isinstance(task, asyncio.Task) await task await aiozc.async_close() assert calls == [ ('add', type_, registration_name), ('update', type_, registration_name), ('remove', type_, registration_name), ] @pytest.mark.asyncio async def test_async_wait_unblocks_on_update() -> None: """Test async_wait will unblock on update.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test-srvc4-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aiozc.async_register_service(info) # Should unblock due to update from the # registration now = current_time_millis() await aiozc.zeroconf.async_wait(50000) assert current_time_millis() - now < 3000 await task now = current_time_millis() await aiozc.zeroconf.async_wait(50) assert current_time_millis() - now < 1000 await aiozc.async_close() @pytest.mark.asyncio async def test_service_info_async_request() -> None: """Test registering services broadcasts and query with AsyncServceInfo.async_request.""" if not has_working_ipv6() or os.environ.get('SKIP_IPV6'): pytest.skip('Requires IPv6') aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test1-srvc-type._tcp.local." name = "xxxyyy" name2 = "abc" registration_name = f"{name}.{type_}" registration_name2 = f"{name2}.{type_}" # Start a tasks BEFORE the registration that will keep trying # and see the registration a bit later get_service_info_task1 = asyncio.ensure_future(aiozc.async_get_service_info(type_, registration_name)) await asyncio.sleep(_LISTENER_TIME / 1000 / 2) get_service_info_task2 = asyncio.ensure_future(aiozc.async_get_service_info(type_, registration_name)) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-1.local.", addresses=[socket.inet_aton("10.0.1.2")], ) info2 = ServiceInfo( type_, registration_name2, 80, 0, 0, desc, "ash-5.local.", addresses=[socket.inet_aton("10.0.1.5")], ) tasks = [] tasks.append(await aiozc.async_register_service(info)) tasks.append(await aiozc.async_register_service(info2)) await asyncio.gather(*tasks) aiosinfo = await get_service_info_task1 assert aiosinfo is not None assert aiosinfo.addresses == [socket.inet_aton("10.0.1.2")] aiosinfo = await get_service_info_task2 assert aiosinfo is not None assert aiosinfo.addresses == [socket.inet_aton("10.0.1.2")] aiosinfo = await aiozc.async_get_service_info(type_, registration_name) assert aiosinfo is not None assert aiosinfo.addresses == [socket.inet_aton("10.0.1.2")] new_info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.3"), socket.inet_pton(socket.AF_INET6, "6001:db8::1")], ) task = await aiozc.async_update_service(new_info) await task aiosinfo = await aiozc.async_get_service_info(type_, registration_name) assert aiosinfo is not None assert aiosinfo.addresses == [socket.inet_aton("10.0.1.3")] aiosinfo = await aiozc.zeroconf.async_get_service_info(type_, registration_name) assert aiosinfo is not None assert aiosinfo.addresses == [socket.inet_aton("10.0.1.3")] aiosinfos = await asyncio.gather( aiozc.async_get_service_info(type_, registration_name), aiozc.async_get_service_info(type_, registration_name2), ) assert aiosinfos[0] is not None assert aiosinfos[0].addresses == [socket.inet_aton("10.0.1.3")] assert aiosinfos[1] is not None assert aiosinfos[1].addresses == [socket.inet_aton("10.0.1.5")] aiosinfo = AsyncServiceInfo(type_, registration_name) _clear_cache(aiozc.zeroconf) # Generating the race condition is almost impossible # without patching since its a TOCTOU race with patch("zeroconf.asyncio.AsyncServiceInfo._is_complete", False): await aiosinfo.async_request(aiozc.zeroconf, 3000) assert aiosinfo is not None assert aiosinfo.addresses == [socket.inet_aton("10.0.1.3")] task = await aiozc.async_unregister_service(new_info) await task aiosinfo = await aiozc.async_get_service_info(type_, registration_name) assert aiosinfo is None await aiozc.async_close() @pytest.mark.asyncio async def test_async_service_browser() -> None: """Test AsyncServiceBrowser.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test9-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" calls = [] class MyListener(ServiceListener): def add_service(self, aiozc: Zeroconf, type: str, name: str) -> None: calls.append(("add", type, name)) def remove_service(self, aiozc: Zeroconf, type: str, name: str) -> None: calls.append(("remove", type, name)) def update_service(self, aiozc: Zeroconf, type: str, name: str) -> None: calls.append(("update", type, name)) listener = MyListener() await aiozc.async_add_service_listener(type_, listener) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aiozc.async_register_service(info) await task new_info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.3")], ) task = await aiozc.async_update_service(new_info) await task task = await aiozc.async_unregister_service(new_info) await task await aiozc.zeroconf.async_wait(1) await aiozc.async_close() assert calls == [ ('add', type_, registration_name), ('update', type_, registration_name), ('remove', type_, registration_name), ] @pytest.mark.asyncio async def test_async_context_manager() -> None: """Test using an async context manager.""" type_ = "_test10-sr-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" async with AsyncZeroconf(interfaces=['127.0.0.1']) as aiozc: info = ServiceInfo( type_, registration_name, 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aiozc.async_register_service(info) await task aiosinfo = await aiozc.async_get_service_info(type_, registration_name) assert aiosinfo is not None @pytest.mark.asyncio async def test_service_browser_cancel_async_context_manager(): """Test we can cancel an AsyncServiceBrowser with it being used as an async context manager.""" # instantiate a zeroconf instance aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf type_ = "_hap._tcp.local." class MyServiceListener(ServiceListener): pass listener = MyServiceListener() browser = AsyncServiceBrowser(zc, type_, None, listener) assert cast(bool, browser.done) is False async with browser: pass assert cast(bool, browser.done) is True await aiozc.async_close() @pytest.mark.asyncio async def test_async_unregister_all_services() -> None: """Test unregistering all services.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) type_ = "_test1-srvc-type._tcp.local." name = "xxxyyy" name2 = "abc" registration_name = f"{name}.{type_}" registration_name2 = f"{name2}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-1.local.", addresses=[socket.inet_aton("10.0.1.2")], ) info2 = ServiceInfo( type_, registration_name2, 80, 0, 0, desc, "ash-5.local.", addresses=[socket.inet_aton("10.0.1.5")], ) tasks = [] tasks.append(await aiozc.async_register_service(info)) tasks.append(await aiozc.async_register_service(info2)) await asyncio.gather(*tasks) tasks = [] tasks.append(aiozc.async_get_service_info(type_, registration_name)) tasks.append(aiozc.async_get_service_info(type_, registration_name2)) results = await asyncio.gather(*tasks) assert results[0] is not None assert results[1] is not None await aiozc.async_unregister_all_services() _clear_cache(aiozc.zeroconf) tasks = [] tasks.append(aiozc.async_get_service_info(type_, registration_name)) tasks.append(aiozc.async_get_service_info(type_, registration_name2)) results = await asyncio.gather(*tasks) assert results[0] is None assert results[1] is None # Verify we can call again await aiozc.async_unregister_all_services() await aiozc.async_close() @pytest.mark.asyncio async def test_async_zeroconf_service_types(): type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" zeroconf_registrar = AsyncZeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await zeroconf_registrar.async_register_service(info) await task # Ensure we do not clear the cache until after the last broadcast is processed await asyncio.sleep(0.2) _clear_cache(zeroconf_registrar.zeroconf) try: service_types = await AsyncZeroconfServiceTypes.async_find(interfaces=['127.0.0.1'], timeout=2) assert type_ in service_types _clear_cache(zeroconf_registrar.zeroconf) service_types = await AsyncZeroconfServiceTypes.async_find(aiozc=zeroconf_registrar, timeout=2) assert type_ in service_types finally: await zeroconf_registrar.async_close() @pytest.mark.asyncio async def test_guard_against_running_serviceinfo_request_event_loop() -> None: """Test that running ServiceInfo.request from the event loop throws.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) service_info = AsyncServiceInfo("_hap._tcp.local.", "doesnotmatter._hap._tcp.local.") with pytest.raises(RuntimeError): service_info.request(aiozc.zeroconf, 3000) await aiozc.async_close() @pytest.mark.asyncio async def test_service_browser_instantiation_generates_add_events_from_cache(): """Test that the ServiceBrowser will generate Add events with the existing cache when starting.""" # instantiate a zeroconf instance aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf type_ = "_hap._tcp.local." registration_name = "xxxyyy.%s" % type_ callbacks = [] class MyServiceListener(ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("add", type_, name)) def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("remove", type_, name)) def update_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("update", type_, name)) listener = MyServiceListener() desc = {'path': '/~paulsm/'} address_parsed = "10.0.1.2" address = socket.inet_aton(address_parsed) info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address]) zc.cache.async_add_records( [info.dns_pointer(), info.dns_service(), *info.dns_addresses(), info.dns_text()] ) browser = AsyncServiceBrowser(zc, type_, None, listener) await asyncio.sleep(0) assert callbacks == [ ('add', type_, registration_name), ] await browser.async_cancel() await aiozc.async_close() @pytest.mark.asyncio async def test_integration(): service_added = asyncio.Event() service_removed = asyncio.Event() unexpected_ttl = asyncio.Event() got_query = asyncio.Event() type_ = "_http._tcp.local." registration_name = "xxxyyy.%s" % type_ def on_service_state_change(zeroconf, service_type, state_change, name): if name == registration_name: if state_change is ServiceStateChange.Added: service_added.set() elif state_change is ServiceStateChange.Removed: service_removed.set() aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_browser = aiozc.zeroconf zeroconf_browser.question_history = QuestionHistoryWithoutSuppression() await zeroconf_browser.async_wait_for_start() # we are going to patch the zeroconf send to check packet sizes old_send = zeroconf_browser.async_send expected_ttl = const._DNS_OTHER_TTL nbr_answers = 0 answers = [] packets = [] def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT, v6_flow_scope=()): """Sends an outgoing packet.""" pout = DNSIncoming(out.packets()[0]) packets.append(pout) last_answers = pout.answers() answers.append(last_answers) nonlocal nbr_answers for answer in last_answers: nbr_answers += 1 if not answer.ttl > expected_ttl / 2: unexpected_ttl.set() got_query.set() old_send(out, addr=addr, port=port, v6_flow_scope=v6_flow_scope) assert len(zeroconf_browser.engine.protocols) == 2 aio_zeroconf_registrar = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_registrar = aio_zeroconf_registrar.zeroconf await aio_zeroconf_registrar.zeroconf.async_wait_for_start() assert len(zeroconf_registrar.engine.protocols) == 2 # patch the zeroconf send so we can capture what is being sent with patch.object(zeroconf_browser, "async_send", send): service_added = asyncio.Event() service_removed = asyncio.Event() browser = AsyncServiceBrowser(zeroconf_browser, type_, [on_service_state_change]) info = ServiceInfo( type_, registration_name, 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) task = await aio_zeroconf_registrar.async_register_service(info) await task loop = asyncio.get_running_loop() try: await asyncio.wait_for(service_added.wait(), 1) assert service_added.is_set() # Make sure the startup queries are sent original_now = loop.time() start_millis = original_now * 1000 now_millis = start_millis for query_count in range(_services_browser.STARTUP_QUERIES): now_millis += (2**query_count) * 1000 time_changed_millis(now_millis) got_query.clear() assert not unexpected_ttl.is_set() assert len(packets) == _services_browser.STARTUP_QUERIES packets.clear() # Wait for the first refresh query # Move time forward past when the TTL is no longer # fresh (AKA ~75% of the TTL) now_millis = start_millis + ((expected_ttl * 1000) * 0.76) time_changed_millis(now_millis) await asyncio.wait_for(got_query.wait(), 1) assert not unexpected_ttl.is_set() assert len(packets) == 1 packets.clear() assert len(answers) == _services_browser.STARTUP_QUERIES + 1 # The first question should have no known answers assert len(answers[0]) == 0 # The rest of the startup questions should have # known answers for answer_list in answers[1:-2]: assert len(answer_list) == 1 # Once the TTL is reached, the last question should have no known answers assert len(answers[-1]) == 0 got_query.clear() packets.clear() # Move time forward past when the TTL is no longer # fresh (AKA 85% of the TTL) to ensure we try # to rescue the record now_millis = start_millis + ((expected_ttl * 1000) * 0.87) time_changed_millis(now_millis) await asyncio.wait_for(got_query.wait(), 1) assert len(packets) == 1 assert not unexpected_ttl.is_set() packets.clear() got_query.clear() # Move time forward past when the TTL is no longer # fresh (AKA 95% of the TTL). At this point # nothing should get scheduled rescued because the rescue # would exceed the TTL now_millis = start_millis + ((expected_ttl * 1000) * 0.98) # Verify we don't send a query for a record that is # past the TTL as we should not try to rescue it # once its past the TTL time_changed_millis(now_millis) await asyncio.wait_for(got_query.wait(), 1) assert len(packets) == 1 # Don't remove service, allow close() to cleanup finally: await aio_zeroconf_registrar.async_close() await asyncio.wait_for(service_removed.wait(), 1) assert service_removed.is_set() await browser.async_cancel() await aiozc.async_close() @pytest.mark.asyncio async def test_info_asking_default_is_asking_qm_questions_after_the_first_qu(): """Verify the service info first question is QU and subsequent ones are QM questions.""" type_ = "_quservice._tcp.local." aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf_info = aiozc.zeroconf name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) zeroconf_info.registry.async_add(info) # we are going to patch the zeroconf send to check query transmission old_send = zeroconf_info.async_send first_outgoing = None second_outgoing = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT): """Sends an outgoing packet.""" nonlocal first_outgoing nonlocal second_outgoing if out.questions: if first_outgoing is not None and second_outgoing is None: # type: ignore[unreachable] second_outgoing = out # type: ignore[unreachable] if first_outgoing is None: first_outgoing = out old_send(out, addr=addr, port=port) # patch the zeroconf send with patch.object(zeroconf_info, "async_send", send): aiosinfo = AsyncServiceInfo(type_, registration_name) # Patch _is_complete so we send multiple times with patch("zeroconf.asyncio.AsyncServiceInfo._is_complete", False): await aiosinfo.async_request(aiozc.zeroconf, 1200) try: assert first_outgoing.questions[0].unicast is True # type: ignore[union-attr] assert second_outgoing.questions[0].unicast is False # type: ignore[attr-defined] finally: await aiozc.async_close() @pytest.mark.asyncio async def test_service_browser_ignores_unrelated_updates(): """Test that the ServiceBrowser ignores unrelated updates.""" # instantiate a zeroconf instance aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf type_ = "_veryuniqueone._tcp.local." registration_name = "xxxyyy.%s" % type_ callbacks = [] class MyServiceListener(ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("add", type_, name)) def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("remove", type_, name)) def update_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks if name == registration_name: callbacks.append(("update", type_, name)) listener = MyServiceListener() desc = {'path': '/~paulsm/'} address_parsed = "10.0.1.2" address = socket.inet_aton(address_parsed) info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[address]) zc.cache.async_add_records( [ info.dns_pointer(), info.dns_service(), *info.dns_addresses(), info.dns_text(), DNSService( "zoom._unrelated._tcp.local.", const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 81, 'unrelated.local.', ), ] ) browser = AsyncServiceBrowser(zc, type_, None, listener) generated = DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( DNSPointer( "_unrelated._tcp.local.", const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, "zoom._unrelated._tcp.local.", ), 0, ) generated.add_answer_at_time( DNSAddress("unrelated.local.", const._TYPE_A, const._CLASS_IN, const._DNS_HOST_TTL, b"1234"), 0, ) generated.add_answer_at_time( DNSText( "zoom._unrelated._tcp.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, b"zoom", ), 0, ) zc.record_manager.async_updates_from_response(DNSIncoming(generated.packets()[0])) await browser.async_cancel() await asyncio.sleep(0) assert callbacks == [ ('add', type_, registration_name), ] await aiozc.async_close() @pytest.mark.asyncio async def test_async_request_timeout(): """Test that the timeout does not throw an exception and finishes close to the actual timeout.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.zeroconf.async_wait_for_start() start_time = current_time_millis() assert await aiozc.async_get_service_info("_notfound.local.", "notthere._notfound.local.") is None end_time = current_time_millis() await aiozc.async_close() # 3000ms for the default timeout # 1000ms for loaded systems + schedule overhead assert (end_time - start_time) < 3000 + 1000 @pytest.mark.asyncio async def test_async_request_non_running_instance(): """Test that the async_request throws when zeroconf is not running.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.async_close() with pytest.raises(NotRunningException): await aiozc.async_get_service_info("_notfound.local.", "notthere._notfound.local.") @pytest.mark.asyncio async def test_legacy_unicast_response(run_isolated): """Verify legacy unicast responses include questions and correct id.""" type_ = "_mservice._tcp.local." aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.zeroconf.async_wait_for_start() name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) aiozc.zeroconf.registry.async_add(info) query = DNSOutgoing(const._FLAGS_QR_QUERY, multicast=False, id_=888) question = DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) query.add_question(question) protocol = aiozc.zeroconf.engine.protocols[0] with patch.object(aiozc.zeroconf, "async_send") as send_mock: protocol.datagram_received(query.packets()[0], ('127.0.0.1', 6503)) calls = send_mock.mock_calls # Verify the response is sent back on the socket it was recieved from assert calls == [call(ANY, '127.0.0.1', 6503, (), protocol.transport)] outgoing = send_mock.call_args[0][0] assert isinstance(outgoing, DNSOutgoing) assert outgoing.questions == [question] assert outgoing.id == query.id await aiozc.async_close() @pytest.mark.asyncio async def test_update_with_uppercase_names(run_isolated): """Test an ip update from a shelly which uses uppercase names.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.zeroconf.async_wait_for_start() callbacks = [] class MyServiceListener(ServiceListener): def add_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks callbacks.append(("add", type_, name)) def remove_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks callbacks.append(("remove", type_, name)) def update_service(self, zc, type_, name) -> None: # type: ignore[no-untyped-def] nonlocal callbacks callbacks.append(("update", type_, name)) listener = MyServiceListener() browser = AsyncServiceBrowser(aiozc.zeroconf, "_http._tcp.local.", None, listener) protocol = aiozc.zeroconf.engine.protocols[0] packet = b'\x00\x00\x84\x80\x00\x00\x00\n\x00\x00\x00\x00\t_services\x07_dns-sd\x04_udp\x05local\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00\x14\x07_shelly\x04_tcp\x05local\x00\t_services\x07_dns-sd\x04_udp\x05local\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00\x12\x05_http\x04_tcp\x05local\x00\x07_shelly\x04_tcp\x05local\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00.\x19shellypro4pm-94b97ec07650\x07_shelly\x04_tcp\x05local\x00\x19shellypro4pm-94b97ec07650\x07_shelly\x04_tcp\x05local\x00\x00!\x80\x01\x00\x00\x00x\x00\'\x00\x00\x00\x00\x00P\x19ShellyPro4PM-94B97EC07650\x05local\x00\x19shellypro4pm-94b97ec07650\x07_shelly\x04_tcp\x05local\x00\x00\x10\x80\x01\x00\x00\x00x\x00"\napp=Pro4PM\x10ver=0.10.0-beta5\x05gen=2\x05_http\x04_tcp\x05local\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00,\x19ShellyPro4PM-94B97EC07650\x05_http\x04_tcp\x05local\x00\x19ShellyPro4PM-94B97EC07650\x05_http\x04_tcp\x05local\x00\x00!\x80\x01\x00\x00\x00x\x00\'\x00\x00\x00\x00\x00P\x19ShellyPro4PM-94B97EC07650\x05local\x00\x19ShellyPro4PM-94B97EC07650\x05_http\x04_tcp\x05local\x00\x00\x10\x80\x01\x00\x00\x00x\x00\x06\x05gen=2\x19ShellyPro4PM-94B97EC07650\x05local\x00\x00\x01\x80\x01\x00\x00\x00x\x00\x04\xc0\xa8\xbc=\x19ShellyPro4PM-94B97EC07650\x05local\x00\x00/\x80\x01\x00\x00\x00x\x00$\x19ShellyPro4PM-94B97EC07650\x05local\x00\x00\x01@' # noqa: E501 protocol.datagram_received(packet, ('127.0.0.1', 6503)) await asyncio.sleep(0) packet = b'\x00\x00\x84\x80\x00\x00\x00\n\x00\x00\x00\x00\t_services\x07_dns-sd\x04_udp\x05local\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00\x14\x07_shelly\x04_tcp\x05local\x00\t_services\x07_dns-sd\x04_udp\x05local\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00\x12\x05_http\x04_tcp\x05local\x00\x07_shelly\x04_tcp\x05local\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00.\x19shellypro4pm-94b97ec07650\x07_shelly\x04_tcp\x05local\x00\x19shellypro4pm-94b97ec07650\x07_shelly\x04_tcp\x05local\x00\x00!\x80\x01\x00\x00\x00x\x00\'\x00\x00\x00\x00\x00P\x19ShellyPro4PM-94B97EC07650\x05local\x00\x19shellypro4pm-94b97ec07650\x07_shelly\x04_tcp\x05local\x00\x00\x10\x80\x01\x00\x00\x00x\x00"\napp=Pro4PM\x10ver=0.10.0-beta5\x05gen=2\x05_http\x04_tcp\x05local\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00,\x19ShellyPro4PM-94B97EC07650\x05_http\x04_tcp\x05local\x00\x19ShellyPro4PM-94B97EC07650\x05_http\x04_tcp\x05local\x00\x00!\x80\x01\x00\x00\x00x\x00\'\x00\x00\x00\x00\x00P\x19ShellyPro4PM-94B97EC07650\x05local\x00\x19ShellyPro4PM-94B97EC07650\x05_http\x04_tcp\x05local\x00\x00\x10\x80\x01\x00\x00\x00x\x00\x06\x05gen=2\x19ShellyPro4PM-94B97EC07650\x05local\x00\x00\x01\x80\x01\x00\x00\x00x\x00\x04\xc0\xa8\xbcA\x19ShellyPro4PM-94B97EC07650\x05local\x00\x00/\x80\x01\x00\x00\x00x\x00$\x19ShellyPro4PM-94B97EC07650\x05local\x00\x00\x01@' # noqa: E501 protocol.datagram_received(packet, ('127.0.0.1', 6503)) await browser.async_cancel() await aiozc.async_close() assert callbacks == [ ('add', '_http._tcp.local.', 'ShellyPro4PM-94B97EC07650._http._tcp.local.'), ('update', '_http._tcp.local.', 'ShellyPro4PM-94B97EC07650._http._tcp.local.'), ] 07070100000067000081A40000000000000000000000016619D4CC0000227E000000000000000000000000000000000000002C00000000python-zeroconf-0.132.2/tests/test_cache.py#!/usr/bin/env python """ Unit tests for zeroconf._cache. """ import logging import unittest import unittest.mock import zeroconf as r from zeroconf import const log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) class TestDNSCache(unittest.TestCase): def test_order(self): record1 = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'b') cache = r.DNSCache() cache.async_add_records([record1, record2]) entry = r.DNSEntry('a', const._TYPE_SOA, const._CLASS_IN) cached_record = cache.get(entry) assert cached_record == record2 def test_adding_same_record_to_cache_different_ttls_with_get(self): """We should always get back the last entry we added if there are different TTLs. This ensures we only have one source of truth for TTLs as a record cannot be both expired and not expired. """ record1 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 10, b'a') cache = r.DNSCache() cache.async_add_records([record1, record2]) entry = r.DNSEntry(record2.name, const._TYPE_A, const._CLASS_IN) cached_record = cache.get(entry) assert cached_record == record2 def test_adding_same_record_to_cache_different_ttls_with_get_all(self): """Verify we only get one record back. The last record added should replace the previous since two records with different ttls are __eq__. This ensures we only have one source of truth for TTLs as a record cannot be both expired and not expired. """ record1 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 10, b'a') cache = r.DNSCache() cache.async_add_records([record1, record2]) cached_records = cache.get_all_by_details('a', const._TYPE_A, const._CLASS_IN) assert cached_records == [record2] def test_cache_empty_does_not_leak_memory_by_leaving_empty_list(self): record1 = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'b') cache = r.DNSCache() cache.async_add_records([record1, record2]) assert 'a' in cache.cache cache.async_remove_records([record1, record2]) assert 'a' not in cache.cache def test_cache_empty_multiple_calls(self): record1 = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'b') cache = r.DNSCache() cache.async_add_records([record1, record2]) assert 'a' in cache.cache cache.async_remove_records([record1, record2]) assert 'a' not in cache.cache class TestDNSAsyncCacheAPI(unittest.TestCase): def test_async_get_unique(self): record1 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'b') cache = r.DNSCache() cache.async_add_records([record1, record2]) assert cache.async_get_unique(record1) == record1 assert cache.async_get_unique(record2) == record2 def test_async_all_by_details(self): record1 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'b') cache = r.DNSCache() cache.async_add_records([record1, record2]) assert set(cache.async_all_by_details('a', const._TYPE_A, const._CLASS_IN)) == {record1, record2} def test_async_entries_with_server(self): record1 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 85, 'ab' ) record2 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'ab' ) cache = r.DNSCache() cache.async_add_records([record1, record2]) assert set(cache.async_entries_with_server('ab')) == {record1, record2} assert set(cache.async_entries_with_server('AB')) == {record1, record2} def test_async_entries_with_name(self): record1 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 85, 'ab' ) record2 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'ab' ) cache = r.DNSCache() cache.async_add_records([record1, record2]) assert set(cache.async_entries_with_name('irrelevant')) == {record1, record2} assert set(cache.async_entries_with_name('Irrelevant')) == {record1, record2} # These functions have been seen in other projects so # we try to maintain a stable API for all the threadsafe getters class TestDNSCacheAPI(unittest.TestCase): def test_get(self): record1 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'b') record3 = r.DNSAddress('a', const._TYPE_AAAA, const._CLASS_IN, 1, b'ipv6') cache = r.DNSCache() cache.async_add_records([record1, record2, record3]) assert cache.get(record1) == record1 assert cache.get(record2) == record2 assert cache.get(r.DNSEntry('a', const._TYPE_A, const._CLASS_IN)) == record2 assert cache.get(r.DNSEntry('a', const._TYPE_AAAA, const._CLASS_IN)) == record3 assert cache.get(r.DNSEntry('notthere', const._TYPE_A, const._CLASS_IN)) is None def test_get_by_details(self): record1 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'b') cache = r.DNSCache() cache.async_add_records([record1, record2]) assert cache.get_by_details('a', const._TYPE_A, const._CLASS_IN) == record2 def test_get_all_by_details(self): record1 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'a') record2 = r.DNSAddress('a', const._TYPE_A, const._CLASS_IN, 1, b'b') cache = r.DNSCache() cache.async_add_records([record1, record2]) assert set(cache.get_all_by_details('a', const._TYPE_A, const._CLASS_IN)) == {record1, record2} def test_entries_with_server(self): record1 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 85, 'ab' ) record2 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'ab' ) cache = r.DNSCache() cache.async_add_records([record1, record2]) assert set(cache.entries_with_server('ab')) == {record1, record2} assert set(cache.entries_with_server('AB')) == {record1, record2} def test_entries_with_name(self): record1 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 85, 'ab' ) record2 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'ab' ) cache = r.DNSCache() cache.async_add_records([record1, record2]) assert set(cache.entries_with_name('irrelevant')) == {record1, record2} assert set(cache.entries_with_name('Irrelevant')) == {record1, record2} def test_current_entry_with_name_and_alias(self): record1 = r.DNSPointer( 'irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, 'x.irrelevant' ) record2 = r.DNSPointer( 'irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, 'y.irrelevant' ) cache = r.DNSCache() cache.async_add_records([record1, record2]) assert cache.current_entry_with_name_and_alias('irrelevant', 'x.irrelevant') == record1 def test_name(self): record1 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 85, 'ab' ) record2 = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'ab' ) cache = r.DNSCache() cache.async_add_records([record1, record2]) assert cache.names() == ['irrelevant'] 07070100000068000081A40000000000000000000000016619D4CC00005D8F000000000000000000000000000000000000002B00000000python-zeroconf-0.132.2/tests/test_core.py#!/usr/bin/env python """ Unit tests for zeroconf._core """ import asyncio import logging import os import socket import sys import threading import time import unittest import unittest.mock from typing import Tuple, Union, cast from unittest.mock import Mock, patch if sys.version_info[:3][1] < 8: AsyncMock = Mock else: from unittest.mock import AsyncMock import pytest import zeroconf as r from zeroconf import NotRunningException, Zeroconf, const, current_time_millis from zeroconf._listener import AsyncListener, _WrappedTransport from zeroconf._protocol.incoming import DNSIncoming from zeroconf.asyncio import AsyncZeroconf from . import _clear_cache, _inject_response, _wait_for_start, has_working_ipv6 log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) def threadsafe_query( zc: 'Zeroconf', protocol: 'AsyncListener', msg: DNSIncoming, addr: str, port: int, transport: _WrappedTransport, v6_flow_scope: Union[Tuple[()], Tuple[int, int]], ) -> None: async def make_query(): protocol.handle_query_or_defer(msg, addr, port, transport, v6_flow_scope) assert zc.loop is not None asyncio.run_coroutine_threadsafe(make_query(), zc.loop).result() class Framework(unittest.TestCase): def test_launch_and_close(self): rv = r.Zeroconf(interfaces=r.InterfaceChoice.All) rv.close() rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default) rv.close() def test_launch_and_close_context_manager(self): with r.Zeroconf(interfaces=r.InterfaceChoice.All) as rv: assert rv.done is False assert rv.done is True with r.Zeroconf(interfaces=r.InterfaceChoice.Default) as rv: # type: ignore[unreachable] assert rv.done is False assert rv.done is True def test_launch_and_close_unicast(self): rv = r.Zeroconf(interfaces=r.InterfaceChoice.All, unicast=True) rv.close() rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default, unicast=True) rv.close() def test_close_multiple_times(self): rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default) rv.close() rv.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_launch_and_close_v4_v6(self): rv = r.Zeroconf(interfaces=r.InterfaceChoice.All, ip_version=r.IPVersion.All) rv.close() rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default, ip_version=r.IPVersion.All) rv.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_launch_and_close_v6_only(self): rv = r.Zeroconf(interfaces=r.InterfaceChoice.All, ip_version=r.IPVersion.V6Only) rv.close() rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default, ip_version=r.IPVersion.V6Only) rv.close() @unittest.skipIf(sys.platform == 'darwin', reason="apple_p2p failure path not testable on mac") def test_launch_and_close_apple_p2p_not_mac(self): with pytest.raises(RuntimeError): r.Zeroconf(apple_p2p=True) @unittest.skipIf(sys.platform != 'darwin', reason="apple_p2p happy path only testable on mac") def test_launch_and_close_apple_p2p_on_mac(self): rv = r.Zeroconf(apple_p2p=True) rv.close() def test_async_updates_from_response(self): def mock_incoming_msg(service_state_change: r.ServiceStateChange) -> r.DNSIncoming: ttl = 120 generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) if service_state_change == r.ServiceStateChange.Updated: generated.add_answer_at_time( r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, service_text, ), 0, ) return r.DNSIncoming(generated.packets()[0]) if service_state_change == r.ServiceStateChange.Removed: ttl = 0 generated.add_answer_at_time( r.DNSPointer(service_type, const._TYPE_PTR, const._CLASS_IN, ttl, service_name), 0 ) generated.add_answer_at_time( r.DNSService( service_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, ttl, 0, 0, 80, service_server, ), 0, ) generated.add_answer_at_time( r.DNSText( service_name, const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, ttl, service_text ), 0, ) generated.add_answer_at_time( r.DNSAddress( service_server, const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, ttl, socket.inet_aton(service_address), ), 0, ) return r.DNSIncoming(generated.packets()[0]) def mock_split_incoming_msg(service_state_change: r.ServiceStateChange) -> r.DNSIncoming: """Mock an incoming message for the case where the packet is split.""" ttl = 120 generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSAddress( service_server, const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, ttl, socket.inet_aton(service_address), ), 0, ) generated.add_answer_at_time( r.DNSService( service_name, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, ttl, 0, 0, 80, service_server, ), 0, ) return r.DNSIncoming(generated.packets()[0]) service_name = 'name._type._tcp.local.' service_type = '_type._tcp.local.' service_server = 'ash-2.local.' service_text = b'path=/~paulsm/' service_address = '10.0.1.2' zeroconf = r.Zeroconf(interfaces=['127.0.0.1']) try: # service added _inject_response(zeroconf, mock_incoming_msg(r.ServiceStateChange.Added)) dns_text = zeroconf.cache.get_by_details(service_name, const._TYPE_TXT, const._CLASS_IN) assert dns_text is not None assert cast(r.DNSText, dns_text).text == service_text # service_text is b'path=/~paulsm/' all_dns_text = zeroconf.cache.get_all_by_details(service_name, const._TYPE_TXT, const._CLASS_IN) assert [dns_text] == all_dns_text # https://tools.ietf.org/html/rfc6762#section-10.2 # Instead of merging this new record additively into the cache in addition # to any previous records with the same name, rrtype, and rrclass, # all old records with that name, rrtype, and rrclass that were received # more than one second ago are declared invalid, # and marked to expire from the cache in one second. time.sleep(1.1) # service updated. currently only text record can be updated service_text = b'path=/~humingchun/' _inject_response(zeroconf, mock_incoming_msg(r.ServiceStateChange.Updated)) dns_text = zeroconf.cache.get_by_details(service_name, const._TYPE_TXT, const._CLASS_IN) assert dns_text is not None assert cast(r.DNSText, dns_text).text == service_text # service_text is b'path=/~humingchun/' time.sleep(1.1) # The split message only has a SRV and A record. # This should not evict TXT records from the cache _inject_response(zeroconf, mock_split_incoming_msg(r.ServiceStateChange.Updated)) time.sleep(1.1) dns_text = zeroconf.cache.get_by_details(service_name, const._TYPE_TXT, const._CLASS_IN) assert dns_text is not None assert cast(r.DNSText, dns_text).text == service_text # service_text is b'path=/~humingchun/' # service removed _inject_response(zeroconf, mock_incoming_msg(r.ServiceStateChange.Removed)) dns_text = zeroconf.cache.get_by_details(service_name, const._TYPE_TXT, const._CLASS_IN) assert dns_text is not None assert dns_text.is_expired(current_time_millis() + 1000) finally: zeroconf.close() def test_generate_service_query_set_qu_bit(): """Test generate_service_query sets the QU bit.""" zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} type_ = "._hap._tcp.local." registration_name = "this-host-is-not-used._hap._tcp.local." info = r.ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) out = zeroconf_registrar.generate_service_query(info) assert out.questions[0].unicast is True zeroconf_registrar.close() def test_invalid_packets_ignored_and_does_not_cause_loop_exception(): """Ensure an invalid packet cannot cause the loop to collapse.""" zc = Zeroconf(interfaces=['127.0.0.1']) generated = r.DNSOutgoing(0) packet = generated.packets()[0] packet = packet[:8] + b'deadbeef' + packet[8:] parsed = r.DNSIncoming(packet) assert parsed.valid is False # Invalid Packet mock_out = unittest.mock.Mock() mock_out.packets = lambda: [packet] zc.send(mock_out) # Invalid oversized packet mock_out = unittest.mock.Mock() mock_out.packets = lambda: [packet * 1000] zc.send(mock_out) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) entry = r.DNSText( "didnotcrashincoming._crash._tcp.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 500, b'path=/~paulsm/', ) assert isinstance(entry, r.DNSText) assert isinstance(entry, r.DNSRecord) assert isinstance(entry, r.DNSEntry) generated.add_answer_at_time(entry, 0) zc.send(generated) time.sleep(0.2) zc.close() assert zc.cache.get(entry) is not None def test_goodbye_all_services(): """Verify generating the goodbye query does not change with time.""" zc = Zeroconf(interfaces=['127.0.0.1']) out = zc.generate_unregister_all_services() assert out is None type_ = "_http._tcp.local." registration_name = "xxxyyy.%s" % type_ desc = {'path': '/~paulsm/'} info = r.ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) out = zc.generate_unregister_all_services() assert out is not None first_packet = out.packets() zc.registry.async_add(info) out2 = zc.generate_unregister_all_services() assert out2 is not None second_packet = out.packets() assert second_packet == first_packet # Verify the registery is empty out3 = zc.generate_unregister_all_services() assert out3 is None assert zc.registry.async_get_service_infos() == [] zc.close() def test_register_service_with_custom_ttl(): """Test a registering a service with a custom ttl.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_homeassistant._tcp.local." name = "MyTestHome" info_service = r.ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, "ash-90.local.", addresses=[socket.inet_aton("10.0.1.2")], ) zc.register_service(info_service, ttl=3000) record = zc.cache.get(info_service.dns_pointer()) assert record is not None assert record.ttl == 3000 zc.close() def test_logging_packets(caplog): """Test packets are only logged with debug logging.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_logging._tcp.local." name = "TLD" info_service = r.ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, "ash-90.local.", addresses=[socket.inet_aton("10.0.1.2")], ) logging.getLogger('zeroconf').setLevel(logging.DEBUG) caplog.clear() zc.register_service(info_service, ttl=3000) assert "Sending to" in caplog.text record = zc.cache.get(info_service.dns_pointer()) assert record is not None assert record.ttl == 3000 logging.getLogger('zeroconf').setLevel(logging.INFO) caplog.clear() zc.unregister_service(info_service) assert "Sending to" not in caplog.text logging.getLogger('zeroconf').setLevel(logging.DEBUG) zc.close() def test_get_service_info_failure_path(): """Verify get_service_info return None when the underlying call returns False.""" zc = Zeroconf(interfaces=['127.0.0.1']) assert zc.get_service_info("_neverused._tcp.local.", "xneverused._neverused._tcp.local.", 10) is None zc.close() def test_sending_unicast(): """Test sending unicast response.""" zc = Zeroconf(interfaces=['127.0.0.1']) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) entry = r.DNSText( "didnotcrashincoming._crash._tcp.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 500, b'path=/~paulsm/', ) generated.add_answer_at_time(entry, 0) zc.send(generated, "2001:db8::1", const._MDNS_PORT) # https://www.iana.org/go/rfc3849 time.sleep(0.2) assert zc.cache.get(entry) is None zc.send(generated, "198.51.100.0", const._MDNS_PORT) # Documentation (TEST-NET-2) time.sleep(0.2) assert zc.cache.get(entry) is None zc.send(generated) # Handle slow github CI runners on windows for _ in range(10): time.sleep(0.05) if zc.cache.get(entry) is not None: break assert zc.cache.get(entry) is not None zc.close() def test_tc_bit_defers(): zc = Zeroconf(interfaces=['127.0.0.1']) _wait_for_start(zc) type_ = "_tcbitdefer._tcp.local." name = "knownname" name2 = "knownname2" name3 = "knownname3" registration_name = f"{name}.{type_}" registration2_name = f"{name2}.{type_}" registration3_name = f"{name3}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." server_name2 = "ash-3.local." server_name3 = "ash-4.local." info = r.ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) info2 = r.ServiceInfo( type_, registration2_name, 80, 0, 0, desc, server_name2, addresses=[socket.inet_aton("10.0.1.2")] ) info3 = r.ServiceInfo( type_, registration3_name, 80, 0, 0, desc, server_name3, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) zc.registry.async_add(info2) zc.registry.async_add(info3) protocol = zc.engine.protocols[0] now = r.current_time_millis() _clear_cache(zc) generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(type_, const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) for _ in range(300): # Add so many answers we end up with another packet generated.add_answer_at_time(info.dns_pointer(), now) generated.add_answer_at_time(info2.dns_pointer(), now) generated.add_answer_at_time(info3.dns_pointer(), now) packets = generated.packets() assert len(packets) == 4 expected_deferred = [] source_ip = '203.0.113.13' next_packet = r.DNSIncoming(packets.pop(0)) expected_deferred.append(next_packet) threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert protocol._deferred[source_ip] == expected_deferred assert source_ip in protocol._timers next_packet = r.DNSIncoming(packets.pop(0)) expected_deferred.append(next_packet) threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert protocol._deferred[source_ip] == expected_deferred assert source_ip in protocol._timers threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert protocol._deferred[source_ip] == expected_deferred assert source_ip in protocol._timers next_packet = r.DNSIncoming(packets.pop(0)) expected_deferred.append(next_packet) threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert protocol._deferred[source_ip] == expected_deferred assert source_ip in protocol._timers next_packet = r.DNSIncoming(packets.pop(0)) expected_deferred.append(next_packet) threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert source_ip not in protocol._deferred assert source_ip not in protocol._timers # unregister zc.unregister_service(info) zc.close() def test_tc_bit_defers_last_response_missing(): zc = Zeroconf(interfaces=['127.0.0.1']) _wait_for_start(zc) type_ = "_knowndefer._tcp.local." name = "knownname" name2 = "knownname2" name3 = "knownname3" registration_name = f"{name}.{type_}" registration2_name = f"{name2}.{type_}" registration3_name = f"{name3}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." server_name2 = "ash-3.local." server_name3 = "ash-4.local." info = r.ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) info2 = r.ServiceInfo( type_, registration2_name, 80, 0, 0, desc, server_name2, addresses=[socket.inet_aton("10.0.1.2")] ) info3 = r.ServiceInfo( type_, registration3_name, 80, 0, 0, desc, server_name3, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) zc.registry.async_add(info2) zc.registry.async_add(info3) protocol = zc.engine.protocols[0] now = r.current_time_millis() _clear_cache(zc) source_ip = '203.0.113.12' generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(type_, const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) for _ in range(300): # Add so many answers we end up with another packet generated.add_answer_at_time(info.dns_pointer(), now) generated.add_answer_at_time(info2.dns_pointer(), now) generated.add_answer_at_time(info3.dns_pointer(), now) packets = generated.packets() assert len(packets) == 4 expected_deferred = [] next_packet = r.DNSIncoming(packets.pop(0)) expected_deferred.append(next_packet) threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert protocol._deferred[source_ip] == expected_deferred timer1 = protocol._timers[source_ip] next_packet = r.DNSIncoming(packets.pop(0)) expected_deferred.append(next_packet) threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert protocol._deferred[source_ip] == expected_deferred timer2 = protocol._timers[source_ip] assert timer1.cancelled() assert timer2 != timer1 # Send the same packet again to similar multi interfaces threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert protocol._deferred[source_ip] == expected_deferred assert source_ip in protocol._timers timer3 = protocol._timers[source_ip] assert not timer3.cancelled() assert timer3 == timer2 next_packet = r.DNSIncoming(packets.pop(0)) expected_deferred.append(next_packet) threadsafe_query(zc, protocol, next_packet, source_ip, const._MDNS_PORT, Mock(), ()) assert protocol._deferred[source_ip] == expected_deferred assert source_ip in protocol._timers timer4 = protocol._timers[source_ip] assert timer3.cancelled() assert timer4 != timer3 for _ in range(8): time.sleep(0.1) if source_ip not in protocol._timers and source_ip not in protocol._deferred: break assert source_ip not in protocol._deferred assert source_ip not in protocol._timers # unregister zc.registry.async_remove(info) zc.close() @pytest.mark.asyncio async def test_open_close_twice_from_async() -> None: """Test we can close twice from a coroutine when using Zeroconf. Ideally callers switch to using AsyncZeroconf, however there will be a peroid where they still call the sync wrapper that we want to ensure will not deadlock on shutdown. This test is expected to throw warnings about tasks being destroyed since we force shutdown right away since we don't want to block callers event loops and since they aren't using the AsyncZeroconf version they won't yield with an await like async_close we don't have much choice but to force things down. """ zc = Zeroconf(interfaces=['127.0.0.1']) zc.close() zc.close() await asyncio.sleep(0) @pytest.mark.asyncio async def test_multiple_sync_instances_stared_from_async_close(): """Test we can shutdown multiple sync instances from async.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) zc2 = Zeroconf(interfaces=['127.0.0.1']) assert zc.loop is not None assert zc2.loop is not None assert zc.loop == zc2.loop zc.close() assert zc.loop.is_running() zc2.close() assert zc2.loop.is_running() zc3 = Zeroconf(interfaces=['127.0.0.1']) assert zc3.loop == zc2.loop zc3.close() assert zc3.loop.is_running() await asyncio.sleep(0) def test_shutdown_while_register_in_process(): """Test we can shutdown while registering a service in another thread.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # start a browser type_ = "_homeassistant._tcp.local." name = "MyTestHome" info_service = r.ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, "ash-90.local.", addresses=[socket.inet_aton("10.0.1.2")], ) def _background_register(): zc.register_service(info_service) bgthread = threading.Thread(target=_background_register, daemon=True) bgthread.start() time.sleep(0.3) zc.close() bgthread.join() @pytest.mark.asyncio @unittest.skipIf(sys.version_info[:3][1] < 8, 'Requires Python 3.8 or later to patch _async_setup') @patch("zeroconf._core._STARTUP_TIMEOUT", 0) @patch("zeroconf._core.AsyncEngine._async_setup", new_callable=AsyncMock) async def test_event_loop_blocked(mock_start): """Test we raise NotRunningException when waiting for startup that times out.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) with pytest.raises(NotRunningException): await aiozc.zeroconf.async_wait_for_start() assert aiozc.zeroconf.started is False 07070100000069000081A40000000000000000000000016619D4CC00003A0C000000000000000000000000000000000000002A00000000python-zeroconf-0.132.2/tests/test_dns.py#!/usr/bin/env python """ Unit tests for zeroconf._dns. """ import logging import os import socket import unittest import unittest.mock import pytest import zeroconf as r from zeroconf import DNSHinfo, DNSText, ServiceInfo, const, current_time_millis from zeroconf._dns import DNSRRSet from . import has_working_ipv6 log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) class TestDunder(unittest.TestCase): def test_dns_text_repr(self): # There was an issue on Python 3 that prevented DNSText's repr # from working when the text was longer than 10 bytes text = DNSText('irrelevant', 0, 0, 0, b'12345678901') repr(text) text = DNSText('irrelevant', 0, 0, 0, b'123') repr(text) def test_dns_hinfo_repr_eq(self): hinfo = DNSHinfo('irrelevant', const._TYPE_HINFO, 0, 0, 'cpu', 'os') assert hinfo == hinfo repr(hinfo) def test_dns_pointer_repr(self): pointer = r.DNSPointer('irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, '123') repr(pointer) @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_dns_address_repr(self): address = r.DNSAddress('irrelevant', const._TYPE_SOA, const._CLASS_IN, 1, b'a') assert repr(address).endswith("b'a'") address_ipv4 = r.DNSAddress( 'irrelevant', const._TYPE_SOA, const._CLASS_IN, 1, socket.inet_pton(socket.AF_INET, '127.0.0.1') ) assert repr(address_ipv4).endswith('127.0.0.1') address_ipv6 = r.DNSAddress( 'irrelevant', const._TYPE_SOA, const._CLASS_IN, 1, socket.inet_pton(socket.AF_INET6, '::1') ) assert repr(address_ipv6).endswith('::1') def test_dns_question_repr(self): question = r.DNSQuestion('irrelevant', const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE) repr(question) assert not question != question def test_dns_service_repr(self): service = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'a' ) repr(service) def test_dns_record_abc(self): record = r.DNSRecord('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL) self.assertRaises(r.AbstractMethodException, record.__eq__, record) with pytest.raises((r.AbstractMethodException, TypeError)): record.write(None) # type: ignore[arg-type] def test_dns_record_reset_ttl(self): start = r.current_time_millis() record = r.DNSRecord( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, created=start ) later = start + 1000 record2 = r.DNSRecord( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, created=later ) now = r.current_time_millis() assert record.created != record2.created assert record.get_remaining_ttl(now) != record2.get_remaining_ttl(now) record.reset_ttl(record2) assert record.ttl == record2.ttl assert record.created == record2.created assert record.get_remaining_ttl(now) == record2.get_remaining_ttl(now) def test_service_info_dunder(self): type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" info = ServiceInfo( type_, registration_name, 80, 0, 0, b'', "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) assert not info != info repr(info) def test_service_info_text_properties_not_given(self): type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" info = ServiceInfo( type_=type_, name=registration_name, addresses=[socket.inet_aton("10.0.1.2")], port=80, server="ash-2.local.", ) assert isinstance(info.text, bytes) repr(info) def test_dns_outgoing_repr(self): dns_outgoing = r.DNSOutgoing(const._FLAGS_QR_QUERY) repr(dns_outgoing) def test_dns_record_is_expired(self): record = r.DNSRecord('irrelevant', const._TYPE_SRV, const._CLASS_IN, 8) now = current_time_millis() assert record.is_expired(now) is False assert record.is_expired(now + (8 / 2 * 1000)) is False assert record.is_expired(now + (8 * 1000)) is True def test_dns_record_is_stale(self): record = r.DNSRecord('irrelevant', const._TYPE_SRV, const._CLASS_IN, 8) now = current_time_millis() assert record.is_stale(now) is False assert record.is_stale(now + (8 / 4.1 * 1000)) is False assert record.is_stale(now + (8 / 1.9 * 1000)) is True assert record.is_stale(now + (8 * 1000)) is True def test_dns_record_is_recent(self): now = current_time_millis() record = r.DNSRecord('irrelevant', const._TYPE_SRV, const._CLASS_IN, 8) assert record.is_recent(now + (8 / 4.2 * 1000)) is True assert record.is_recent(now + (8 / 3 * 1000)) is False assert record.is_recent(now + (8 / 2 * 1000)) is False assert record.is_recent(now + (8 * 1000)) is False def test_dns_question_hashablity(): """Test DNSQuestions are hashable.""" record1 = r.DNSQuestion('irrelevant', const._TYPE_A, const._CLASS_IN) record2 = r.DNSQuestion('irrelevant', const._TYPE_A, const._CLASS_IN) record_set = {record1, record2} assert len(record_set) == 1 record_set.add(record1) assert len(record_set) == 1 record3_dupe = r.DNSQuestion('irrelevant', const._TYPE_A, const._CLASS_IN) assert record2 == record3_dupe assert record2.__hash__() == record3_dupe.__hash__() record_set.add(record3_dupe) assert len(record_set) == 1 record4_dupe = r.DNSQuestion('notsame', const._TYPE_A, const._CLASS_IN) assert record2 != record4_dupe assert record2.__hash__() != record4_dupe.__hash__() record_set.add(record4_dupe) assert len(record_set) == 2 def test_dns_record_hashablity_does_not_consider_ttl(): """Test DNSRecord are hashable.""" # Verify the TTL is not considered in the hash record1 = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, const._DNS_OTHER_TTL, b'same') record2 = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, const._DNS_HOST_TTL, b'same') record_set = {record1, record2} assert len(record_set) == 1 record_set.add(record1) assert len(record_set) == 1 record3_dupe = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, const._DNS_HOST_TTL, b'same') assert record2 == record3_dupe assert record2.__hash__() == record3_dupe.__hash__() record_set.add(record3_dupe) assert len(record_set) == 1 def test_dns_record_hashablity_does_not_consider_unique(): """Test DNSRecord are hashable and unique is ignored.""" # Verify the unique value is not considered in the hash record1 = r.DNSAddress( 'irrelevant', const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, b'same' ) record2 = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, const._DNS_OTHER_TTL, b'same') assert record1.class_ == record2.class_ assert record1.__hash__() == record2.__hash__() record_set = {record1, record2} assert len(record_set) == 1 def test_dns_address_record_hashablity(): """Test DNSAddress are hashable.""" address1 = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 1, b'a') address2 = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 1, b'b') address3 = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 1, b'c') address4 = r.DNSAddress('irrelevant', const._TYPE_AAAA, const._CLASS_IN, 1, b'c') record_set = {address1, address2, address3, address4} assert len(record_set) == 4 record_set.add(address1) assert len(record_set) == 4 address3_dupe = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 1, b'c') record_set.add(address3_dupe) assert len(record_set) == 4 # Verify we can remove records additional_set = {address1, address2} record_set -= additional_set assert record_set == {address3, address4} def test_dns_hinfo_record_hashablity(): """Test DNSHinfo are hashable.""" hinfo1 = r.DNSHinfo('irrelevant', const._TYPE_HINFO, 0, 0, 'cpu1', 'os') hinfo2 = r.DNSHinfo('irrelevant', const._TYPE_HINFO, 0, 0, 'cpu2', 'os') record_set = {hinfo1, hinfo2} assert len(record_set) == 2 record_set.add(hinfo1) assert len(record_set) == 2 hinfo2_dupe = r.DNSHinfo('irrelevant', const._TYPE_HINFO, 0, 0, 'cpu2', 'os') assert hinfo2 == hinfo2_dupe assert hinfo2.__hash__() == hinfo2_dupe.__hash__() record_set.add(hinfo2_dupe) assert len(record_set) == 2 def test_dns_pointer_record_hashablity(): """Test DNSPointer are hashable.""" ptr1 = r.DNSPointer('irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, '123') ptr2 = r.DNSPointer('irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, '456') record_set = {ptr1, ptr2} assert len(record_set) == 2 record_set.add(ptr1) assert len(record_set) == 2 ptr2_dupe = r.DNSPointer('irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, '456') assert ptr2 == ptr2 assert ptr2.__hash__() == ptr2_dupe.__hash__() record_set.add(ptr2_dupe) assert len(record_set) == 2 def test_dns_pointer_comparison_is_case_insensitive(): """Test DNSPointer comparison is case insensitive.""" ptr1 = r.DNSPointer('irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, '123') ptr2 = r.DNSPointer('irrelevant'.upper(), const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, '123') assert ptr1 == ptr2 def test_dns_text_record_hashablity(): """Test DNSText are hashable.""" text1 = r.DNSText('irrelevant', 0, 0, const._DNS_OTHER_TTL, b'12345678901') text2 = r.DNSText('irrelevant', 1, 0, const._DNS_OTHER_TTL, b'12345678901') text3 = r.DNSText('irrelevant', 0, 1, const._DNS_OTHER_TTL, b'12345678901') text4 = r.DNSText('irrelevant', 0, 0, const._DNS_OTHER_TTL, b'ABCDEFGHIJK') record_set = {text1, text2, text3, text4} assert len(record_set) == 4 record_set.add(text1) assert len(record_set) == 4 text1_dupe = r.DNSText('irrelevant', 0, 0, const._DNS_OTHER_TTL, b'12345678901') assert text1 == text1_dupe assert text1.__hash__() == text1_dupe.__hash__() record_set.add(text1_dupe) assert len(record_set) == 4 def test_dns_service_record_hashablity(): """Test DNSService are hashable.""" srv1 = r.DNSService('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'a') srv2 = r.DNSService('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 1, 80, 'a') srv3 = r.DNSService('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 81, 'a') srv4 = r.DNSService('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'ab') record_set = {srv1, srv2, srv3, srv4} assert len(record_set) == 4 record_set.add(srv1) assert len(record_set) == 4 srv1_dupe = r.DNSService( 'irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'a' ) assert srv1 == srv1_dupe assert srv1.__hash__() == srv1_dupe.__hash__() record_set.add(srv1_dupe) assert len(record_set) == 4 def test_dns_service_server_key(): """Test DNSService server_key is lowercase.""" srv1 = r.DNSService( 'X._tcp._http.local.', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'X.local.' ) assert srv1.name == 'X._tcp._http.local.' assert srv1.key == 'x._tcp._http.local.' assert srv1.server == 'X.local.' assert srv1.server_key == 'x.local.' def test_dns_service_server_comparison_is_case_insensitive(): """Test DNSService server comparison is case insensitive.""" srv1 = r.DNSService( 'X._tcp._http.local.', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'X.local.' ) srv2 = r.DNSService( 'X._tcp._http.local.', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 0, 0, 80, 'x.local.' ) assert srv1 == srv2 def test_dns_nsec_record_hashablity(): """Test DNSNsec are hashable.""" nsec1 = r.DNSNsec( 'irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, 'irrelevant', [1, 2, 3] ) nsec2 = r.DNSNsec( 'irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, 'irrelevant', [1, 2] ) record_set = {nsec1, nsec2} assert len(record_set) == 2 record_set.add(nsec1) assert len(record_set) == 2 nsec2_dupe = r.DNSNsec( 'irrelevant', const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, 'irrelevant', [1, 2] ) assert nsec2 == nsec2_dupe assert nsec2.__hash__() == nsec2_dupe.__hash__() record_set.add(nsec2_dupe) assert len(record_set) == 2 def test_rrset_does_not_consider_ttl(): """Test DNSRRSet does not consider the ttl in the hash.""" longarec = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 100, b'same') shortarec = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 10, b'same') longaaaarec = r.DNSAddress('irrelevant', const._TYPE_AAAA, const._CLASS_IN, 100, b'same') shortaaaarec = r.DNSAddress('irrelevant', const._TYPE_AAAA, const._CLASS_IN, 10, b'same') rrset = DNSRRSet([longarec, shortaaaarec]) assert rrset.suppresses(longarec) assert rrset.suppresses(shortarec) assert not rrset.suppresses(longaaaarec) assert rrset.suppresses(shortaaaarec) verylongarec = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 1000, b'same') longarec = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 100, b'same') mediumarec = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 60, b'same') shortarec = r.DNSAddress('irrelevant', const._TYPE_A, const._CLASS_IN, 10, b'same') rrset2 = DNSRRSet([mediumarec]) assert not rrset2.suppresses(verylongarec) assert rrset2.suppresses(longarec) assert rrset2.suppresses(mediumarec) assert rrset2.suppresses(shortarec) 0707010000006A000081A40000000000000000000000016619D4CC00000D44000000000000000000000000000000000000002D00000000python-zeroconf-0.132.2/tests/test_engine.py#!/usr/bin/env python """ Unit tests for zeroconf._engine """ import asyncio import itertools import logging from typing import Set from unittest.mock import patch import pytest import zeroconf as r from zeroconf import _engine, const from zeroconf.asyncio import AsyncZeroconf log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) # This test uses asyncio because it needs to access the cache directly # which is not threadsafe @pytest.mark.asyncio async def test_reaper(): with patch.object(_engine, "_CACHE_CLEANUP_INTERVAL", 0.01): aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf = aiozc.zeroconf cache = zeroconf.cache original_entries = list(itertools.chain(*(cache.entries_with_name(name) for name in cache.names()))) record_with_10s_ttl = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 10, b'a') record_with_1s_ttl = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'b') zeroconf.cache.async_add_records([record_with_10s_ttl, record_with_1s_ttl]) question = r.DNSQuestion("_hap._tcp._local.", const._TYPE_PTR, const._CLASS_IN) now = r.current_time_millis() other_known_answers: Set[r.DNSRecord] = { r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, 10000, 'known-to-other._hap._tcp.local.', ) } zeroconf.question_history.add_question_at_time(question, now, other_known_answers) assert zeroconf.question_history.suppresses(question, now, other_known_answers) entries_with_cache = list(itertools.chain(*(cache.entries_with_name(name) for name in cache.names()))) await asyncio.sleep(1.2) entries = list(itertools.chain(*(cache.entries_with_name(name) for name in cache.names()))) assert zeroconf.cache.get(record_with_1s_ttl) is None await aiozc.async_close() assert not zeroconf.question_history.suppresses(question, now, other_known_answers) assert entries != original_entries assert entries_with_cache != original_entries assert record_with_10s_ttl in entries assert record_with_1s_ttl not in entries @pytest.mark.asyncio async def test_reaper_aborts_when_done(): """Ensure cache cleanup stops when zeroconf is done.""" with patch.object(_engine, "_CACHE_CLEANUP_INTERVAL", 0.01): aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zeroconf = aiozc.zeroconf record_with_10s_ttl = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 10, b'a') record_with_1s_ttl = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'b') zeroconf.cache.async_add_records([record_with_10s_ttl, record_with_1s_ttl]) assert zeroconf.cache.get(record_with_10s_ttl) is not None assert zeroconf.cache.get(record_with_1s_ttl) is not None await aiozc.async_close() await asyncio.sleep(1.2) assert zeroconf.cache.get(record_with_10s_ttl) is not None assert zeroconf.cache.get(record_with_1s_ttl) is not None 0707010000006B000081A40000000000000000000000016619D4CC0000139D000000000000000000000000000000000000003100000000python-zeroconf-0.132.2/tests/test_exceptions.py#!/usr/bin/env python """ Unit tests for zeroconf._exceptions """ import logging import unittest import unittest.mock import zeroconf as r from zeroconf import ServiceInfo, Zeroconf log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) class Exceptions(unittest.TestCase): browser = None # type: Zeroconf @classmethod def setUpClass(cls): cls.browser = Zeroconf(interfaces=['127.0.0.1']) @classmethod def tearDownClass(cls): cls.browser.close() del cls.browser def test_bad_service_info_name(self): self.assertRaises(r.BadTypeInNameException, self.browser.get_service_info, "type", "type_not") def test_bad_service_names(self): bad_names_to_try = ( '', 'local', '_tcp.local.', '_udp.local.', '._udp.local.', '_@._tcp.local.', '_A@._tcp.local.', '_x--x._tcp.local.', '_-x._udp.local.', '_x-._tcp.local.', '_22._udp.local.', '_2-2._tcp.local.', '\x00._x._udp.local.', ) for name in bad_names_to_try: self.assertRaises(r.BadTypeInNameException, self.browser.get_service_info, name, 'x.' + name) def test_bad_local_names_for_get_service_info(self): bad_names_to_try = ( 'homekitdev._nothttp._tcp.local.', 'homekitdev._http._udp.local.', ) for name in bad_names_to_try: self.assertRaises( r.BadTypeInNameException, self.browser.get_service_info, '_http._tcp.local.', name ) def test_good_instance_names(self): assert r.service_type_name('.._x._tcp.local.') == '_x._tcp.local.' assert r.service_type_name('x.y._http._tcp.local.') == '_http._tcp.local.' assert r.service_type_name('1.2.3._mqtt._tcp.local.') == '_mqtt._tcp.local.' assert r.service_type_name('x.sub._http._tcp.local.') == '_http._tcp.local.' assert ( r.service_type_name('6d86f882b90facee9170ad3439d72a4d6ee9f511._zget._http._tcp.local.') == '_http._tcp.local.' ) def test_good_instance_names_without_protocol(self): good_names_to_try = ( "Rachio-C73233.local.", 'YeelightColorBulb-3AFD.local.', 'YeelightTunableBulb-7220.local.', "AlexanderHomeAssistant 74651D.local.", 'iSmartGate-152.local.', 'MyQ-FGA.local.', 'lutron-02c4392a.local.', 'WICED-hap-3E2734.local.', 'MyHost.local.', 'MyHost.sub.local.', ) for name in good_names_to_try: assert r.service_type_name(name, strict=False) == 'local.' for name in good_names_to_try: # Raises without strict=False self.assertRaises(r.BadTypeInNameException, r.service_type_name, name) def test_bad_types(self): bad_names_to_try = ( '._x._tcp.local.', 'a' * 64 + '._sub._http._tcp.local.', 'a' * 62 + 'â._sub._http._tcp.local.', ) for name in bad_names_to_try: self.assertRaises(r.BadTypeInNameException, r.service_type_name, name) def test_bad_sub_types(self): bad_names_to_try = ( '_sub._http._tcp.local.', '._sub._http._tcp.local.', '\x7f._sub._http._tcp.local.', '\x1f._sub._http._tcp.local.', ) for name in bad_names_to_try: self.assertRaises(r.BadTypeInNameException, r.service_type_name, name) def test_good_service_names(self): good_names_to_try = ( ('_x._tcp.local.', '_x._tcp.local.'), ('_x._udp.local.', '_x._udp.local.'), ('_12345-67890-abc._udp.local.', '_12345-67890-abc._udp.local.'), ('x._sub._http._tcp.local.', '_http._tcp.local.'), ('a' * 63 + '._sub._http._tcp.local.', '_http._tcp.local.'), ('a' * 61 + 'â._sub._http._tcp.local.', '_http._tcp.local.'), ) for name, result in good_names_to_try: assert r.service_type_name(name) == result assert r.service_type_name('_one_two._tcp.local.', strict=False) == '_one_two._tcp.local.' def test_invalid_addresses(self): type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" bad = (b'127.0.0.1', b'::1') for addr in bad: self.assertRaisesRegex( TypeError, 'Addresses must either ', ServiceInfo, type_, registration_name, port=80, addresses=[addr], ) 0707010000006C000081A40000000000000000000000016619D4CC00011DB3000000000000000000000000000000000000002F00000000python-zeroconf-0.132.2/tests/test_handlers.py#!/usr/bin/env python """ Unit tests for zeroconf._handlers """ import asyncio import logging import os import socket import time import unittest import unittest.mock from typing import List, cast from unittest.mock import patch import pytest import zeroconf as r from zeroconf import ServiceInfo, Zeroconf, const, current_time_millis from zeroconf._handlers.multicast_outgoing_queue import ( MulticastOutgoingQueue, construct_outgoing_multicast_answers, ) from zeroconf._utils.time import millis_to_seconds from zeroconf.asyncio import AsyncZeroconf from . import _clear_cache, _inject_response, has_working_ipv6 log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) class TestRegistrar(unittest.TestCase): def test_ttl(self): # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # service definition type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) nbr_answers = nbr_additionals = nbr_authorities = 0 def get_ttl(record_type): if expected_ttl is not None: return expected_ttl elif record_type in [const._TYPE_A, const._TYPE_SRV, const._TYPE_NSEC]: return const._DNS_HOST_TTL else: return const._DNS_OTHER_TTL def _process_outgoing_packet(out): """Sends an outgoing packet.""" nonlocal nbr_answers, nbr_additionals, nbr_authorities for answer, time_ in out.answers: nbr_answers += 1 assert answer.ttl == get_ttl(answer.type) for answer in out.additionals: nbr_additionals += 1 assert answer.ttl == get_ttl(answer.type) for answer in out.authorities: nbr_authorities += 1 assert answer.ttl == get_ttl(answer.type) # register service with default TTL expected_ttl = None for _ in range(3): _process_outgoing_packet(zc.generate_service_query(info)) zc.registry.async_add(info) for _ in range(3): _process_outgoing_packet(zc.generate_service_broadcast(info, None)) assert nbr_answers == 15 and nbr_additionals == 0 and nbr_authorities == 3 nbr_answers = nbr_additionals = nbr_authorities = 0 # query query = r.DNSOutgoing(const._FLAGS_QR_QUERY | const._FLAGS_AA) assert query.is_query() is True query.add_question(r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN)) query.add_question(r.DNSQuestion(info.name, const._TYPE_SRV, const._CLASS_IN)) query.add_question(r.DNSQuestion(info.name, const._TYPE_TXT, const._CLASS_IN)) query.add_question(r.DNSQuestion(info.server or info.name, const._TYPE_A, const._CLASS_IN)) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers _process_outgoing_packet(construct_outgoing_multicast_answers(question_answers.mcast_aggregate)) # The additonals should all be suppresed since they are all in the answers section # There will be one NSEC additional to indicate the lack of AAAA record # assert nbr_answers == 4 and nbr_additionals == 1 and nbr_authorities == 0 nbr_answers = nbr_additionals = nbr_authorities = 0 # unregister expected_ttl = 0 zc.registry.async_remove(info) for _ in range(3): _process_outgoing_packet(zc.generate_service_broadcast(info, 0)) assert nbr_answers == 15 and nbr_additionals == 0 and nbr_authorities == 0 nbr_answers = nbr_additionals = nbr_authorities = 0 expected_ttl = None for _ in range(3): _process_outgoing_packet(zc.generate_service_query(info)) zc.registry.async_add(info) # register service with custom TTL expected_ttl = const._DNS_HOST_TTL * 2 assert expected_ttl != const._DNS_HOST_TTL for _ in range(3): _process_outgoing_packet(zc.generate_service_broadcast(info, expected_ttl)) assert nbr_answers == 15 and nbr_additionals == 0 and nbr_authorities == 3 nbr_answers = nbr_additionals = nbr_authorities = 0 # query expected_ttl = None query = r.DNSOutgoing(const._FLAGS_QR_QUERY | const._FLAGS_AA) query.add_question(r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN)) query.add_question(r.DNSQuestion(info.name, const._TYPE_SRV, const._CLASS_IN)) query.add_question(r.DNSQuestion(info.name, const._TYPE_TXT, const._CLASS_IN)) query.add_question(r.DNSQuestion(info.server or info.name, const._TYPE_A, const._CLASS_IN)) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers _process_outgoing_packet(construct_outgoing_multicast_answers(question_answers.mcast_aggregate)) # There will be one NSEC additional to indicate the lack of AAAA record assert nbr_answers == 4 and nbr_additionals == 1 and nbr_authorities == 0 nbr_answers = nbr_additionals = nbr_authorities = 0 # unregister expected_ttl = 0 zc.registry.async_remove(info) for _ in range(3): _process_outgoing_packet(zc.generate_service_broadcast(info, 0)) assert nbr_answers == 15 and nbr_additionals == 0 and nbr_authorities == 0 nbr_answers = nbr_additionals = nbr_authorities = 0 zc.close() def test_name_conflicts(self): # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_homeassistant._tcp.local." name = "Home" registration_name = f"{name}.{type_}" info = ServiceInfo( type_, name=registration_name, server="random123.local.", addresses=[socket.inet_pton(socket.AF_INET, "1.2.3.4")], port=80, properties={"version": "1.0"}, ) zc.register_service(info) conflicting_info = ServiceInfo( type_, name=registration_name, server="random456.local.", addresses=[socket.inet_pton(socket.AF_INET, "4.5.6.7")], port=80, properties={"version": "1.0"}, ) with pytest.raises(r.NonUniqueNameException): zc.register_service(conflicting_info) zc.close() def test_register_and_lookup_type_by_uppercase_name(self): # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_mylowertype._tcp.local." name = "Home" registration_name = f"{name}.{type_}" info = ServiceInfo( type_, name=registration_name, server="random123.local.", addresses=[socket.inet_pton(socket.AF_INET, "1.2.3.4")], port=80, properties={"version": "1.0"}, ) zc.register_service(info) _clear_cache(zc) info = ServiceInfo(type_, registration_name) info.load_from_cache(zc) assert info.addresses == [] out = r.DNSOutgoing(const._FLAGS_QR_QUERY) out.add_question(r.DNSQuestion(type_.upper(), const._TYPE_PTR, const._CLASS_IN)) zc.send(out) time.sleep(1) info = ServiceInfo(type_, registration_name) info.load_from_cache(zc) assert info.addresses == [socket.inet_pton(socket.AF_INET, "1.2.3.4")] assert info.properties == {b"version": b"1.0"} zc.close() def test_ptr_optimization(): # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # service definition type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) # register zc.register_service(info) # Verify we won't respond for 1s with the same multicast query = r.DNSOutgoing(const._FLAGS_QR_QUERY) query.add_question(r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN)) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert not question_answers.mcast_aggregate # Since we sent the PTR in the last second, they # should end up in the delayed at least one second bucket assert question_answers.mcast_aggregate_last_second # Clear the cache to allow responding again _clear_cache(zc) # Verify we will now respond query = r.DNSOutgoing(const._FLAGS_QR_QUERY) query.add_question(r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN)) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert not question_answers.mcast_aggregate_last_second has_srv = has_txt = has_a = False nbr_additionals = 0 nbr_answers = len(question_answers.mcast_aggregate) additionals = set().union(*question_answers.mcast_aggregate.values()) for answer in additionals: nbr_additionals += 1 if answer.type == const._TYPE_SRV: has_srv = True elif answer.type == const._TYPE_TXT: has_txt = True elif answer.type == const._TYPE_A: has_a = True assert nbr_answers == 1 and nbr_additionals == 4 # There will be one NSEC additional to indicate the lack of AAAA record assert has_srv and has_txt and has_a # unregister zc.unregister_service(info) zc.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_any_query_for_ptr(): """Test that queries for ANY will return PTR records and the response is aggregated.""" zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_anyptr._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." ipv6_address = socket.inet_pton(socket.AF_INET6, "2001:db8::1") info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, server_name, addresses=[ipv6_address]) zc.registry.async_add(info) _clear_cache(zc) generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(type_, const._TYPE_ANY, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers mcast_answers = list(question_answers.mcast_aggregate) assert mcast_answers[0].name == type_ assert mcast_answers[0].alias == registration_name # type: ignore[attr-defined] # unregister zc.registry.async_remove(info) zc.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_aaaa_query(): """Test that queries for AAAA records work and should respond right away.""" zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_knownaaaservice._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." ipv6_address = socket.inet_pton(socket.AF_INET6, "2001:db8::1") info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, server_name, addresses=[ipv6_address]) zc.registry.async_add(info) generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(server_name, const._TYPE_AAAA, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers mcast_answers = list(question_answers.mcast_now) assert mcast_answers[0].address == ipv6_address # type: ignore[attr-defined] # unregister zc.registry.async_remove(info) zc.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_aaaa_query_upper_case(): """Test that queries for AAAA records work and should respond right away with an upper case name.""" zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_knownaaaservice._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." ipv6_address = socket.inet_pton(socket.AF_INET6, "2001:db8::1") info = ServiceInfo(type_, registration_name, 80, 0, 0, desc, server_name, addresses=[ipv6_address]) zc.registry.async_add(info) generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(server_name.upper(), const._TYPE_AAAA, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers mcast_answers = list(question_answers.mcast_now) assert mcast_answers[0].address == ipv6_address # type: ignore[attr-defined] # unregister zc.registry.async_remove(info) zc.close() @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_a_and_aaaa_record_fate_sharing(): """Test that queries for AAAA always return A records in the additionals and should respond right away.""" zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_a-and-aaaa-service._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." ipv6_address = socket.inet_pton(socket.AF_INET6, "2001:db8::1") ipv4_address = socket.inet_aton("10.0.1.2") info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[ipv6_address, ipv4_address] ) aaaa_record = info.dns_addresses(version=r.IPVersion.V6Only)[0] a_record = info.dns_addresses(version=r.IPVersion.V4Only)[0] zc.registry.async_add(info) # Test AAAA query generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(server_name, const._TYPE_AAAA, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers additionals = set().union(*question_answers.mcast_now.values()) assert aaaa_record in question_answers.mcast_now assert a_record in additionals assert len(question_answers.mcast_now) == 1 assert len(additionals) == 1 # Test A query generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(server_name, const._TYPE_A, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers additionals = set().union(*question_answers.mcast_now.values()) assert a_record in question_answers.mcast_now assert aaaa_record in additionals assert len(question_answers.mcast_now) == 1 assert len(additionals) == 1 # unregister zc.registry.async_remove(info) zc.close() def test_unicast_response(): """Ensure we send a unicast response when the source port is not the MDNS port.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # service definition type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) # register zc.registry.async_add(info) _clear_cache(zc) # query query = r.DNSOutgoing(const._FLAGS_QR_QUERY) query.add_question(r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN)) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], True ) assert question_answers for answers in (question_answers.ucast, question_answers.mcast_aggregate): has_srv = has_txt = has_a = has_aaaa = has_nsec = False nbr_additionals = 0 nbr_answers = len(answers) additionals = set().union(*answers.values()) for answer in additionals: nbr_additionals += 1 if answer.type == const._TYPE_SRV: has_srv = True elif answer.type == const._TYPE_TXT: has_txt = True elif answer.type == const._TYPE_A: has_a = True elif answer.type == const._TYPE_AAAA: has_aaaa = True elif answer.type == const._TYPE_NSEC: has_nsec = True # There will be one NSEC additional to indicate the lack of AAAA record assert nbr_answers == 1 and nbr_additionals == 4 assert has_srv and has_txt and has_a and has_nsec assert not has_aaaa # unregister zc.registry.async_remove(info) zc.close() @pytest.mark.asyncio async def test_probe_answered_immediately(): """Verify probes are responded to immediately.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # service definition type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) query.add_question(question) query.add_authorative_answer(info.dns_pointer()) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second assert question_answers.mcast_now query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True query.add_question(question) query.add_authorative_answer(info.dns_pointer()) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert question_answers.ucast assert question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second zc.close() @pytest.mark.asyncio async def test_probe_answered_immediately_with_uppercase_name(): """Verify probes are responded to immediately with an uppercase name.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # service definition type_ = "_test-srvc-type._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type.upper(), const._TYPE_PTR, const._CLASS_IN) query.add_question(question) query.add_authorative_answer(info.dns_pointer()) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second assert question_answers.mcast_now query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True query.add_question(question) query.add_authorative_answer(info.dns_pointer()) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert question_answers.ucast assert question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second zc.close() def test_qu_response(): """Handle multicast incoming with the QU bit set.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # service definition type_ = "_test-srvc-type._tcp.local." other_type_ = "_notthesame._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" registration_name2 = f"{name}.{other_type_}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) info2 = ServiceInfo( other_type_, registration_name2, 80, 0, 0, desc, "ash-other.local.", addresses=[socket.inet_aton("10.0.4.2")], ) # register zc.register_service(info) def _validate_complete_response(answers): has_srv = has_txt = has_a = has_aaaa = has_nsec = False nbr_answers = len(answers) additionals = set().union(*answers.values()) nbr_additionals = len(additionals) for answer in additionals: if answer.type == const._TYPE_SRV: has_srv = True elif answer.type == const._TYPE_TXT: has_txt = True elif answer.type == const._TYPE_A: has_a = True elif answer.type == const._TYPE_AAAA: has_aaaa = True elif answer.type == const._TYPE_NSEC: has_nsec = True assert nbr_answers == 1 and nbr_additionals == 4 assert has_srv and has_txt and has_a and has_nsec assert not has_aaaa # With QU should respond to only unicast when the answer has been recently multicast query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers _validate_complete_response(question_answers.ucast) assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second _clear_cache(zc) # With QU should respond to only multicast since the response hasn't been seen since 75% of the ttl query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate _validate_complete_response(question_answers.mcast_now) # With QU set and an authorative answer (probe) should respond to both unitcast and multicast since the response hasn't been seen since 75% of the ttl query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) query.add_authorative_answer(info2.dns_pointer()) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers _validate_complete_response(question_answers.ucast) _validate_complete_response(question_answers.mcast_now) _inject_response( zc, r.DNSIncoming(construct_outgoing_multicast_answers(question_answers.mcast_now).packets()[0]) ) # With the cache repopulated; should respond to only unicast when the answer has been recently multicast query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second _validate_complete_response(question_answers.ucast) # unregister zc.unregister_service(info) zc.close() def test_known_answer_supression(): zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_knownanswersv8._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) now = current_time_millis() _clear_cache(zc) # Test PTR supression generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(type_, const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(type_, const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) generated.add_answer_at_time(info.dns_pointer(), now) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second # Test A supression generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(server_name, const._TYPE_A, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(server_name, const._TYPE_A, const._CLASS_IN) generated.add_question(question) for dns_address in info.dns_addresses(): generated.add_answer_at_time(dns_address, now) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second # Test NSEC record returned when there is no AAAA record and we expectly ask generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(server_name, const._TYPE_AAAA, const._CLASS_IN) generated.add_question(question) for dns_address in info.dns_addresses(): generated.add_answer_at_time(dns_address, now) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast expected_nsec_record = cast(r.DNSNsec, list(question_answers.mcast_now)[0]) assert const._TYPE_A not in expected_nsec_record.rdtypes assert const._TYPE_AAAA in expected_nsec_record.rdtypes assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second # Test SRV supression generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(registration_name, const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(registration_name, const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) generated.add_answer_at_time(info.dns_service(), now) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second # Test TXT supression generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(registration_name, const._TYPE_TXT, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(registration_name, const._TYPE_TXT, const._CLASS_IN) generated.add_question(question) generated.add_answer_at_time(info.dns_text(), now) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second # unregister zc.registry.async_remove(info) zc.close() def test_multi_packet_known_answer_supression(): zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_handlermultis._tcp.local." name = "knownname" name2 = "knownname2" name3 = "knownname3" registration_name = f"{name}.{type_}" registration2_name = f"{name2}.{type_}" registration3_name = f"{name3}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." server_name2 = "ash-3.local." server_name3 = "ash-4.local." info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) info2 = ServiceInfo( type_, registration2_name, 80, 0, 0, desc, server_name2, addresses=[socket.inet_aton("10.0.1.2")] ) info3 = ServiceInfo( type_, registration3_name, 80, 0, 0, desc, server_name3, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) zc.registry.async_add(info2) zc.registry.async_add(info3) now = current_time_millis() _clear_cache(zc) # Test PTR supression generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(type_, const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) for _ in range(1000): # Add so many answers we end up with another packet generated.add_answer_at_time(info.dns_pointer(), now) generated.add_answer_at_time(info2.dns_pointer(), now) generated.add_answer_at_time(info3.dns_pointer(), now) packets = generated.packets() assert len(packets) > 1 question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second # unregister zc.registry.async_remove(info) zc.registry.async_remove(info2) zc.registry.async_remove(info3) zc.close() def test_known_answer_supression_service_type_enumeration_query(): zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_otherknown._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) type_2 = "_otherknown2._tcp.local." name = "knownname" registration_name2 = f"{name}.{type_2}" desc = {'path': '/~paulsm/'} server_name2 = "ash-3.local." info2 = ServiceInfo( type_2, registration_name2, 80, 0, 0, desc, server_name2, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info2) now = current_time_millis() _clear_cache(zc) # Test PTR supression generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(const._SERVICE_TYPE_ENUMERATION_NAME, const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(const._SERVICE_TYPE_ENUMERATION_NAME, const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) generated.add_answer_at_time( r.DNSPointer( const._SERVICE_TYPE_ENUMERATION_NAME, const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, type_, ), now, ) generated.add_answer_at_time( r.DNSPointer( const._SERVICE_TYPE_ENUMERATION_NAME, const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, type_2, ), now, ) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second # unregister zc.registry.async_remove(info) zc.registry.async_remove(info2) zc.close() def test_upper_case_enumeration_query(): zc = Zeroconf(interfaces=['127.0.0.1']) type_ = "_otherknown._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) type_2 = "_otherknown2._tcp.local." name = "knownname" registration_name2 = f"{name}.{type_2}" desc = {'path': '/~paulsm/'} server_name2 = "ash-3.local." info2 = ServiceInfo( type_2, registration_name2, 80, 0, 0, desc, server_name2, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info2) _clear_cache(zc) # Test PTR supression generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(const._SERVICE_TYPE_ENUMERATION_NAME.upper(), const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second # unregister zc.registry.async_remove(info) zc.registry.async_remove(info2) zc.close() def test_enumeration_query_with_no_registered_services(): zc = Zeroconf(interfaces=['127.0.0.1']) _clear_cache(zc) generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(const._SERVICE_TYPE_ENUMERATION_NAME.upper(), const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert not question_answers # unregister zc.close() # This test uses asyncio because it needs to access the cache directly # which is not threadsafe @pytest.mark.asyncio async def test_qu_response_only_sends_additionals_if_sends_answer(): """Test that a QU response does not send additionals unless it sends the answer as well.""" # instantiate a zeroconf instance aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf type_ = "_addtest1._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "ash-2.local." info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info) type_2 = "_addtest2._tcp.local." name = "knownname" registration_name2 = f"{name}.{type_2}" desc = {'path': '/~paulsm/'} server_name2 = "ash-3.local." info2 = ServiceInfo( type_2, registration_name2, 80, 0, 0, desc, server_name2, addresses=[socket.inet_aton("10.0.1.2")] ) zc.registry.async_add(info2) ptr_record = info.dns_pointer() # Add the PTR record to the cache zc.cache.async_add_records([ptr_record]) # Add the A record to the cache with 50% ttl remaining a_record = info.dns_addresses()[0] a_record.set_created_ttl(current_time_millis() - (a_record.ttl * 1000 / 2), a_record.ttl) assert not a_record.is_recent(current_time_millis()) info._dns_address_cache = None # we are mutating the record so clear the cache zc.cache.async_add_records([a_record]) # With QU should respond to only unicast when the answer has been recently multicast # even if the additional has not been recently multicast query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second additionals = set().union(*question_answers.ucast.values()) assert a_record in additionals assert ptr_record in question_answers.ucast # Remove the 50% A record and add a 100% A record zc.cache.async_remove_records([a_record]) a_record = info.dns_addresses()[0] assert a_record.is_recent(current_time_millis()) zc.cache.async_add_records([a_record]) # With QU should respond to only unicast when the answer has been recently multicast # even if the additional has not been recently multicast query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second additionals = set().union(*question_answers.ucast.values()) assert a_record in additionals assert ptr_record in question_answers.ucast # Remove the 100% PTR record and add a 50% PTR record zc.cache.async_remove_records([ptr_record]) ptr_record.set_created_ttl(current_time_millis() - (ptr_record.ttl * 1000 / 2), ptr_record.ttl) assert not ptr_record.is_recent(current_time_millis()) zc.cache.async_add_records([ptr_record]) # With QU should respond to only multicast since the has less # than 75% of its ttl remaining query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second additionals = set().union(*question_answers.mcast_now.values()) assert a_record in additionals assert info.dns_text() in additionals assert info.dns_service() in additionals assert ptr_record in question_answers.mcast_now # Ask 2 QU questions, with info the PTR is at 50%, with info2 the PTR is at 100% # We should get back a unicast reply for info2, but info should be multicasted since its within 75% of its TTL # With QU should respond to only multicast since the has less # than 75% of its ttl remaining query = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) question = r.DNSQuestion(info2.type, const._TYPE_PTR, const._CLASS_IN) question.unicast = True # Set the QU bit assert question.unicast is True query.add_question(question) zc.cache.async_add_records([info2.dns_pointer()]) # Add 100% TTL for info2 to the cache question_answers = zc.query_handler.async_response( [r.DNSIncoming(packet) for packet in query.packets()], False ) assert question_answers assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second mcast_now_additionals = set().union(*question_answers.mcast_now.values()) assert a_record in mcast_now_additionals assert info.dns_text() in mcast_now_additionals assert info.dns_addresses()[0] in mcast_now_additionals assert info.dns_pointer() in question_answers.mcast_now ucast_additionals = set().union(*question_answers.ucast.values()) assert info2.dns_pointer() in question_answers.ucast assert info2.dns_text() in ucast_additionals assert info2.dns_service() in ucast_additionals assert info2.dns_addresses()[0] in ucast_additionals # unregister zc.registry.async_remove(info) await aiozc.async_close() # This test uses asyncio because it needs to access the cache directly # which is not threadsafe @pytest.mark.asyncio async def test_cache_flush_bit(): """Test that the cache flush bit sets the TTL to one for matching records.""" # instantiate a zeroconf instance aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf type_ = "_cacheflush._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "server-uu1.local." info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) a_record = info.dns_addresses()[0] zc.cache.async_add_records([info.dns_pointer(), a_record, info.dns_text(), info.dns_service()]) info.addresses = [socket.inet_aton("10.0.1.5"), socket.inet_aton("10.0.1.6")] new_records = info.dns_addresses() for new_record in new_records: assert new_record.unique is True original_a_record = zc.cache.async_get_unique(a_record) # Do the run within 1s to verify the original record is not going to be expired out = r.DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA, multicast=True) for answer in new_records: out.add_answer_at_time(answer, 0) for packet in out.packets(): zc.record_manager.async_updates_from_response(r.DNSIncoming(packet)) assert zc.cache.async_get_unique(a_record) is original_a_record assert original_a_record is not None assert original_a_record.ttl != 1 for record in new_records: assert zc.cache.async_get_unique(record) is not None original_a_record.created = current_time_millis() - 1500 # Do the run within 1s to verify the original record is not going to be expired out = r.DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA, multicast=True) for answer in new_records: out.add_answer_at_time(answer, 0) for packet in out.packets(): zc.record_manager.async_updates_from_response(r.DNSIncoming(packet)) assert original_a_record.ttl == 1 for record in new_records: assert zc.cache.async_get_unique(record) is not None cached_records = [zc.cache.async_get_unique(record) for record in new_records] for cached_record in cached_records: assert cached_record is not None cached_record.created = current_time_millis() - 1500 fresh_address = socket.inet_aton("4.4.4.4") info.addresses = [fresh_address] # Do the run within 1s to verify the two new records get marked as expired out = r.DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA, multicast=True) for answer in info.dns_addresses(): out.add_answer_at_time(answer, 0) for packet in out.packets(): zc.record_manager.async_updates_from_response(r.DNSIncoming(packet)) for cached_record in cached_records: assert cached_record is not None assert cached_record.ttl == 1 for entry in zc.cache.async_all_by_details(server_name, const._TYPE_A, const._CLASS_IN): assert isinstance(entry, r.DNSAddress) if entry.address == fresh_address: assert entry.ttl > 1 else: assert entry.ttl == 1 # Wait for the ttl 1 records to expire await asyncio.sleep(1.1) loaded_info = r.ServiceInfo(type_, registration_name) loaded_info.load_from_cache(zc) assert loaded_info.addresses == info.addresses await aiozc.async_close() # This test uses asyncio because it needs to access the cache directly # which is not threadsafe @pytest.mark.asyncio async def test_record_update_manager_add_listener_callsback_existing_records(): """Test that the RecordUpdateManager will callback existing records.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc: Zeroconf = aiozc.zeroconf updated = [] class MyListener(r.RecordUpdateListener): """A RecordUpdateListener that does not implement update_records.""" def async_update_records(self, zc: 'Zeroconf', now: float, records: List[r.RecordUpdate]) -> None: """Update multiple records in one shot.""" updated.extend(records) type_ = "_cacheflush._tcp.local." name = "knownname" registration_name = f"{name}.{type_}" desc = {'path': '/~paulsm/'} server_name = "server-uu1.local." info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, server_name, addresses=[socket.inet_aton("10.0.1.2")] ) a_record = info.dns_addresses()[0] ptr_record = info.dns_pointer() zc.cache.async_add_records([ptr_record, a_record, info.dns_text(), info.dns_service()]) listener = MyListener() zc.add_listener( listener, [ r.DNSQuestion(type_, const._TYPE_PTR, const._CLASS_IN), r.DNSQuestion(server_name, const._TYPE_A, const._CLASS_IN), ], ) await asyncio.sleep(0) # flush out the call_soon_threadsafe assert {record.new for record in updated} == {ptr_record, a_record} # The old records should be None so we trigger Add events # in service browsers instead of Update events assert {record.old for record in updated} == {None} await aiozc.async_close() @pytest.mark.asyncio async def test_questions_query_handler_populates_the_question_history_from_qm_questions(): aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf now = current_time_millis() _clear_cache(zc) aiozc.zeroconf.registry.async_add( ServiceInfo( "_hap._tcp.local.", "other._hap._tcp.local.", 80, 0, 0, {"md": "known"}, "ash-2.local.", addresses=[socket.inet_aton("1.2.3.4")], ) ) services = aiozc.zeroconf.registry.async_get_infos_type("_hap._tcp.local.") assert len(services) == 1 generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion("_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN) question.unicast = False known_answer = r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, 10000, 'known-to-other._hap._tcp.local.' ) generated.add_question(question) generated.add_answer_at_time(known_answer, 0) now = r.current_time_millis() packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert not question_answers.ucast assert not question_answers.mcast_now assert question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second assert zc.question_history.suppresses(question, now, {known_answer}) await aiozc.async_close() @pytest.mark.asyncio async def test_questions_query_handler_does_not_put_qu_questions_in_history(): aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf now = current_time_millis() _clear_cache(zc) info = ServiceInfo( "_hap._tcp.local.", "qu._hap._tcp.local.", 80, 0, 0, {"md": "known"}, "ash-2.local.", addresses=[socket.inet_aton("1.2.3.4")], ) aiozc.zeroconf.registry.async_add(info) generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion("_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN) question.unicast = True known_answer = r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, 10000, 'notqu._hap._tcp.local.' ) generated.add_question(question) generated.add_answer_at_time(known_answer, 0) now = r.current_time_millis() packets = generated.packets() question_answers = zc.query_handler.async_response([r.DNSIncoming(packet) for packet in packets], False) assert question_answers assert "qu._hap._tcp.local." in str(question_answers) assert not question_answers.ucast # has not multicast recently assert question_answers.mcast_now assert not question_answers.mcast_aggregate assert not question_answers.mcast_aggregate_last_second assert not zc.question_history.suppresses(question, now, {known_answer}) await aiozc.async_close() @pytest.mark.asyncio async def test_guard_against_low_ptr_ttl(): """Ensure we enforce a minimum for PTR record ttls to avoid excessive refresh queries from ServiceBrowsers. Some poorly designed IoT devices can set excessively low PTR TTLs would will cause ServiceBrowsers to flood the network with excessive refresh queries. """ aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf # Apple uses a 15s minimum TTL, however we do not have the same # level of rate limit and safe guards so we use 1/4 of the recommended value answer_with_low_ttl = r.DNSPointer( "myservicelow_tcp._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, 2, 'low.local.', ) answer_with_normal_ttl = r.DNSPointer( "myservicelow_tcp._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, 'normal.local.', ) good_bye_answer = r.DNSPointer( "myservicelow_tcp._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, 0, 'goodbye.local.', ) # TTL should be adjusted to a safe value response = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) response.add_answer_at_time(answer_with_low_ttl, 0) response.add_answer_at_time(answer_with_normal_ttl, 0) response.add_answer_at_time(good_bye_answer, 0) incoming = r.DNSIncoming(response.packets()[0]) zc.record_manager.async_updates_from_response(incoming) incoming_answer_low = zc.cache.async_get_unique(answer_with_low_ttl) assert incoming_answer_low is not None assert incoming_answer_low.ttl == const._DNS_PTR_MIN_TTL incoming_answer_normal = zc.cache.async_get_unique(answer_with_normal_ttl) assert incoming_answer_normal is not None assert incoming_answer_normal.ttl == const._DNS_OTHER_TTL assert zc.cache.async_get_unique(good_bye_answer) is None await aiozc.async_close() @pytest.mark.asyncio async def test_duplicate_goodbye_answers_in_packet(): """Ensure we do not throw an exception when there are duplicate goodbye records in a packet.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc = aiozc.zeroconf answer_with_normal_ttl = r.DNSPointer( "myservicelow_tcp._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, 'host.local.', ) good_bye_answer = r.DNSPointer( "myservicelow_tcp._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, 0, 'host.local.', ) response = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) response.add_answer_at_time(answer_with_normal_ttl, 0) incoming = r.DNSIncoming(response.packets()[0]) zc.record_manager.async_updates_from_response(incoming) response = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) response.add_answer_at_time(good_bye_answer, 0) response.add_answer_at_time(good_bye_answer, 0) incoming = r.DNSIncoming(response.packets()[0]) zc.record_manager.async_updates_from_response(incoming) await aiozc.async_close() @pytest.mark.asyncio async def test_response_aggregation_timings(run_isolated): """Verify multicast respones are aggregated.""" type_ = "_mservice._tcp.local." type_2 = "_mservice2._tcp.local." type_3 = "_mservice3._tcp.local." aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.zeroconf.async_wait_for_start() name = "xxxyyy" registration_name = f"{name}.{type_}" registration_name2 = f"{name}.{type_2}" registration_name3 = f"{name}.{type_3}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")] ) info2 = ServiceInfo( type_2, registration_name2, 80, 0, 0, desc, "ash-4.local.", addresses=[socket.inet_aton("10.0.1.3")] ) info3 = ServiceInfo( type_3, registration_name3, 80, 0, 0, desc, "ash-4.local.", addresses=[socket.inet_aton("10.0.1.3")] ) aiozc.zeroconf.registry.async_add(info) aiozc.zeroconf.registry.async_add(info2) aiozc.zeroconf.registry.async_add(info3) query = r.DNSOutgoing(const._FLAGS_QR_QUERY, multicast=True) question = r.DNSQuestion(info.type, const._TYPE_PTR, const._CLASS_IN) query.add_question(question) query2 = r.DNSOutgoing(const._FLAGS_QR_QUERY, multicast=True) question2 = r.DNSQuestion(info2.type, const._TYPE_PTR, const._CLASS_IN) query2.add_question(question2) query3 = r.DNSOutgoing(const._FLAGS_QR_QUERY, multicast=True) question3 = r.DNSQuestion(info3.type, const._TYPE_PTR, const._CLASS_IN) query3.add_question(question3) query4 = r.DNSOutgoing(const._FLAGS_QR_QUERY, multicast=True) query4.add_question(question) query4.add_question(question2) zc = aiozc.zeroconf protocol = zc.engine.protocols[0] with patch.object(aiozc.zeroconf, "async_send") as send_mock: protocol.datagram_received(query.packets()[0], ('127.0.0.1', const._MDNS_PORT)) protocol.datagram_received(query2.packets()[0], ('127.0.0.1', const._MDNS_PORT)) protocol.datagram_received(query.packets()[0], ('127.0.0.1', const._MDNS_PORT)) await asyncio.sleep(0.7) # Should aggregate into a single answer with up to a 500ms + 120ms delay calls = send_mock.mock_calls assert len(calls) == 1 outgoing = send_mock.call_args[0][0] incoming = r.DNSIncoming(outgoing.packets()[0]) zc.record_manager.async_updates_from_response(incoming) assert info.dns_pointer() in incoming.answers() assert info2.dns_pointer() in incoming.answers() send_mock.reset_mock() protocol.datagram_received(query3.packets()[0], ('127.0.0.1', const._MDNS_PORT)) await asyncio.sleep(0.3) # Should send within 120ms since there are no other # answers to aggregate with calls = send_mock.mock_calls assert len(calls) == 1 outgoing = send_mock.call_args[0][0] incoming = r.DNSIncoming(outgoing.packets()[0]) zc.record_manager.async_updates_from_response(incoming) assert info3.dns_pointer() in incoming.answers() send_mock.reset_mock() # Because the response was sent in the last second we need to make # sure the next answer is delayed at least a second aiozc.zeroconf.engine.protocols[0].datagram_received( query4.packets()[0], ('127.0.0.1', const._MDNS_PORT) ) await asyncio.sleep(0.5) # After 0.5 seconds it should not have been sent # Protect the network against excessive packet flooding # https://datatracker.ietf.org/doc/html/rfc6762#section-14 calls = send_mock.mock_calls assert len(calls) == 0 send_mock.reset_mock() await asyncio.sleep(1.2) calls = send_mock.mock_calls assert len(calls) == 1 outgoing = send_mock.call_args[0][0] incoming = r.DNSIncoming(outgoing.packets()[0]) assert info.dns_pointer() in incoming.answers() await aiozc.async_close() @pytest.mark.asyncio async def test_response_aggregation_timings_multiple(run_isolated, disable_duplicate_packet_suppression): """Verify multicast responses that are aggregated do not take longer than 620ms to send. 620ms is the maximum random delay of 120ms and 500ms additional for aggregation.""" type_2 = "_mservice2._tcp.local." aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) await aiozc.zeroconf.async_wait_for_start() name = "xxxyyy" registration_name2 = f"{name}.{type_2}" desc = {'path': '/~paulsm/'} info2 = ServiceInfo( type_2, registration_name2, 80, 0, 0, desc, "ash-4.local.", addresses=[socket.inet_aton("10.0.1.3")] ) aiozc.zeroconf.registry.async_add(info2) query2 = r.DNSOutgoing(const._FLAGS_QR_QUERY, multicast=True) question2 = r.DNSQuestion(info2.type, const._TYPE_PTR, const._CLASS_IN) query2.add_question(question2) zc = aiozc.zeroconf protocol = zc.engine.protocols[0] with patch.object(aiozc.zeroconf, "async_send") as send_mock: send_mock.reset_mock() protocol.datagram_received(query2.packets()[0], ('127.0.0.1', const._MDNS_PORT)) protocol.last_time = 0 # manually reset the last time to avoid duplicate packet suppression await asyncio.sleep(0.2) calls = send_mock.mock_calls assert len(calls) == 1 outgoing = send_mock.call_args[0][0] incoming = r.DNSIncoming(outgoing.packets()[0]) zc.record_manager.async_updates_from_response(incoming) assert info2.dns_pointer() in incoming.answers() send_mock.reset_mock() protocol.datagram_received(query2.packets()[0], ('127.0.0.1', const._MDNS_PORT)) protocol.last_time = 0 # manually reset the last time to avoid duplicate packet suppression await asyncio.sleep(1.2) calls = send_mock.mock_calls assert len(calls) == 1 outgoing = send_mock.call_args[0][0] incoming = r.DNSIncoming(outgoing.packets()[0]) zc.record_manager.async_updates_from_response(incoming) assert info2.dns_pointer() in incoming.answers() send_mock.reset_mock() protocol.datagram_received(query2.packets()[0], ('127.0.0.1', const._MDNS_PORT)) protocol.last_time = 0 # manually reset the last time to avoid duplicate packet suppression protocol.datagram_received(query2.packets()[0], ('127.0.0.1', const._MDNS_PORT)) protocol.last_time = 0 # manually reset the last time to avoid duplicate packet suppression # The delay should increase with two packets and # 900ms is beyond the maximum aggregation delay # when there is no network protection delay await asyncio.sleep(0.9) calls = send_mock.mock_calls assert len(calls) == 0 # 1000ms (1s network protection delays) # - 900ms (already slept) # + 120ms (maximum random delay) # + 200ms (maximum protected aggregation delay) # + 20ms (execution time) await asyncio.sleep(millis_to_seconds(1000 - 900 + 120 + 200 + 20)) calls = send_mock.mock_calls assert len(calls) == 1 outgoing = send_mock.call_args[0][0] incoming = r.DNSIncoming(outgoing.packets()[0]) zc.record_manager.async_updates_from_response(incoming) assert info2.dns_pointer() in incoming.answers() @pytest.mark.asyncio async def test_response_aggregation_random_delay(): """Verify the random delay for outgoing multicast will coalesce into a single group When the random delay is shorter than the last outgoing group, the groups should be combined. """ type_ = "_mservice._tcp.local." type_2 = "_mservice2._tcp.local." type_3 = "_mservice3._tcp.local." type_4 = "_mservice4._tcp.local." type_5 = "_mservice5._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" registration_name2 = f"{name}.{type_2}" registration_name3 = f"{name}.{type_3}" registration_name4 = f"{name}.{type_4}" registration_name5 = f"{name}.{type_5}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-1.local.", addresses=[socket.inet_aton("10.0.1.2")] ) info2 = ServiceInfo( type_2, registration_name2, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.3")] ) info3 = ServiceInfo( type_3, registration_name3, 80, 0, 0, desc, "ash-3.local.", addresses=[socket.inet_aton("10.0.1.2")] ) info4 = ServiceInfo( type_4, registration_name4, 80, 0, 0, desc, "ash-4.local.", addresses=[socket.inet_aton("10.0.1.2")] ) info5 = ServiceInfo( type_5, registration_name5, 80, 0, 0, desc, "ash-5.local.", addresses=[socket.inet_aton("10.0.1.2")] ) mocked_zc = unittest.mock.MagicMock() outgoing_queue = MulticastOutgoingQueue(mocked_zc, 0, 500) now = current_time_millis() outgoing_queue._multicast_delay_random_min = 500 outgoing_queue._multicast_delay_random_max = 600 outgoing_queue.async_add(now, {info.dns_pointer(): set()}) # The second group should always be coalesced into first group since it will always come before outgoing_queue._multicast_delay_random_min = 300 outgoing_queue._multicast_delay_random_max = 400 outgoing_queue.async_add(now, {info2.dns_pointer(): set()}) # The third group should always be coalesced into first group since it will always come before outgoing_queue._multicast_delay_random_min = 100 outgoing_queue._multicast_delay_random_max = 200 outgoing_queue.async_add(now, {info3.dns_pointer(): set(), info4.dns_pointer(): set()}) assert len(outgoing_queue.queue) == 1 assert info.dns_pointer() in outgoing_queue.queue[0].answers assert info2.dns_pointer() in outgoing_queue.queue[0].answers assert info3.dns_pointer() in outgoing_queue.queue[0].answers assert info4.dns_pointer() in outgoing_queue.queue[0].answers # The forth group should not be coalesced because its scheduled after the last group in the queue outgoing_queue._multicast_delay_random_min = 700 outgoing_queue._multicast_delay_random_max = 800 outgoing_queue.async_add(now, {info5.dns_pointer(): set()}) assert len(outgoing_queue.queue) == 2 assert info.dns_pointer() not in outgoing_queue.queue[1].answers assert info2.dns_pointer() not in outgoing_queue.queue[1].answers assert info3.dns_pointer() not in outgoing_queue.queue[1].answers assert info4.dns_pointer() not in outgoing_queue.queue[1].answers assert info5.dns_pointer() in outgoing_queue.queue[1].answers @pytest.mark.asyncio async def test_future_answers_are_removed_on_send(): """Verify any future answers scheduled to be sent are removed when we send.""" type_ = "_mservice._tcp.local." type_2 = "_mservice2._tcp.local." name = "xxxyyy" registration_name = f"{name}.{type_}" registration_name2 = f"{name}.{type_2}" desc = {'path': '/~paulsm/'} info = ServiceInfo( type_, registration_name, 80, 0, 0, desc, "ash-1.local.", addresses=[socket.inet_aton("10.0.1.2")] ) info2 = ServiceInfo( type_2, registration_name2, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.3")] ) mocked_zc = unittest.mock.MagicMock() outgoing_queue = MulticastOutgoingQueue(mocked_zc, 0, 0) now = current_time_millis() outgoing_queue._multicast_delay_random_min = 1 outgoing_queue._multicast_delay_random_max = 1 outgoing_queue.async_add(now, {info.dns_pointer(): set()}) assert len(outgoing_queue.queue) == 1 outgoing_queue._multicast_delay_random_min = 2 outgoing_queue._multicast_delay_random_max = 2 outgoing_queue.async_add(now, {info.dns_pointer(): set()}) assert len(outgoing_queue.queue) == 2 outgoing_queue._multicast_delay_random_min = 1000 outgoing_queue._multicast_delay_random_max = 1000 outgoing_queue.async_add(now, {info2.dns_pointer(): set()}) outgoing_queue.async_add(now, {info.dns_pointer(): set()}) assert len(outgoing_queue.queue) == 3 await asyncio.sleep(0.1) outgoing_queue.async_ready() assert len(outgoing_queue.queue) == 1 # The answer should get removed because we just sent it assert info.dns_pointer() not in outgoing_queue.queue[0].answers # But the one we have not sent yet shoudl still go out later assert info2.dns_pointer() in outgoing_queue.queue[0].answers @pytest.mark.asyncio async def test_add_listener_warns_when_not_using_record_update_listener(caplog): """Log when a listener is added that is not using RecordUpdateListener as a base class.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc: Zeroconf = aiozc.zeroconf updated = [] class MyListener: """A RecordUpdateListener that does not implement update_records.""" def async_update_records(self, zc: 'Zeroconf', now: float, records: List[r.RecordUpdate]) -> None: """Update multiple records in one shot.""" updated.extend(records) zc.add_listener(MyListener(), None) # type: ignore[arg-type] await asyncio.sleep(0) # flush out any call soons assert ( "listeners passed to async_add_listener must inherit from RecordUpdateListener" in caplog.text or "TypeError: Argument \'listener\' has incorrect type" in caplog.text ) await aiozc.async_close() @pytest.mark.asyncio async def test_async_updates_iteration_safe(): """Ensure we can safely iterate over the async_updates.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc: Zeroconf = aiozc.zeroconf updated = [] good_bye_answer = r.DNSPointer( "myservicelow_tcp._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, 0, 'goodbye.local.', ) class OtherListener(r.RecordUpdateListener): """A RecordUpdateListener that does not implement update_records.""" def async_update_records(self, zc: 'Zeroconf', now: float, records: List[r.RecordUpdate]) -> None: """Update multiple records in one shot.""" updated.extend(records) other = OtherListener() class ListenerThatAddsListener(r.RecordUpdateListener): """A RecordUpdateListener that does not implement update_records.""" def async_update_records(self, zc: 'Zeroconf', now: float, records: List[r.RecordUpdate]) -> None: """Update multiple records in one shot.""" updated.extend(records) zc.async_add_listener(other, None) zc.async_add_listener(ListenerThatAddsListener(), None) await asyncio.sleep(0) # flush out any call soons # This should not raise RuntimeError: set changed size during iteration zc.record_manager.async_updates( now=current_time_millis(), records=[r.RecordUpdate(good_bye_answer, None)] ) assert len(updated) == 1 await aiozc.async_close() @pytest.mark.asyncio async def test_async_updates_complete_iteration_safe(): """Ensure we can safely iterate over the async_updates_complete.""" aiozc = AsyncZeroconf(interfaces=['127.0.0.1']) zc: Zeroconf = aiozc.zeroconf class OtherListener(r.RecordUpdateListener): """A RecordUpdateListener that does not implement update_records.""" def async_update_records_complete(self) -> None: """Update multiple records in one shot.""" other = OtherListener() class ListenerThatAddsListener(r.RecordUpdateListener): """A RecordUpdateListener that does not implement update_records.""" def async_update_records_complete(self) -> None: """Update multiple records in one shot.""" zc.async_add_listener(other, None) zc.async_add_listener(ListenerThatAddsListener(), None) await asyncio.sleep(0) # flush out any call soons # This should not raise RuntimeError: set changed size during iteration zc.record_manager.async_updates_complete(False) await aiozc.async_close() 0707010000006D000081A40000000000000000000000016619D4CC00000A5E000000000000000000000000000000000000002E00000000python-zeroconf-0.132.2/tests/test_history.py#!/usr/bin/env python """Unit tests for _history.py.""" from typing import Set import zeroconf as r import zeroconf.const as const from zeroconf._history import QuestionHistory def test_question_suppression(): history = QuestionHistory() question = r.DNSQuestion("_hap._tcp._local.", const._TYPE_PTR, const._CLASS_IN) now = r.current_time_millis() other_known_answers: Set[r.DNSRecord] = { r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, 10000, 'known-to-other._hap._tcp.local.' ) } our_known_answers: Set[r.DNSRecord] = { r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, 10000, 'known-to-us._hap._tcp.local.' ) } history.add_question_at_time(question, now, other_known_answers) # Verify the question is suppressed if the known answers are the same assert history.suppresses(question, now, other_known_answers) # Verify the question is suppressed if we know the answer to all the known answers assert history.suppresses(question, now, other_known_answers | our_known_answers) # Verify the question is not suppressed if our known answers do no include the ones in the last question assert not history.suppresses(question, now, set()) # Verify the question is not suppressed if our known answers do no include the ones in the last question assert not history.suppresses(question, now, our_known_answers) # Verify the question is no longer suppressed after 1s assert not history.suppresses(question, now + 1000, other_known_answers) def test_question_expire(): history = QuestionHistory() now = r.current_time_millis() question = r.DNSQuestion("_hap._tcp._local.", const._TYPE_PTR, const._CLASS_IN) other_known_answers: Set[r.DNSRecord] = { r.DNSPointer( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN, 10000, 'known-to-other._hap._tcp.local.', created=now, ) } history.add_question_at_time(question, now, other_known_answers) # Verify the question is suppressed if the known answers are the same assert history.suppresses(question, now, other_known_answers) history.async_expire(now) # Verify the question is suppressed if the known answers are the same since the cache hasn't expired assert history.suppresses(question, now, other_known_answers) history.async_expire(now + 1000) # Verify the question not longer suppressed since the cache has expired assert not history.suppresses(question, now, other_known_answers) 0707010000006E000081A40000000000000000000000016619D4CC000019F0000000000000000000000000000000000000002B00000000python-zeroconf-0.132.2/tests/test_init.py#!/usr/bin/env python """ Unit tests for zeroconf.py """ import logging import socket import time import unittest import unittest.mock from unittest.mock import patch import zeroconf as r from zeroconf import ServiceInfo, Zeroconf, const from . import _inject_responses log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) class Names(unittest.TestCase): def test_long_name(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) question = r.DNSQuestion( "this.is.a.very.long.name.with.lots.of.parts.in.it.local.", const._TYPE_SRV, const._CLASS_IN ) generated.add_question(question) r.DNSIncoming(generated.packets()[0]) def test_exceedingly_long_name(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) name = "%slocal." % ("part." * 1000) question = r.DNSQuestion(name, const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) r.DNSIncoming(generated.packets()[0]) def test_extra_exceedingly_long_name(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) name = "%slocal." % ("part." * 4000) question = r.DNSQuestion(name, const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) r.DNSIncoming(generated.packets()[0]) def test_exceedingly_long_name_part(self): name = "%s.local." % ("a" * 1000) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) question = r.DNSQuestion(name, const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) self.assertRaises(r.NamePartTooLongException, generated.packets) def test_same_name(self): name = "paired.local." generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) question = r.DNSQuestion(name, const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) generated.add_question(question) r.DNSIncoming(generated.packets()[0]) def test_verify_name_change_with_lots_of_names(self): # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) # create a bunch of servers type_ = "_my-service._tcp.local." name = 'a wonderful service' server_count = 300 self.generate_many_hosts(zc, type_, name, server_count) # verify that name changing works self.verify_name_change(zc, type_, name, server_count) zc.close() def test_large_packet_exception_log_handling(self): """Verify we downgrade debug after warning.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) with patch('zeroconf._logger.log.warning') as mocked_log_warn, patch( 'zeroconf._logger.log.debug' ) as mocked_log_debug: # now that we have a long packet in our possession, let's verify the # exception handling. out = r.DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA) out.data.append(b'\0' * 10000) # mock the zeroconf logger and check for the correct logging backoff call_counts = mocked_log_warn.call_count, mocked_log_debug.call_count # try to send an oversized packet zc.send(out) assert mocked_log_warn.call_count == call_counts[0] zc.send(out) assert mocked_log_warn.call_count == call_counts[0] # mock the zeroconf logger and check for the correct logging backoff call_counts = mocked_log_warn.call_count, mocked_log_debug.call_count # force receive on oversized packet zc.send(out, const._MDNS_ADDR, const._MDNS_PORT) zc.send(out, const._MDNS_ADDR, const._MDNS_PORT) time.sleep(0.3) r.log.debug( 'warn %d debug %d was %s', mocked_log_warn.call_count, mocked_log_debug.call_count, call_counts, ) assert mocked_log_debug.call_count > call_counts[0] # close our zeroconf which will close the sockets zc.close() def verify_name_change(self, zc, type_, name, number_hosts): desc = {'path': '/~paulsm/'} info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) # verify name conflict self.assertRaises(r.NonUniqueNameException, zc.register_service, info_service) # verify no name conflict https://tools.ietf.org/html/rfc6762#section-6.6 zc.register_service(info_service, cooperating_responders=True) # Create a new object since allow_name_change will mutate the # original object and then we will have the wrong service # in the registry info_service2 = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) zc.register_service(info_service2, allow_name_change=True) assert info_service2.name.split('.')[0] == '%s-%d' % (name, number_hosts + 1) def generate_many_hosts(self, zc, type_, name, number_hosts): block_size = 25 number_hosts = int((number_hosts - 1) / block_size + 1) * block_size out = r.DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA) for i in range(1, number_hosts + 1): next_name = name if i == 1 else '%s-%d' % (name, i) self.generate_host(out, next_name, type_) _inject_responses(zc, [r.DNSIncoming(packet) for packet in out.packets()]) @staticmethod def generate_host(out, host_name, type_): name = '.'.join((host_name, type_)) out.add_answer_at_time( r.DNSPointer(type_, const._TYPE_PTR, const._CLASS_IN, const._DNS_OTHER_TTL, name), 0 ) out.add_answer_at_time( r.DNSService( type_, const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, 80, name, ), 0, ) 0707010000006F000081A40000000000000000000000016619D4CC000020D5000000000000000000000000000000000000002F00000000python-zeroconf-0.132.2/tests/test_listener.py#!/usr/bin/env python """ Unit tests for zeroconf._listener """ import logging import unittest import unittest.mock from typing import Tuple, Union from unittest.mock import MagicMock, patch import zeroconf as r from zeroconf import ( ServiceInfo, Zeroconf, _engine, _listener, const, current_time_millis, ) from zeroconf._protocol import outgoing from zeroconf._protocol.incoming import DNSIncoming from . import QuestionHistoryWithoutSuppression log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) def test_guard_against_oversized_packets(): """Ensure we do not process oversized packets. These packets can quickly overwhelm the system. """ zc = Zeroconf(interfaces=['127.0.0.1']) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) for i in range(5000): generated.add_answer_at_time( r.DNSText( "packet{i}.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 500, b'path=/~paulsm/', ), 0, ) try: # We are patching to generate an oversized packet with patch.object(outgoing, "_MAX_MSG_ABSOLUTE", 100000), patch.object( outgoing, "_MAX_MSG_TYPICAL", 100000 ): over_sized_packet = generated.packets()[0] assert len(over_sized_packet) > const._MAX_MSG_ABSOLUTE except AttributeError: # cannot patch with cython zc.close() return generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) okpacket_record = r.DNSText( "okpacket.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 500, b'path=/~paulsm/', ) generated.add_answer_at_time( okpacket_record, 0, ) ok_packet = generated.packets()[0] # We cannot test though the network interface as some operating systems # will guard against the oversized packet and we won't see it. listener = _listener.AsyncListener(zc) listener.transport = unittest.mock.MagicMock() listener.datagram_received(ok_packet, ('127.0.0.1', const._MDNS_PORT)) assert zc.cache.async_get_unique(okpacket_record) is not None listener.datagram_received(over_sized_packet, ('127.0.0.1', const._MDNS_PORT)) assert ( zc.cache.async_get_unique( r.DNSText( "packet0.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 500, b'path=/~paulsm/', ) ) is None ) logging.getLogger('zeroconf').setLevel(logging.INFO) listener.datagram_received(over_sized_packet, ('::1', const._MDNS_PORT, 1, 1)) assert ( zc.cache.async_get_unique( r.DNSText( "packet0.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 500, b'path=/~paulsm/', ) ) is None ) zc.close() def test_guard_against_duplicate_packets(): """Ensure we do not process duplicate packets. These packets can quickly overwhelm the system. """ zc = Zeroconf(interfaces=['127.0.0.1']) zc.registry.async_add( ServiceInfo("_http._tcp.local.", "Test._http._tcp.local.", server="Test._http._tcp.local.", port=4) ) zc.question_history = QuestionHistoryWithoutSuppression() class SubListener(_listener.AsyncListener): def handle_query_or_defer( self, msg: DNSIncoming, addr: str, port: int, transport: _engine._WrappedTransport, v6_flow_scope: Union[Tuple[()], Tuple[int, int]] = (), ) -> None: """Handle a query or defer it for later processing.""" super().handle_query_or_defer(msg, addr, port, transport, v6_flow_scope) listener = SubListener(zc) listener.transport = MagicMock() query = r.DNSOutgoing(const._FLAGS_QR_QUERY, multicast=True) question = r.DNSQuestion("x._http._tcp.local.", const._TYPE_PTR, const._CLASS_IN) query.add_question(question) packet_with_qm_question = query.packets()[0] query3 = r.DNSOutgoing(const._FLAGS_QR_QUERY, multicast=True) question3 = r.DNSQuestion("x._ay._tcp.local.", const._TYPE_PTR, const._CLASS_IN) query3.add_question(question3) packet_with_qm_question2 = query3.packets()[0] query2 = r.DNSOutgoing(const._FLAGS_QR_QUERY, multicast=True) question2 = r.DNSQuestion("x._http._tcp.local.", const._TYPE_PTR, const._CLASS_IN) question2.unicast = True query2.add_question(question2) packet_with_qu_question = query2.packets()[0] addrs = ("1.2.3.4", 43) with patch.object(listener, "handle_query_or_defer") as _handle_query_or_defer: start_time = current_time_millis() listener._process_datagram_at_time( False, len(packet_with_qm_question), start_time, packet_with_qm_question, addrs ) _handle_query_or_defer.assert_called_once() _handle_query_or_defer.reset_mock() # Now call with the same packet again and handle_query_or_defer should not fire listener._process_datagram_at_time( False, len(packet_with_qm_question), start_time, packet_with_qm_question, addrs ) _handle_query_or_defer.assert_not_called() _handle_query_or_defer.reset_mock() # Now walk time forward 1100 milliseconds new_time = start_time + 1100 # Now call with the same packet again and handle_query_or_defer should fire listener._process_datagram_at_time( False, len(packet_with_qm_question), new_time, packet_with_qm_question, addrs ) _handle_query_or_defer.assert_called_once() _handle_query_or_defer.reset_mock() # Now call with the different packet and handle_query_or_defer should fire listener._process_datagram_at_time( False, len(packet_with_qm_question2), new_time, packet_with_qm_question2, addrs ) _handle_query_or_defer.assert_called_once() _handle_query_or_defer.reset_mock() # Now call with the different packet and handle_query_or_defer should fire listener._process_datagram_at_time( False, len(packet_with_qm_question), new_time, packet_with_qm_question, addrs ) _handle_query_or_defer.assert_called_once() _handle_query_or_defer.reset_mock() # Now call with the different packet with qu question and handle_query_or_defer should fire listener._process_datagram_at_time( False, len(packet_with_qu_question), new_time, packet_with_qu_question, addrs ) _handle_query_or_defer.assert_called_once() _handle_query_or_defer.reset_mock() # Now call again with the same packet that has a qu question and handle_query_or_defer should fire listener._process_datagram_at_time( False, len(packet_with_qu_question), new_time, packet_with_qu_question, addrs ) _handle_query_or_defer.assert_called_once() _handle_query_or_defer.reset_mock() log.setLevel(logging.WARNING) # Call with the QM packet again listener._process_datagram_at_time( False, len(packet_with_qm_question), new_time, packet_with_qm_question, addrs ) _handle_query_or_defer.assert_called_once() _handle_query_or_defer.reset_mock() # Now call with the same packet again and handle_query_or_defer should not fire listener._process_datagram_at_time( False, len(packet_with_qm_question), new_time, packet_with_qm_question, addrs ) _handle_query_or_defer.assert_not_called() _handle_query_or_defer.reset_mock() # Now call with garbage listener._process_datagram_at_time(False, len(b'garbage'), new_time, b'garbage', addrs) _handle_query_or_defer.assert_not_called() _handle_query_or_defer.reset_mock() zc.close() 07070100000070000081A40000000000000000000000016619D4CC00000D44000000000000000000000000000000000000002D00000000python-zeroconf-0.132.2/tests/test_logger.py#!/usr/bin/env python """Unit tests for logger.py.""" import logging from unittest.mock import call, patch from zeroconf._logger import QuietLogger, set_logger_level_if_unset def test_loading_logger(): """Test loading logger does not change level unless it is unset.""" log = logging.getLogger('zeroconf') log.setLevel(logging.CRITICAL) set_logger_level_if_unset() log = logging.getLogger('zeroconf') assert log.level == logging.CRITICAL log = logging.getLogger('zeroconf') log.setLevel(logging.NOTSET) set_logger_level_if_unset() log = logging.getLogger('zeroconf') assert log.level == logging.WARNING def test_log_warning_once(): """Test we only log with warning level once.""" QuietLogger._seen_logs = {} quiet_logger = QuietLogger() with patch("zeroconf._logger.log.warning") as mock_log_warning, patch( "zeroconf._logger.log.debug" ) as mock_log_debug: quiet_logger.log_warning_once("the warning") assert mock_log_warning.mock_calls assert not mock_log_debug.mock_calls with patch("zeroconf._logger.log.warning") as mock_log_warning, patch( "zeroconf._logger.log.debug" ) as mock_log_debug: quiet_logger.log_warning_once("the warning") assert not mock_log_warning.mock_calls assert mock_log_debug.mock_calls def test_log_exception_warning(): """Test we only log with warning level once.""" QuietLogger._seen_logs = {} quiet_logger = QuietLogger() with patch("zeroconf._logger.log.warning") as mock_log_warning, patch( "zeroconf._logger.log.debug" ) as mock_log_debug: quiet_logger.log_exception_warning("the exception warning") assert mock_log_warning.mock_calls assert not mock_log_debug.mock_calls with patch("zeroconf._logger.log.warning") as mock_log_warning, patch( "zeroconf._logger.log.debug" ) as mock_log_debug: quiet_logger.log_exception_warning("the exception warning") assert not mock_log_warning.mock_calls assert mock_log_debug.mock_calls def test_llog_exception_debug(): """Test we only log with a trace once.""" QuietLogger._seen_logs = {} quiet_logger = QuietLogger() with patch("zeroconf._logger.log.debug") as mock_log_debug: quiet_logger.log_exception_debug("the exception") assert mock_log_debug.mock_calls == [call('the exception', exc_info=True)] with patch("zeroconf._logger.log.debug") as mock_log_debug: quiet_logger.log_exception_debug("the exception") assert mock_log_debug.mock_calls == [call('the exception', exc_info=False)] def test_log_exception_once(): """Test we only log with warning level once.""" QuietLogger._seen_logs = {} quiet_logger = QuietLogger() exc = Exception() with patch("zeroconf._logger.log.warning") as mock_log_warning, patch( "zeroconf._logger.log.debug" ) as mock_log_debug: quiet_logger.log_exception_once(exc, "the exceptional exception warning") assert mock_log_warning.mock_calls assert not mock_log_debug.mock_calls with patch("zeroconf._logger.log.warning") as mock_log_warning, patch( "zeroconf._logger.log.debug" ) as mock_log_debug: quiet_logger.log_exception_once(exc, "the exceptional exception warning") assert not mock_log_warning.mock_calls assert mock_log_debug.mock_calls 07070100000071000081A40000000000000000000000016619D4CC0000AD54000000000000000000000000000000000000002F00000000python-zeroconf-0.132.2/tests/test_protocol.py#!/usr/bin/env python """ Unit tests for zeroconf._protocol """ import copy import logging import os import socket import struct import unittest import unittest.mock from typing import cast import pytest import zeroconf as r from zeroconf import DNSHinfo, DNSIncoming, DNSText, const, current_time_millis from . import has_working_ipv6 log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) class PacketGeneration(unittest.TestCase): def test_parse_own_packet_simple(self): generated = r.DNSOutgoing(0) r.DNSIncoming(generated.packets()[0]) def test_parse_own_packet_simple_unicast(self): generated = r.DNSOutgoing(0, False) r.DNSIncoming(generated.packets()[0]) def test_parse_own_packet_flags(self): generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) r.DNSIncoming(generated.packets()[0]) def test_parse_own_packet_question(self): generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) generated.add_question(r.DNSQuestion("testname.local.", const._TYPE_SRV, const._CLASS_IN)) r.DNSIncoming(generated.packets()[0]) def test_parse_own_packet_nsec(self): answer = r.DNSNsec( 'eufy HomeBase2-2464._hap._tcp.local.', const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, 'eufy HomeBase2-2464._hap._tcp.local.', [const._TYPE_TXT, const._TYPE_SRV], ) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time(answer, 0) parsed = r.DNSIncoming(generated.packets()[0]) assert answer in parsed.answers() # Now with the higher RD type first answer = r.DNSNsec( 'eufy HomeBase2-2464._hap._tcp.local.', const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, 'eufy HomeBase2-2464._hap._tcp.local.', [const._TYPE_SRV, const._TYPE_TXT], ) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time(answer, 0) parsed = r.DNSIncoming(generated.packets()[0]) assert answer in parsed.answers() # Types > 255 should raise an exception answer_invalid_types = r.DNSNsec( 'eufy HomeBase2-2464._hap._tcp.local.', const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, 'eufy HomeBase2-2464._hap._tcp.local.', [const._TYPE_TXT, const._TYPE_SRV, 1000], ) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time(answer_invalid_types, 0) with pytest.raises(ValueError, match='rdtype 1000 is too large for NSEC'): generated.packets() # Empty rdtypes are not allowed answer_invalid_types = r.DNSNsec( 'eufy HomeBase2-2464._hap._tcp.local.', const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, 'eufy HomeBase2-2464._hap._tcp.local.', [], ) generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time(answer_invalid_types, 0) with pytest.raises(ValueError, match='NSEC must have at least one rdtype'): generated.packets() def test_parse_own_packet_response(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSService( "æøå.local.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, 80, "foo.local.", ), 0, ) parsed = r.DNSIncoming(generated.packets()[0]) assert len(generated.answers) == 1 assert len(generated.answers) == len(parsed.answers()) def test_adding_empty_answer(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( None, 0, ) generated.add_answer_at_time( r.DNSService( "æøå.local.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, 80, "foo.local.", ), 0, ) parsed = r.DNSIncoming(generated.packets()[0]) assert len(generated.answers) == 1 assert len(generated.answers) == len(parsed.answers()) def test_adding_expired_answer(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) generated.add_answer_at_time( r.DNSService( "æøå.local.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, 80, "foo.local.", ), current_time_millis() + 1000000, ) parsed = r.DNSIncoming(generated.packets()[0]) assert len(generated.answers) == 0 assert len(generated.answers) == len(parsed.answers()) def test_match_question(self): generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion("testname.local.", const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) parsed = r.DNSIncoming(generated.packets()[0]) assert len(generated.questions) == 1 assert len(generated.questions) == len(parsed.questions) assert question == parsed.questions[0] def test_suppress_answer(self): query_generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) question = r.DNSQuestion("testname.local.", const._TYPE_SRV, const._CLASS_IN) query_generated.add_question(question) answer1 = r.DNSService( "testname1.local.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, 80, "foo.local.", ) staleanswer2 = r.DNSService( "testname2.local.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL / 2, 0, 0, 80, "foo.local.", ) answer2 = r.DNSService( "testname2.local.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, 80, "foo.local.", ) query_generated.add_answer_at_time(answer1, 0) query_generated.add_answer_at_time(staleanswer2, 0) query = r.DNSIncoming(query_generated.packets()[0]) # Should be suppressed response = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) response.add_answer(query, answer1) assert len(response.answers) == 0 # Should not be suppressed, TTL in query is too short response.add_answer(query, answer2) assert len(response.answers) == 1 # Should not be suppressed, name is different tmp = copy.copy(answer1) tmp.key = "testname3.local." tmp.name = "testname3.local." response.add_answer(query, tmp) assert len(response.answers) == 2 # Should not be suppressed, type is different tmp = copy.copy(answer1) tmp.type = const._TYPE_A response.add_answer(query, tmp) assert len(response.answers) == 3 # Should not be suppressed, class is different tmp = copy.copy(answer1) tmp.class_ = const._CLASS_NONE response.add_answer(query, tmp) assert len(response.answers) == 4 # ::TODO:: could add additional tests for DNSAddress, DNSHinfo, DNSPointer, DNSText, DNSService def test_dns_hinfo(self): generated = r.DNSOutgoing(0) generated.add_additional_answer(DNSHinfo('irrelevant', const._TYPE_HINFO, 0, 0, 'cpu', 'os')) parsed = r.DNSIncoming(generated.packets()[0]) answer = cast(r.DNSHinfo, parsed.answers()[0]) assert answer.cpu == 'cpu' assert answer.os == 'os' generated = r.DNSOutgoing(0) generated.add_additional_answer(DNSHinfo('irrelevant', const._TYPE_HINFO, 0, 0, 'cpu', 'x' * 257)) self.assertRaises(r.NamePartTooLongException, generated.packets) def test_many_questions(self): """Test many questions get seperated into multiple packets.""" generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) questions = [] for i in range(100): question = r.DNSQuestion(f"testname{i}.local.", const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) questions.append(question) assert len(generated.questions) == 100 packets = generated.packets() assert len(packets) == 2 assert len(packets[0]) < const._MAX_MSG_TYPICAL assert len(packets[1]) < const._MAX_MSG_TYPICAL parsed1 = r.DNSIncoming(packets[0]) assert len(parsed1.questions) == 85 parsed2 = r.DNSIncoming(packets[1]) assert len(parsed2.questions) == 15 def test_many_questions_with_many_known_answers(self): """Test many questions and known answers get seperated into multiple packets.""" generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) questions = [] for _ in range(30): question = r.DNSQuestion("_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN) generated.add_question(question) questions.append(question) assert len(generated.questions) == 30 now = current_time_millis() for _ in range(200): known_answer = r.DNSPointer( "myservice{i}_tcp._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, '123.local.', ) generated.add_answer_at_time(known_answer, now) packets = generated.packets() assert len(packets) == 3 assert len(packets[0]) <= const._MAX_MSG_TYPICAL assert len(packets[1]) <= const._MAX_MSG_TYPICAL assert len(packets[2]) <= const._MAX_MSG_TYPICAL parsed1 = r.DNSIncoming(packets[0]) assert len(parsed1.questions) == 30 assert len(parsed1.answers()) == 88 assert parsed1.truncated parsed2 = r.DNSIncoming(packets[1]) assert len(parsed2.questions) == 0 assert len(parsed2.answers()) == 101 assert parsed2.truncated parsed3 = r.DNSIncoming(packets[2]) assert len(parsed3.questions) == 0 assert len(parsed3.answers()) == 11 assert not parsed3.truncated def test_massive_probe_packet_split(self): """Test probe with many authorative answers.""" generated = r.DNSOutgoing(const._FLAGS_QR_QUERY | const._FLAGS_AA) questions = [] for _ in range(30): question = r.DNSQuestion( "_hap._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE ) generated.add_question(question) questions.append(question) assert len(generated.questions) == 30 for _ in range(200): authorative_answer = r.DNSPointer( "myservice{i}_tcp._tcp.local.", const._TYPE_PTR, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, '123.local.', ) generated.add_authorative_answer(authorative_answer) packets = generated.packets() assert len(packets) == 3 assert len(packets[0]) <= const._MAX_MSG_TYPICAL assert len(packets[1]) <= const._MAX_MSG_TYPICAL assert len(packets[2]) <= const._MAX_MSG_TYPICAL parsed1 = r.DNSIncoming(packets[0]) assert parsed1.questions[0].unicast is True assert len(parsed1.questions) == 30 assert parsed1.num_questions == 30 assert parsed1.num_authorities == 88 assert parsed1.truncated parsed2 = r.DNSIncoming(packets[1]) assert len(parsed2.questions) == 0 assert parsed2.num_authorities == 101 assert parsed2.truncated parsed3 = r.DNSIncoming(packets[2]) assert len(parsed3.questions) == 0 assert parsed3.num_authorities == 11 assert not parsed3.truncated def test_only_one_answer_can_by_large(self): """Test that only the first answer in each packet can be large. https://datatracker.ietf.org/doc/html/rfc6762#section-17 """ generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) query = r.DNSIncoming(r.DNSOutgoing(const._FLAGS_QR_QUERY).packets()[0]) for i in range(3): generated.add_answer( query, r.DNSText( "zoom._hap._tcp.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, 1200, b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==' * 100, ), ) generated.add_answer( query, r.DNSService( "testname1.local.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, 80, "foo.local.", ), ) assert len(generated.answers) == 4 packets = generated.packets() assert len(packets) == 4 assert len(packets[0]) <= const._MAX_MSG_ABSOLUTE assert len(packets[0]) > const._MAX_MSG_TYPICAL assert len(packets[1]) <= const._MAX_MSG_ABSOLUTE assert len(packets[1]) > const._MAX_MSG_TYPICAL assert len(packets[2]) <= const._MAX_MSG_ABSOLUTE assert len(packets[2]) > const._MAX_MSG_TYPICAL assert len(packets[3]) <= const._MAX_MSG_TYPICAL for packet in packets: parsed = r.DNSIncoming(packet) assert len(parsed.answers()) == 1 def test_questions_do_not_end_up_every_packet(self): """Test that questions are not sent again when multiple packets are needed. https://datatracker.ietf.org/doc/html/rfc6762#section-7.2 Sometimes a Multicast DNS querier will already have too many answers to fit in the Known-Answer Section of its query packets.... It MUST immediately follow the packet with another query packet containing no questions and as many more Known-Answer records as will fit. """ generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) for i in range(35): question = r.DNSQuestion(f"testname{i}.local.", const._TYPE_SRV, const._CLASS_IN) generated.add_question(question) answer = r.DNSService( f"testname{i}.local.", const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, 80, f"foo{i}.local.", ) generated.add_answer_at_time(answer, 0) assert len(generated.questions) == 35 assert len(generated.answers) == 35 packets = generated.packets() assert len(packets) == 2 assert len(packets[0]) <= const._MAX_MSG_TYPICAL assert len(packets[1]) <= const._MAX_MSG_TYPICAL parsed1 = r.DNSIncoming(packets[0]) assert len(parsed1.questions) == 35 assert len(parsed1.answers()) == 33 parsed2 = r.DNSIncoming(packets[1]) assert len(parsed2.questions) == 0 assert len(parsed2.answers()) == 2 class PacketForm(unittest.TestCase): def test_transaction_id(self): """ID must be zero in a DNS-SD packet""" generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) bytes = generated.packets()[0] id = bytes[0] << 8 | bytes[1] assert id == 0 def test_setting_id(self): """Test setting id in the constructor""" generated = r.DNSOutgoing(const._FLAGS_QR_QUERY, id_=4444) assert generated.id == 4444 def test_query_header_bits(self): generated = r.DNSOutgoing(const._FLAGS_QR_QUERY) bytes = generated.packets()[0] flags = bytes[2] << 8 | bytes[3] assert flags == 0x0 def test_response_header_bits(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) bytes = generated.packets()[0] flags = bytes[2] << 8 | bytes[3] assert flags == 0x8000 def test_numbers(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) bytes = generated.packets()[0] (num_questions, num_answers, num_authorities, num_additionals) = struct.unpack('!4H', bytes[4:12]) assert num_questions == 0 assert num_answers == 0 assert num_authorities == 0 assert num_additionals == 0 def test_numbers_questions(self): generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE) question = r.DNSQuestion("testname.local.", const._TYPE_SRV, const._CLASS_IN) for i in range(10): generated.add_question(question) bytes = generated.packets()[0] (num_questions, num_answers, num_authorities, num_additionals) = struct.unpack('!4H', bytes[4:12]) assert num_questions == 10 assert num_answers == 0 assert num_authorities == 0 assert num_additionals == 0 class TestDnsIncoming(unittest.TestCase): def test_incoming_exception_handling(self): generated = r.DNSOutgoing(0) packet = generated.packets()[0] packet = packet[:8] + b'deadbeef' + packet[8:] parsed = r.DNSIncoming(packet) parsed = r.DNSIncoming(packet) assert parsed.valid is False def test_incoming_unknown_type(self): generated = r.DNSOutgoing(0) answer = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'a') generated.add_additional_answer(answer) packet = generated.packets()[0] parsed = r.DNSIncoming(packet) assert len(parsed.answers()) == 0 assert parsed.is_query() != parsed.is_response() def test_incoming_circular_reference(self): assert not r.DNSIncoming( bytes.fromhex( '01005e0000fb542a1bf0577608004500006897934000ff11d81bc0a86a31e00000fb' '14e914e90054f9b2000084000000000100000000095f7365727669636573075f646e' '732d7364045f756470056c6f63616c00000c0001000011940018105f73706f746966' '792d636f6e6e656374045f746370c023' ) ).valid @unittest.skipIf(not has_working_ipv6(), 'Requires IPv6') @unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_incoming_ipv6(self): addr = "2606:2800:220:1:248:1893:25c8:1946" # example.com packed = socket.inet_pton(socket.AF_INET6, addr) generated = r.DNSOutgoing(0) answer = r.DNSAddress('domain', const._TYPE_AAAA, const._CLASS_IN | const._CLASS_UNIQUE, 1, packed) generated.add_additional_answer(answer) packet = generated.packets()[0] parsed = r.DNSIncoming(packet) record = parsed.answers()[0] assert isinstance(record, r.DNSAddress) assert record.address == packed def test_dns_compression_rollback_for_corruption(): """Verify rolling back does not lead to dns compression corruption.""" out = r.DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA) address = socket.inet_pton(socket.AF_INET, "192.168.208.5") additionals = [ { "name": "HASS Bridge ZJWH FF5137._hap._tcp.local.", "address": address, "port": 51832, "text": b"\x13md=HASS Bridge" b" ZJWH\x06pv=1.0\x14id=01:6B:30:FF:51:37\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=L0m/aQ==", }, { "name": "HASS Bridge 3K9A C2582A._hap._tcp.local.", "address": address, "port": 51834, "text": b"\x13md=HASS Bridge" b" 3K9A\x06pv=1.0\x14id=E2:AA:5B:C2:58:2A\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=b2CnzQ==", }, { "name": "Master Bed TV CEDB27._hap._tcp.local.", "address": address, "port": 51830, "text": b"\x10md=Master Bed" b" TV\x06pv=1.0\x14id=9E:B7:44:CE:DB:27\x05c#=18\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=CVj1kw==", }, { "name": "Living Room TV 921B77._hap._tcp.local.", "address": address, "port": 51833, "text": b"\x11md=Living Room" b" TV\x06pv=1.0\x14id=11:61:E7:92:1B:77\x05c#=17\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=qU77SQ==", }, { "name": "HASS Bridge ZC8X FF413D._hap._tcp.local.", "address": address, "port": 51829, "text": b"\x13md=HASS Bridge" b" ZC8X\x06pv=1.0\x14id=96:14:45:FF:41:3D\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=b0QZlg==", }, { "name": "HASS Bridge WLTF 4BE61F._hap._tcp.local.", "address": address, "port": 51837, "text": b"\x13md=HASS Bridge" b" WLTF\x06pv=1.0\x14id=E0:E7:98:4B:E6:1F\x04c#=2\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=ahAISA==", }, { "name": "FrontdoorCamera 8941D1._hap._tcp.local.", "address": address, "port": 54898, "text": b"\x12md=FrontdoorCamera\x06pv=1.0\x14id=9F:B7:DC:89:41:D1\x04c#=2\x04" b"s#=1\x04ff=0\x04ci=2\x04sf=0\x0bsh=0+MXmA==", }, { "name": "HASS Bridge W9DN 5B5CC5._hap._tcp.local.", "address": address, "port": 51836, "text": b"\x13md=HASS Bridge" b" W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=6fLM5A==", }, { "name": "HASS Bridge Y9OO EFF0A7._hap._tcp.local.", "address": address, "port": 51838, "text": b"\x13md=HASS Bridge" b" Y9OO\x06pv=1.0\x14id=D3:FE:98:EF:F0:A7\x04c#=2\x04s#=1\x04ff=0\x04" b"ci=2\x04sf=0\x0bsh=u3bdfw==", }, { "name": "Snooze Room TV 6B89B0._hap._tcp.local.", "address": address, "port": 51835, "text": b"\x11md=Snooze Room" b" TV\x06pv=1.0\x14id=5F:D5:70:6B:89:B0\x05c#=17\x04s#=1\x04ff=0\x05" b"ci=31\x04sf=0\x0bsh=xNTqsg==", }, { "name": "AlexanderHomeAssistant 74651D._hap._tcp.local.", "address": address, "port": 54811, "text": b"\x19md=AlexanderHomeAssistant\x06pv=1.0\x14id=59:8A:0B:74:65:1D\x05" b"c#=14\x04s#=1\x04ff=0\x04ci=2\x04sf=0\x0bsh=ccZLPA==", }, { "name": "HASS Bridge OS95 39C053._hap._tcp.local.", "address": address, "port": 51831, "text": b"\x13md=HASS Bridge" b" OS95\x06pv=1.0\x14id=7E:8C:E6:39:C0:53\x05c#=12\x04s#=1\x04ff=0\x04ci=2" b"\x04sf=0\x0bsh=Xfe5LQ==", }, ] out.add_answer_at_time( DNSText( "HASS Bridge W9DN 5B5CC5._hap._tcp.local.", const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, b'\x13md=HASS Bridge W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1' b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) for record in additionals: out.add_additional_answer( r.DNSService( record["name"], # type: ignore const._TYPE_SRV, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, 0, 0, record["port"], # type: ignore record["name"], # type: ignore ) ) out.add_additional_answer( r.DNSText( record["name"], # type: ignore const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, record["text"], # type: ignore ) ) out.add_additional_answer( r.DNSAddress( record["name"], # type: ignore const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_HOST_TTL, record["address"], # type: ignore ) ) for packet in out.packets(): # Verify we can process the packets we created to # ensure there is no corruption with the dns compression incoming = r.DNSIncoming(packet) assert incoming.valid is True assert ( len(incoming.answers()) == incoming.num_answers + incoming.num_authorities + incoming.num_additionals ) def test_tc_bit_in_query_packet(): """Verify the TC bit is set when known answers exceed the packet size.""" out = r.DNSOutgoing(const._FLAGS_QR_QUERY | const._FLAGS_AA) type_ = "_hap._tcp.local." out.add_question(r.DNSQuestion(type_, const._TYPE_PTR, const._CLASS_IN)) for i in range(30): out.add_answer_at_time( DNSText( ("HASS Bridge W9DN %s._hap._tcp.local." % i), const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, b'\x13md=HASS Bridge W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1' b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) packets = out.packets() assert len(packets) == 3 first_packet = r.DNSIncoming(packets[0]) assert first_packet.truncated assert first_packet.valid is True second_packet = r.DNSIncoming(packets[1]) assert second_packet.truncated assert second_packet.valid is True third_packet = r.DNSIncoming(packets[2]) assert not third_packet.truncated assert third_packet.valid is True def test_tc_bit_not_set_in_answer_packet(): """Verify the TC bit is not set when there are no questions and answers exceed the packet size.""" out = r.DNSOutgoing(const._FLAGS_QR_RESPONSE | const._FLAGS_AA) for i in range(30): out.add_answer_at_time( DNSText( ("HASS Bridge W9DN %s._hap._tcp.local." % i), const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, b'\x13md=HASS Bridge W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1' b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) packets = out.packets() assert len(packets) == 3 first_packet = r.DNSIncoming(packets[0]) assert not first_packet.truncated assert first_packet.valid is True second_packet = r.DNSIncoming(packets[1]) assert not second_packet.truncated assert second_packet.valid is True third_packet = r.DNSIncoming(packets[2]) assert not third_packet.truncated assert third_packet.valid is True # 4003 15.973052 192.168.107.68 224.0.0.251 MDNS 76 Standard query 0xffc4 PTR _raop._tcp.local, "QM" question def test_qm_packet_parser(): """Test we can parse a query packet with the QM bit.""" qm_packet = ( b'\xff\xc4\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x05_raop\x04_tcp\x05local\x00\x00\x0c\x00\x01' ) parsed = DNSIncoming(qm_packet) assert parsed.questions[0].unicast is False assert ",QM," in str(parsed.questions[0]) # 389951 1450.577370 192.168.107.111 224.0.0.251 MDNS 115 Standard query 0x0000 PTR _companion-link._tcp.local, "QU" question OPT def test_qu_packet_parser(): """Test we can parse a query packet with the QU bit.""" qu_packet = ( b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x01\x0f_companion-link\x04_tcp\x05local' b'\x00\x00\x0c\x80\x01\x00\x00)\x05\xa0\x00\x00\x11\x94\x00\x12\x00\x04\x00\x0e\x00dz{\x8a6\x9czF\x84,\xcaQ\xff' ) parsed = DNSIncoming(qu_packet) assert parsed.questions[0].unicast is True assert ",QU," in str(parsed.questions[0]) def test_parse_packet_with_nsec_record(): """Test we can parse a packet with an NSEC record.""" nsec_packet = ( b"\x00\x00\x84\x00\x00\x00\x00\x01\x00\x00\x00\x03\x08_meshcop\x04_udp\x05local\x00\x00\x0c\x00" b"\x01\x00\x00\x11\x94\x00\x0f\x0cMyHome54 (2)\xc0\x0c\xc0+\x00\x10\x80\x01\x00\x00\x11\x94\x00" b")\x0bnn=MyHome54\x13xp=695034D148CC4784\x08tv=0.0.0\xc0+\x00!\x80\x01\x00\x00\x00x\x00\x15\x00" b"\x00\x00\x00\xc0'\x0cMaster-Bed-2\xc0\x1a\xc0+\x00/\x80\x01\x00\x00\x11\x94\x00\t\xc0+\x00\x05" b"\x00\x00\x80\x00@" ) parsed = DNSIncoming(nsec_packet) nsec_record = cast(r.DNSNsec, parsed.answers()[3]) assert "nsec," in str(nsec_record) assert nsec_record.rdtypes == [16, 33] assert nsec_record.next_name == "MyHome54 (2)._meshcop._udp.local." def test_records_same_packet_share_fate(): """Test records in the same packet all have the same created time.""" out = r.DNSOutgoing(const._FLAGS_QR_QUERY | const._FLAGS_AA) type_ = "_hap._tcp.local." out.add_question(r.DNSQuestion(type_, const._TYPE_PTR, const._CLASS_IN)) for i in range(30): out.add_answer_at_time( DNSText( ("HASS Bridge W9DN %s._hap._tcp.local." % i), const._TYPE_TXT, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, b'\x13md=HASS Bridge W9DN\x06pv=1.0\x14id=11:8E:DB:5B:5C:C5\x05c#=12\x04s#=1' b'\x04ff=0\x04ci=2\x04sf=0\x0bsh=6fLM5A==', ), 0, ) for packet in out.packets(): dnsin = DNSIncoming(packet) first_time = dnsin.answers()[0].created for answer in dnsin.answers(): assert answer.created == first_time def test_dns_compression_invalid_skips_bad_name_compress_in_question(): """Test our wire parser can skip bad compression in questions.""" packet = ( b'\x00\x00\x00\x00\x00\x04\x00\x00\x00\x07\x00\x00\x11homeassistant1128\x05l' b'ocal\x00\x00\xff\x00\x014homeassistant1128 [534a4794e5ed41879ecf012252d3e02' b'a]\x0c_workstation\x04_tcp\xc0\x1e\x00\xff\x00\x014homeassistant1127 [534a47' b'94e5ed41879ecf012252d3e02a]\xc0^\x00\xff\x00\x014homeassistant1123 [534a479' b'4e5ed41879ecf012252d3e02a]\xc0^\x00\xff\x00\x014homeassistant1118 [534a4794' b'e5ed41879ecf012252d3e02a]\xc0^\x00\xff\x00\x01\xc0\x0c\x00\x01\x80' b'\x01\x00\x00\x00x\x00\x04\xc0\xa8<\xc3\xc0v\x00\x10\x80\x01\x00\x00\x00' b'x\x00\x01\x00\xc0v\x00!\x80\x01\x00\x00\x00x\x00\x1f\x00\x00\x00\x00' b'\x00\x00\x11homeassistant1127\x05local\x00\xc0\xb1\x00\x10\x80' b'\x01\x00\x00\x00x\x00\x01\x00\xc0\xb1\x00!\x80\x01\x00\x00\x00x\x00\x1f' b'\x00\x00\x00\x00\x00\x00\x11homeassistant1123\x05local\x00\xc0)\x00\x10\x80' b'\x01\x00\x00\x00x\x00\x01\x00\xc0)\x00!\x80\x01\x00\x00\x00x\x00\x1f' b'\x00\x00\x00\x00\x00\x00\x11homeassistant1128\x05local\x00' ) parsed = r.DNSIncoming(packet) assert len(parsed.questions) == 4 def test_dns_compression_all_invalid(caplog): """Test our wire parser can skip all invalid data.""" packet = ( b'\x00\x00\x84\x00\x00\x00\x00\x01\x00\x00\x00\x00!roborock-vacuum-s5e_miio416' b'112328\x00\x00/\x80\x01\x00\x00\x00x\x00\t\xc0P\x00\x05@\x00\x00\x00\x00' ) parsed = r.DNSIncoming(packet, ("2.4.5.4", 5353)) assert len(parsed.questions) == 0 assert len(parsed.answers()) == 0 assert " Unable to parse; skipping record" in caplog.text def test_invalid_next_name_ignored(): """Test our wire parser does not throw an an invalid next name. The RFC states it should be ignored when used with mDNS. """ packet = ( b'\x00\x00\x00\x00\x00\x01\x00\x02\x00\x00\x00\x00\x07Android\x05local\x00\x00' b'\xff\x00\x01\xc0\x0c\x00/\x00\x01\x00\x00\x00x\x00\x08\xc02\x00\x04@' b'\x00\x00\x08\xc0\x0c\x00\x01\x00\x01\x00\x00\x00x\x00\x04\xc0\xa8X<' ) parsed = r.DNSIncoming(packet) assert len(parsed.questions) == 1 assert len(parsed.answers()) == 2 def test_dns_compression_invalid_skips_record(): """Test our wire parser can skip records we do not know how to parse.""" packet = ( b"\x00\x00\x84\x00\x00\x00\x00\x06\x00\x00\x00\x00\x04_hap\x04_tcp\x05local\x00\x00\x0c" b"\x00\x01\x00\x00\x11\x94\x00\x16\x13eufy HomeBase2-2464\xc0\x0c\x04Eufy\xc0\x16\x00/" b"\x80\x01\x00\x00\x00x\x00\x08\xc0\xa6\x00\x04@\x00\x00\x08\xc0'\x00/\x80\x01\x00\x00" b"\x11\x94\x00\t\xc0'\x00\x05\x00\x00\x80\x00@\xc0=\x00\x01\x80\x01\x00\x00\x00x\x00\x04" b"\xc0\xa8Dp\xc0'\x00!\x80\x01\x00\x00\x00x\x00\x08\x00\x00\x00\x00\xd1_\xc0=\xc0'\x00" b"\x10\x80\x01\x00\x00\x11\x94\x00K\x04c#=1\x04ff=2\x14id=38:71:4F:6B:76:00\x08md=T8010" b"\x06pv=1.1\x05s#=75\x04sf=1\x04ci=2\x0bsh=xaQk4g==" ) parsed = r.DNSIncoming(packet) answer = r.DNSNsec( 'eufy HomeBase2-2464._hap._tcp.local.', const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, 'eufy HomeBase2-2464._hap._tcp.local.', [const._TYPE_TXT, const._TYPE_SRV], ) assert answer in parsed.answers() def test_dns_compression_points_forward(): """Test our wire parser can unpack nsec records with compression.""" packet = ( b"\x00\x00\x84\x00\x00\x00\x00\x07\x00\x00\x00\x00\x0eTV Beneden (2)" b"\x10_androidtvremote\x04_tcp\x05local\x00\x00\x10\x80\x01\x00\x00\x11" b"\x94\x00\x15\x14bt=D8:13:99:AC:98:F1\xc0\x0c\x00/\x80\x01\x00\x00\x11" b"\x94\x00\t\xc0\x0c\x00\x05\x00\x00\x80\x00@\tAndroid-3\xc01\x00/\x80" b"\x01\x00\x00\x00x\x00\x08\xc0\x9c\x00\x04@\x00\x00\x08\xc0l\x00\x01\x80" b"\x01\x00\x00\x00x\x00\x04\xc0\xa8X\x0f\xc0\x0c\x00!\x80\x01\x00\x00\x00" b"x\x00\x08\x00\x00\x00\x00\x19B\xc0l\xc0\x1b\x00\x0c\x00\x01\x00\x00\x11" b"\x94\x00\x02\xc0\x0c\t_services\x07_dns-sd\x04_udp\xc01\x00\x0c\x00\x01" b"\x00\x00\x11\x94\x00\x02\xc0\x1b" ) parsed = r.DNSIncoming(packet) answer = r.DNSNsec( 'TV Beneden (2)._androidtvremote._tcp.local.', const._TYPE_NSEC, const._CLASS_IN | const._CLASS_UNIQUE, const._DNS_OTHER_TTL, 'TV Beneden (2)._androidtvremote._tcp.local.', [const._TYPE_TXT, const._TYPE_SRV], ) assert answer in parsed.answers() def test_dns_compression_points_to_itself(): """Test our wire parser does not loop forever when a compression pointer points to itself.""" packet = ( b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x06domain\x05local\x00\x00\x01" b"\x80\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x05\xc0(\x00\x01\x80\x01\x00\x00\x00" b"\x01\x00\x04\xc0\xa8\xd0\x06" ) parsed = r.DNSIncoming(packet) assert len(parsed.answers()) == 1 def test_dns_compression_points_beyond_packet(): """Test our wire parser does not fail when the compression pointer points beyond the packet.""" packet = ( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x06domain\x05local\x00\x00\x01' b'\x80\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x05\xe7\x0f\x00\x01\x80\x01\x00\x00' b'\x00\x01\x00\x04\xc0\xa8\xd0\x06' ) parsed = r.DNSIncoming(packet) assert len(parsed.answers()) == 1 def test_dns_compression_generic_failure(caplog): """Test our wire parser does not loop forever when dns compression is corrupt.""" packet = ( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x06domain\x05local\x00\x00\x01' b'\x80\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x05-\x0c\x00\x01\x80\x01\x00\x00' b'\x00\x01\x00\x04\xc0\xa8\xd0\x06' ) parsed = r.DNSIncoming(packet, ("1.2.3.4", 5353)) assert len(parsed.answers()) == 1 assert "Received invalid packet from ('1.2.3.4', 5353)" in caplog.text def test_label_length_attack(): """Test our wire parser does not loop forever when the name exceeds 253 chars.""" packet = ( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x01d\x01d\x01d\x01d\x01d\x01d' b'\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d' b'\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d' b'\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d' b'\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d' b'\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d' b'\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d' b'\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d' b'\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x01d\x00\x00\x01\x80' b'\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x05\xc0\x0c\x00\x01\x80\x01\x00\x00\x00' b'\x01\x00\x04\xc0\xa8\xd0\x06' ) parsed = r.DNSIncoming(packet) assert len(parsed.answers()) == 0 def test_label_compression_attack(): """Test our wire parser does not loop forever when exceeding the maximum number of labels.""" packet = ( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x03atk\x00\x00\x01\x80' b'\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x05\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03' b'atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\xc0' b'\x0c\x00\x01\x80\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x06' ) parsed = r.DNSIncoming(packet) assert len(parsed.answers()) == 1 def test_dns_compression_loop_attack(): """Test our wire parser does not loop forever when dns compression is in a loop.""" packet = ( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07\x03atk\x03dns\x05loc' b'al\xc0\x10\x00\x01\x80\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x05\x04a' b'tk2\x04dns2\xc0\x14\x00\x01\x80\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x05' b'\x04atk3\xc0\x10\x00\x01\x80\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0' b'\x05\x04atk4\x04dns5\xc0\x14\x00\x01\x80\x01\x00\x00\x00\x01\x00\x04\xc0' b'\xa8\xd0\x05\x04atk5\x04dns2\xc0^\x00\x01\x80\x01\x00\x00\x00\x01\x00' b'\x04\xc0\xa8\xd0\x05\xc0s\x00\x01\x80\x01\x00\x00\x00\x01\x00' b'\x04\xc0\xa8\xd0\x05\xc0s\x00\x01\x80\x01\x00\x00\x00\x01\x00' b'\x04\xc0\xa8\xd0\x05' ) parsed = r.DNSIncoming(packet) assert len(parsed.answers()) == 0 def test_txt_after_invalid_nsec_name_still_usable(): """Test that we can see the txt record after the invalid nsec record.""" packet = ( b'\x00\x00\x84\x00\x00\x00\x00\x06\x00\x00\x00\x00\x06_sonos\x04_tcp\x05loc' b'al\x00\x00\x0c\x00\x01\x00\x00\x11\x94\x00\x15\x12Sonos-542A1BC9220E' b'\xc0\x0c\x12Sonos-542A1BC9220E\xc0\x18\x00/\x80\x01\x00\x00\x00x\x00' b'\x08\xc1t\x00\x04@\x00\x00\x08\xc0)\x00/\x80\x01\x00\x00\x11\x94\x00' b'\t\xc0)\x00\x05\x00\x00\x80\x00@\xc0)\x00!\x80\x01\x00\x00\x00x' b'\x00\x08\x00\x00\x00\x00\x05\xa3\xc0>\xc0>\x00\x01\x80\x01\x00\x00\x00x' b'\x00\x04\xc0\xa8\x02:\xc0)\x00\x10\x80\x01\x00\x00\x11\x94\x01*2info=/api' b'/v1/players/RINCON_542A1BC9220E01400/info\x06vers=3\x10protovers=1.24.1\nbo' b'otseq=11%hhid=Sonos_rYn9K9DLXJe0f3LP9747lbvFvh;mhhid=Sonos_rYn9K9DLXJe0f3LP9' b'747lbvFvh.Q45RuMaeC07rfXh7OJGm<location=http://192.168.2.58:1400/xml/device_' b'description.xml\x0csslport=1443\x0ehhsslport=1843\tvariant=2\x0emdnssequen' b'ce=0' ) parsed = r.DNSIncoming(packet) txt_record = cast(r.DNSText, parsed.answers()[4]) # The NSEC record with the invalid name compression should be skipped assert txt_record.text == ( b'2info=/api/v1/players/RINCON_542A1BC9220E01400/info\x06vers=3\x10protovers' b'=1.24.1\nbootseq=11%hhid=Sonos_rYn9K9DLXJe0f3LP9747lbvFvh;mhhid=Sonos_rYn' b'9K9DLXJe0f3LP9747lbvFvh.Q45RuMaeC07rfXh7OJGm<location=http://192.168.2.58:14' b'00/xml/device_description.xml\x0csslport=1443\x0ehhsslport=1843\tvarian' b't=2\x0emdnssequence=0' ) assert len(parsed.answers()) == 5 def test_parse_matter_packet(): """Test our wire parser can handle a packet from matter.""" packet_hex = ( "000084000000000a00000000075f6d6174746572045f746370056c6f63" "616c00000c000100001194002421413336303441463533314638364442" "372d30303030303030303030303030303636c00cc00c000c0001000011" "94002421333346353633363743453244333646302d3030303030303030" "3444423341334541c00cc00c000c000100001194002421414531313941" "304130374145304632302d34383742343631363639333638413332c00c" "c00c000c00010000119400242141333630344146353331463836444237" "2d30303030303030303030303030303237c00cc00c000c000100001194" "002421413336303441463533314638364442372d303030303030303030" "30303030303637c00cc00c000c00010000119400242133334635363336" "3743453244333646302d30303030303030304243363637324136c00cc0" "0c000c000100001194002421414531313941304130374145304632302d" "39464534383646413645373730464433c00cc00c000c00010000119400" "2421413336303441463533314638364442372d30303030303030303030" "303030303434c00cc00c000c0001000011940024213935374431413839" "44463239343033312d41423337393041444346434231423239c00cc00c" "000c000100001194002421413336303441463533314638364442372d30" "303030303030303030303030303638c00c" ) parsed = r.DNSIncoming(bytes.fromhex(packet_hex)) assert len(parsed.answers()) == 10 07070100000072000081A40000000000000000000000016619D4CC00002514000000000000000000000000000000000000002F00000000python-zeroconf-0.132.2/tests/test_services.py#!/usr/bin/env python """ Unit tests for zeroconf._services. """ import logging import os import socket import time import unittest from threading import Event from typing import Dict import pytest import zeroconf as r from zeroconf import Zeroconf from zeroconf._services.info import ServiceInfo from . import _clear_cache, has_working_ipv6 log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) class ListenerTest(unittest.TestCase): def test_integration_with_listener_class(self): sub_service_added = Event() service_added = Event() service_removed = Event() sub_service_updated = Event() duplicate_service_added = Event() subtype_name = "_printer" type_ = "_http._tcp.local." subtype = subtype_name + "._sub." + type_ name = "UPPERxxxyyyæøå" registration_name = f"{name}.{subtype}" class MyListener(r.ServiceListener): def add_service(self, zeroconf, type, name): zeroconf.get_service_info(type, name) service_added.set() def remove_service(self, zeroconf, type, name): service_removed.set() def update_service(self, zeroconf, type, name): pass class DuplicateListener(r.ServiceListener): def add_service(self, zeroconf, type, name): duplicate_service_added.set() def remove_service(self, zeroconf, type, name): pass def update_service(self, zeroconf, type, name): pass class MySubListener(r.ServiceListener): def add_service(self, zeroconf, type, name): sub_service_added.set() pass def remove_service(self, zeroconf, type, name): pass def update_service(self, zeroconf, type, name): sub_service_updated.set() listener = MyListener() zeroconf_browser = Zeroconf(interfaces=['127.0.0.1']) zeroconf_browser.add_service_listener(type_, listener) properties = dict( prop_none=None, prop_string=b'a_prop', prop_float=1.0, prop_blank=b'a blanked string', prop_true=1, prop_false=0, ) zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1']) desc = {'path': '/~paulsm/'} # type: Dict desc.update(properties) addresses = [socket.inet_aton("10.0.1.2")] if has_working_ipv6() and not os.environ.get('SKIP_IPV6'): addresses.append(socket.inet_pton(socket.AF_INET6, "6001:db8::1")) addresses.append(socket.inet_pton(socket.AF_INET6, "2001:db8::1")) info_service = ServiceInfo( subtype, registration_name, port=80, properties=desc, server="ash-2.local.", addresses=addresses ) zeroconf_registrar.register_service(info_service) try: service_added.wait(1) assert service_added.is_set() # short pause to allow multicast timers to expire time.sleep(3) zeroconf_browser.add_service_listener(type_, DuplicateListener()) duplicate_service_added.wait( 1 ) # Ensure a listener for the same type calls back right away from cache # clear the answer cache to force query _clear_cache(zeroconf_browser) cached_info = ServiceInfo(type_, registration_name) cached_info.load_from_cache(zeroconf_browser) assert cached_info.properties == {} # get service info without answer cache info = zeroconf_browser.get_service_info(type_, registration_name) assert info is not None assert info.properties[b'prop_none'] is None assert info.properties[b'prop_string'] == properties['prop_string'] assert info.properties[b'prop_float'] == b'1.0' assert info.properties[b'prop_blank'] == properties['prop_blank'] assert info.properties[b'prop_true'] == b'1' assert info.properties[b'prop_false'] == b'0' assert info.decoded_properties['prop_none'] is None assert info.decoded_properties['prop_string'] == b'a_prop'.decode('utf-8') assert info.decoded_properties['prop_float'] == '1.0' assert info.decoded_properties['prop_blank'] == b'a blanked string'.decode('utf-8') assert info.decoded_properties['prop_true'] == '1' assert info.decoded_properties['prop_false'] == '0' assert info.addresses == addresses[:1] # no V6 by default assert set(info.addresses_by_version(r.IPVersion.All)) == set(addresses) cached_info = ServiceInfo(type_, registration_name) cached_info.load_from_cache(zeroconf_browser) assert cached_info.properties is not None # Populate the cache zeroconf_browser.get_service_info(subtype, registration_name) # get service info with only the cache cached_info = ServiceInfo(subtype, registration_name) cached_info.load_from_cache(zeroconf_browser) assert cached_info.properties is not None assert cached_info.properties[b'prop_float'] == b'1.0' # get service info with only the cache with the lowercase name cached_info = ServiceInfo(subtype, registration_name.lower()) cached_info.load_from_cache(zeroconf_browser) # Ensure uppercase output is preserved assert cached_info.name == registration_name assert cached_info.key == registration_name.lower() assert cached_info.properties is not None assert cached_info.properties[b'prop_float'] == b'1.0' info = zeroconf_browser.get_service_info(subtype, registration_name) assert info is not None assert info.properties is not None assert info.properties[b'prop_none'] is None cached_info = ServiceInfo(subtype, registration_name.lower()) cached_info.load_from_cache(zeroconf_browser) assert cached_info.properties is not None assert cached_info.properties[b'prop_none'] is None # test TXT record update sublistener = MySubListener() zeroconf_browser.add_service_listener(subtype, sublistener) properties['prop_blank'] = b'an updated string' desc.update(properties) info_service = ServiceInfo( subtype, registration_name, 80, 0, 0, desc, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) zeroconf_registrar.update_service(info_service) sub_service_added.wait(1) # we cleared the cache above assert sub_service_added.is_set() info = zeroconf_browser.get_service_info(type_, registration_name) assert info is not None assert info.properties[b'prop_blank'] == properties['prop_blank'] assert info.decoded_properties['prop_blank'] == b'an updated string'.decode('utf-8') cached_info = ServiceInfo(subtype, registration_name) cached_info.load_from_cache(zeroconf_browser) assert cached_info.properties is not None assert cached_info.properties[b'prop_blank'] == properties['prop_blank'] assert cached_info.decoded_properties['prop_blank'] == b'an updated string'.decode('utf-8') zeroconf_registrar.unregister_service(info_service) service_removed.wait(1) assert service_removed.is_set() finally: zeroconf_registrar.close() zeroconf_browser.remove_service_listener(listener) zeroconf_browser.close() def test_servicelisteners_raise_not_implemented(): """Verify service listeners raise when one of the methods is not implemented.""" class MyPartialListener(r.ServiceListener): """A listener that does not implement anything.""" zc = r.Zeroconf(interfaces=['127.0.0.1']) with pytest.raises(NotImplementedError): MyPartialListener().add_service( zc, "_tivo-videostream._tcp.local.", "Tivo1._tivo-videostream._tcp.local." ) with pytest.raises(NotImplementedError): MyPartialListener().remove_service( zc, "_tivo-videostream._tcp.local.", "Tivo1._tivo-videostream._tcp.local." ) with pytest.raises(NotImplementedError): MyPartialListener().update_service( zc, "_tivo-videostream._tcp.local.", "Tivo1._tivo-videostream._tcp.local." ) zc.close() def test_signal_registration_interface(): """Test adding and removing from the SignalRegistrationInterface.""" interface = r.SignalRegistrationInterface([]) def dummy(): pass interface.register_handler(dummy) interface.unregister_handler(dummy) with pytest.raises(ValueError): interface.unregister_handler(dummy) 07070100000073000081A40000000000000000000000016619D4CC00000AD8000000000000000000000000000000000000002E00000000python-zeroconf-0.132.2/tests/test_updates.py#!/usr/bin/env python """ Unit tests for zeroconf._updates. """ import logging import socket import time import pytest import zeroconf as r from zeroconf import Zeroconf, const from zeroconf._record_update import RecordUpdate from zeroconf._services.browser import ServiceBrowser from zeroconf._services.info import ServiceInfo log = logging.getLogger('zeroconf') original_logging_level = logging.NOTSET def setup_module(): global original_logging_level original_logging_level = log.level log.setLevel(logging.DEBUG) def teardown_module(): if original_logging_level != logging.NOTSET: log.setLevel(original_logging_level) def test_legacy_record_update_listener(): """Test a RecordUpdateListener that does not implement update_records.""" # instantiate a zeroconf instance zc = Zeroconf(interfaces=['127.0.0.1']) with pytest.raises(RuntimeError): r.RecordUpdateListener().update_record( zc, 0, r.DNSRecord('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL) ) updates = [] class LegacyRecordUpdateListener(r.RecordUpdateListener): """A RecordUpdateListener that does not implement update_records.""" def update_record(self, zc: 'Zeroconf', now: float, record: r.DNSRecord) -> None: nonlocal updates updates.append(record) listener = LegacyRecordUpdateListener() zc.add_listener(listener, None) # dummy service callback def on_service_state_change(zeroconf, service_type, state_change, name): pass # start a browser type_ = "_homeassistant._tcp.local." name = "MyTestHome" browser = ServiceBrowser(zc, type_, [on_service_state_change]) info_service = ServiceInfo( type_, f'{name}.{type_}', 80, 0, 0, {'path': '/~paulsm/'}, "ash-2.local.", addresses=[socket.inet_aton("10.0.1.2")], ) zc.register_service(info_service) time.sleep(0.001) browser.cancel() assert len(updates) assert len([isinstance(update, r.DNSPointer) and update.name == type_ for update in updates]) >= 1 zc.remove_listener(listener) # Removing a second time should not throw zc.remove_listener(listener) zc.close() def test_record_update_compat(): """Test a RecordUpdate can fetch by index.""" new = r.DNSPointer('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 'new') old = r.DNSPointer('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL, 'old') update = RecordUpdate(new, old) assert update[0] == new assert update[1] == old with pytest.raises(IndexError): update[2] assert update.new == new assert update.old == old 07070100000074000041ED0000000000000000000000026619D4CC00000000000000000000000000000000000000000000002400000000python-zeroconf-0.132.2/tests/utils07070100000075000081A40000000000000000000000016619D4CC000003CB000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/tests/utils/__init__.py""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine This module provides a framework for the use of DNS Service Discovery using IP multicast. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ 07070100000076000081A40000000000000000000000016619D4CC000013EF000000000000000000000000000000000000003400000000python-zeroconf-0.132.2/tests/utils/test_asyncio.py#!/usr/bin/env python """Unit tests for zeroconf._utils.asyncio.""" import asyncio import concurrent.futures import contextlib import threading import time from typing import Optional from unittest.mock import patch import pytest from zeroconf import EventLoopBlocked from zeroconf._engine import _CLOSE_TIMEOUT from zeroconf._utils import asyncio as aioutils from zeroconf.const import _LOADED_SYSTEM_TIMEOUT @pytest.mark.asyncio async def test_async_get_all_tasks() -> None: """Test we can get all tasks in the event loop. We make sure we handle RuntimeError here as this is not thread safe under PyPy """ loop = aioutils.get_running_loop() assert loop is not None await aioutils._async_get_all_tasks(loop) if not hasattr(asyncio, 'all_tasks'): return with patch("zeroconf._utils.asyncio.asyncio.all_tasks", side_effect=RuntimeError): await aioutils._async_get_all_tasks(loop) @pytest.mark.asyncio async def test_get_running_loop_from_async() -> None: """Test we can get the event loop.""" assert isinstance(aioutils.get_running_loop(), asyncio.AbstractEventLoop) def test_get_running_loop_no_loop() -> None: """Test we get None when there is no loop running.""" assert aioutils.get_running_loop() is None @pytest.mark.asyncio async def test_wait_event_or_timeout_times_out() -> None: """Test wait_event_or_timeout will timeout.""" test_event = asyncio.Event() await aioutils.wait_event_or_timeout(test_event, 0.1) task = asyncio.ensure_future(test_event.wait()) await asyncio.sleep(0.1) async def _async_wait_or_timeout(): await aioutils.wait_event_or_timeout(test_event, 0.1) # Test high lock contention await asyncio.gather(*[_async_wait_or_timeout() for _ in range(100)]) task.cancel() with contextlib.suppress(asyncio.CancelledError): await task def test_shutdown_loop() -> None: """Test shutting down an event loop.""" loop = None loop_thread_ready = threading.Event() runcoro_thread_ready = threading.Event() def _run_loop() -> None: nonlocal loop loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop_thread_ready.set() loop.run_forever() loop_thread = threading.Thread(target=_run_loop, daemon=True) loop_thread.start() loop_thread_ready.wait() async def _still_running(): await asyncio.sleep(5) def _run_coro() -> None: runcoro_thread_ready.set() assert loop is not None with contextlib.suppress(concurrent.futures.TimeoutError): asyncio.run_coroutine_threadsafe(_still_running(), loop).result(1) runcoro_thread = threading.Thread(target=_run_coro, daemon=True) runcoro_thread.start() runcoro_thread_ready.wait() time.sleep(0.1) assert loop is not None aioutils.shutdown_loop(loop) for _ in range(5): if not loop.is_running(): break time.sleep(0.05) assert loop.is_running() is False runcoro_thread.join() def test_cumulative_timeouts_less_than_close_plus_buffer(): """Test that the combined async timeouts are shorter than the close timeout with the buffer. We want to make sure that the close timeout is the one that gets raised if something goes wrong. """ assert ( aioutils._TASK_AWAIT_TIMEOUT + aioutils._GET_ALL_TASKS_TIMEOUT + aioutils._WAIT_FOR_LOOP_TASKS_TIMEOUT ) < 1 + _CLOSE_TIMEOUT + _LOADED_SYSTEM_TIMEOUT @pytest.mark.asyncio async def test_run_coro_with_timeout() -> None: """Test running a coroutine with a timeout raises EventLoopBlocked.""" loop = asyncio.get_event_loop() task: Optional[asyncio.Task] = None async def _saved_sleep_task(): nonlocal task task = asyncio.create_task(asyncio.sleep(0.2)) assert task is not None await task def _run_in_loop(): aioutils.run_coro_with_timeout(_saved_sleep_task(), loop, 0.1) with pytest.raises(EventLoopBlocked), patch.object(aioutils, "_LOADED_SYSTEM_TIMEOUT", 0.0): await loop.run_in_executor(None, _run_in_loop) assert task is not None # ensure the thread is shutdown task.cancel() await asyncio.sleep(0) await _shutdown_default_executor(loop) # Remove this when we drop support for older python versions # since we can use loop.shutdown_default_executor() in 3.9+ async def _shutdown_default_executor(loop: asyncio.AbstractEventLoop) -> None: """Backport of cpython 3.9 schedule the shutdown of the default executor.""" future = loop.create_future() def _do_shutdown() -> None: try: loop._default_executor.shutdown(wait=True) # type: ignore # pylint: disable=protected-access loop.call_soon_threadsafe(future.set_result, None) except Exception as ex: # pylint: disable=broad-except loop.call_soon_threadsafe(future.set_exception, ex) thread = threading.Thread(target=_do_shutdown) thread.start() try: await future finally: thread.join() 07070100000077000081A40000000000000000000000016619D4CC00000AEB000000000000000000000000000000000000003600000000python-zeroconf-0.132.2/tests/utils/test_ipaddress.py#!/usr/bin/env python """Unit tests for zeroconf._utils.ipaddress.""" import sys import pytest from zeroconf import const from zeroconf._dns import DNSAddress from zeroconf._utils import ipaddress def test_cached_ip_addresses_wrapper(): """Test the cached_ip_addresses_wrapper.""" assert ipaddress.cached_ip_addresses('') is None assert ipaddress.cached_ip_addresses('foo') is None assert ( str(ipaddress.cached_ip_addresses(b'&\x06(\x00\x02 \x00\x01\x02H\x18\x93%\xc8\x19F')) == '2606:2800:220:1:248:1893:25c8:1946' ) assert ipaddress.cached_ip_addresses('::1') == ipaddress.IPv6Address('::1') ipv4 = ipaddress.cached_ip_addresses('169.254.0.0') assert ipv4 is not None assert ipv4.is_link_local is True assert ipv4.is_unspecified is False ipv4 = ipaddress.cached_ip_addresses('0.0.0.0') assert ipv4 is not None assert ipv4.is_link_local is False assert ipv4.is_unspecified is True ipv6 = ipaddress.cached_ip_addresses('fe80::1') assert ipv6 is not None assert ipv6.is_link_local is True assert ipv6.is_unspecified is False ipv6 = ipaddress.cached_ip_addresses('0:0:0:0:0:0:0:0') assert ipv6 is not None assert ipv6.is_link_local is False assert ipv6.is_unspecified is True @pytest.mark.skipif(sys.version_info < (3, 9, 0), reason='scope_id is not supported') def test_get_ip_address_object_from_record(): """Test the get_ip_address_object_from_record.""" # not link local packed = b'&\x06(\x00\x02 \x00\x01\x02H\x18\x93%\xc8\x19F' record = DNSAddress( 'domain.local', const._TYPE_AAAA, const._CLASS_IN | const._CLASS_UNIQUE, 1, packed, scope_id=3 ) assert record.scope_id == 3 assert ipaddress.get_ip_address_object_from_record(record) == ipaddress.IPv6Address( '2606:2800:220:1:248:1893:25c8:1946' ) # link local packed = b'\xfe\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01' record = DNSAddress( 'domain.local', const._TYPE_AAAA, const._CLASS_IN | const._CLASS_UNIQUE, 1, packed, scope_id=3 ) assert record.scope_id == 3 assert ipaddress.get_ip_address_object_from_record(record) == ipaddress.IPv6Address('fe80::1%3') record = DNSAddress('domain.local', const._TYPE_AAAA, const._CLASS_IN | const._CLASS_UNIQUE, 1, packed) assert record.scope_id is None assert ipaddress.get_ip_address_object_from_record(record) == ipaddress.IPv6Address('fe80::1') record = DNSAddress( 'domain.local', const._TYPE_A, const._CLASS_IN | const._CLASS_UNIQUE, 1, packed, scope_id=0 ) assert record.scope_id == 0 # Ensure scope_id of 0 is not appended to the address assert ipaddress.get_ip_address_object_from_record(record) == ipaddress.IPv6Address('fe80::1') 07070100000078000081A40000000000000000000000016619D4CC00000C8E000000000000000000000000000000000000003100000000python-zeroconf-0.132.2/tests/utils/test_name.py#!/usr/bin/env python """Unit tests for zeroconf._utils.name.""" import socket import pytest from zeroconf import BadTypeInNameException from zeroconf._services.info import ServiceInfo, instance_name_from_service_info from zeroconf._utils import name as nameutils def test_service_type_name_overlong_type(): """Test overlong service_type_name type.""" with pytest.raises(BadTypeInNameException): nameutils.service_type_name("Tivo1._tivo-videostream._tcp.local.") nameutils.service_type_name("Tivo1._tivo-videostream._tcp.local.", strict=False) def test_service_type_name_overlong_full_name(): """Test overlong service_type_name full name.""" long_name = "Tivo1Tivo1Tivo1Tivo1Tivo1Tivo1Tivo1Tivo1" * 100 with pytest.raises(BadTypeInNameException): nameutils.service_type_name(f"{long_name}._tivo-videostream._tcp.local.") with pytest.raises(BadTypeInNameException): nameutils.service_type_name(f"{long_name}._tivo-videostream._tcp.local.", strict=False) @pytest.mark.parametrize( "instance_name, service_type", ( ("CustomerInformationService-F4D4885E9EEB", "_ibisip_http._tcp.local."), ("DeviceManagementService_F4D4885E9EEB", "_ibisip_http._tcp.local."), ), ) def test_service_type_name_non_strict_compliant_names(instance_name, service_type): """Test service_type_name for valid names, but not strict-compliant.""" desc = {'path': '/~paulsm/'} service_name = f'{instance_name}.{service_type}' service_server = 'ash-1.local.' service_address = socket.inet_aton("10.0.1.2") info = ServiceInfo( service_type, service_name, 22, 0, 0, desc, service_server, addresses=[service_address] ) assert info.get_name() == instance_name with pytest.raises(BadTypeInNameException): nameutils.service_type_name(service_name) with pytest.raises(BadTypeInNameException): instance_name_from_service_info(info) nameutils.service_type_name(service_name, strict=False) assert instance_name_from_service_info(info, strict=False) == instance_name def test_possible_types(): """Test possible types from name.""" assert nameutils.possible_types('.') == set() assert nameutils.possible_types('local.') == set() assert nameutils.possible_types('_tcp.local.') == set() assert nameutils.possible_types('_test-srvc-type._tcp.local.') == {'_test-srvc-type._tcp.local.'} assert nameutils.possible_types('_any._tcp.local.') == {'_any._tcp.local.'} assert nameutils.possible_types('.._x._tcp.local.') == {'_x._tcp.local.'} assert nameutils.possible_types('x.y._http._tcp.local.') == {'_http._tcp.local.'} assert nameutils.possible_types('1.2.3._mqtt._tcp.local.') == {'_mqtt._tcp.local.'} assert nameutils.possible_types('x.sub._http._tcp.local.') == {'_http._tcp.local.'} assert nameutils.possible_types('6d86f882b90facee9170ad3439d72a4d6ee9f511._zget._http._tcp.local.') == { '_http._tcp.local.', '_zget._http._tcp.local.', } assert nameutils.possible_types('my._printer._sub._http._tcp.local.') == { '_http._tcp.local.', '_sub._http._tcp.local.', '_printer._sub._http._tcp.local.', } 07070100000079000081A40000000000000000000000016619D4CC000024C5000000000000000000000000000000000000003000000000python-zeroconf-0.132.2/tests/utils/test_net.py#!/usr/bin/env python """Unit tests for zeroconf._utils.net.""" import errno import socket import unittest from unittest.mock import MagicMock, Mock, patch import ifaddr import pytest import zeroconf as r from zeroconf._utils import net as netutils def _generate_mock_adapters(): mock_lo0 = Mock(spec=ifaddr.Adapter) mock_lo0.nice_name = "lo0" mock_lo0.ips = [ifaddr.IP("127.0.0.1", 8, "lo0")] mock_lo0.index = 0 mock_eth0 = Mock(spec=ifaddr.Adapter) mock_eth0.nice_name = "eth0" mock_eth0.ips = [ifaddr.IP(("2001:db8::", 1, 1), 8, "eth0")] mock_eth0.index = 1 mock_eth1 = Mock(spec=ifaddr.Adapter) mock_eth1.nice_name = "eth1" mock_eth1.ips = [ifaddr.IP("192.168.1.5", 23, "eth1")] mock_eth1.index = 2 mock_vtun0 = Mock(spec=ifaddr.Adapter) mock_vtun0.nice_name = "vtun0" mock_vtun0.ips = [ifaddr.IP("169.254.3.2", 16, "vtun0")] mock_vtun0.index = 3 return [mock_eth0, mock_lo0, mock_eth1, mock_vtun0] def test_ip6_to_address_and_index(): """Test we can extract from mocked adapters.""" adapters = _generate_mock_adapters() assert netutils.ip6_to_address_and_index(adapters, "2001:db8::") == (('2001:db8::', 1, 1), 1) assert netutils.ip6_to_address_and_index(adapters, "2001:db8::%1") == (('2001:db8::', 1, 1), 1) with pytest.raises(RuntimeError): assert netutils.ip6_to_address_and_index(adapters, "2005:db8::") def test_interface_index_to_ip6_address(): """Test we can extract from mocked adapters.""" adapters = _generate_mock_adapters() assert netutils.interface_index_to_ip6_address(adapters, 1) == ('2001:db8::', 1, 1) # call with invalid adapter with pytest.raises(RuntimeError): assert netutils.interface_index_to_ip6_address(adapters, 6) # call with adapter that has ipv4 address only with pytest.raises(RuntimeError): assert netutils.interface_index_to_ip6_address(adapters, 2) def test_ip6_addresses_to_indexes(): """Test we can extract from mocked adapters.""" interfaces = [1] with patch("zeroconf._utils.net.ifaddr.get_adapters", return_value=_generate_mock_adapters()): assert netutils.ip6_addresses_to_indexes(interfaces) == [(('2001:db8::', 1, 1), 1)] interfaces_2 = ['2001:db8::'] with patch("zeroconf._utils.net.ifaddr.get_adapters", return_value=_generate_mock_adapters()): assert netutils.ip6_addresses_to_indexes(interfaces_2) == [(('2001:db8::', 1, 1), 1)] def test_normalize_interface_choice_errors(): """Test we generate exception on invalid input.""" with patch("zeroconf._utils.net.get_all_addresses", return_value=[]), patch( "zeroconf._utils.net.get_all_addresses_v6", return_value=[] ), pytest.raises(RuntimeError): netutils.normalize_interface_choice(r.InterfaceChoice.All) with pytest.raises(TypeError): netutils.normalize_interface_choice("1.2.3.4") @pytest.mark.parametrize( "errno,expected_result", [(errno.EADDRINUSE, False), (errno.EADDRNOTAVAIL, False), (errno.EINVAL, False), (0, True)], ) def test_add_multicast_member_socket_errors(errno, expected_result): """Test we handle socket errors when adding multicast members.""" if errno: setsockopt_mock = unittest.mock.Mock(side_effect=OSError(errno, f"Error: {errno}")) else: setsockopt_mock = unittest.mock.Mock() fileno_mock = unittest.mock.PropertyMock(return_value=10) socket_mock = unittest.mock.Mock(setsockopt=setsockopt_mock, fileno=fileno_mock) assert r.add_multicast_member(socket_mock, "0.0.0.0") == expected_result def test_autodetect_ip_version(): """Tests for auto detecting IPVersion based on interface ips.""" assert r.autodetect_ip_version(["1.3.4.5"]) is r.IPVersion.V4Only assert r.autodetect_ip_version([]) is r.IPVersion.V4Only assert r.autodetect_ip_version(["::1", "1.2.3.4"]) is r.IPVersion.All assert r.autodetect_ip_version(["::1"]) is r.IPVersion.V6Only def test_disable_ipv6_only_or_raise(): """Test that IPV6_V6ONLY failing logs a nice error message and still raises.""" errors_logged = [] def _log_error(*args): nonlocal errors_logged errors_logged.append(args) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with pytest.raises(OSError), patch.object(netutils.log, "error", _log_error), patch( "socket.socket.setsockopt", side_effect=OSError ): netutils.disable_ipv6_only_or_raise(sock) assert ( errors_logged[0][0] == 'Support for dual V4-V6 sockets is not present, use IPVersion.V4 or IPVersion.V6' ) @pytest.mark.skipif(not hasattr(socket, 'SO_REUSEPORT'), reason="System does not have SO_REUSEPORT") def test_set_so_reuseport_if_available_is_present(): """Test that setting socket.SO_REUSEPORT only OSError errno.ENOPROTOOPT is trapped.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with pytest.raises(OSError), patch("socket.socket.setsockopt", side_effect=OSError): netutils.set_so_reuseport_if_available(sock) with patch("socket.socket.setsockopt", side_effect=OSError(errno.ENOPROTOOPT, None)): netutils.set_so_reuseport_if_available(sock) @pytest.mark.skipif(hasattr(socket, 'SO_REUSEPORT'), reason="System has SO_REUSEPORT") def test_set_so_reuseport_if_available_not_present(): """Test that we do not try to set SO_REUSEPORT if it is not present.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with patch("socket.socket.setsockopt", side_effect=OSError): netutils.set_so_reuseport_if_available(sock) def test_set_mdns_port_socket_options_for_ip_version(): """Test OSError with errno with EINVAL and bind address '' from setsockopt IP_MULTICAST_TTL does not raise.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Should raise on EPERM always with pytest.raises(OSError), patch("socket.socket.setsockopt", side_effect=OSError(errno.EPERM, None)): netutils.set_mdns_port_socket_options_for_ip_version(sock, ('',), r.IPVersion.V4Only) # Should raise on EINVAL always when bind address is not '' with pytest.raises(OSError), patch("socket.socket.setsockopt", side_effect=OSError(errno.EINVAL, None)): netutils.set_mdns_port_socket_options_for_ip_version(sock, ('127.0.0.1',), r.IPVersion.V4Only) # Should not raise on EINVAL when bind address is '' with patch("socket.socket.setsockopt", side_effect=OSError(errno.EINVAL, None)): netutils.set_mdns_port_socket_options_for_ip_version(sock, ('',), r.IPVersion.V4Only) def test_add_multicast_member(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) interface = '127.0.0.1' # EPERM should always raise with pytest.raises(OSError), patch("socket.socket.setsockopt", side_effect=OSError(errno.EPERM, None)): netutils.add_multicast_member(sock, interface) # EADDRINUSE should return False with patch("socket.socket.setsockopt", side_effect=OSError(errno.EADDRINUSE, None)): assert netutils.add_multicast_member(sock, interface) is False # EADDRNOTAVAIL should return False with patch("socket.socket.setsockopt", side_effect=OSError(errno.EADDRNOTAVAIL, None)): assert netutils.add_multicast_member(sock, interface) is False # EINVAL should return False with patch("socket.socket.setsockopt", side_effect=OSError(errno.EINVAL, None)): assert netutils.add_multicast_member(sock, interface) is False # ENOPROTOOPT should return False with patch("socket.socket.setsockopt", side_effect=OSError(errno.ENOPROTOOPT, None)): assert netutils.add_multicast_member(sock, interface) is False # ENODEV should raise for ipv4 with pytest.raises(OSError), patch("socket.socket.setsockopt", side_effect=OSError(errno.ENODEV, None)): netutils.add_multicast_member(sock, interface) is False # ENODEV should return False for ipv6 with patch("socket.socket.setsockopt", side_effect=OSError(errno.ENODEV, None)): assert netutils.add_multicast_member(sock, ('2001:db8::', 1, 1)) is False # type: ignore[arg-type] # No IPv6 support should return False for IPv6 with patch("socket.inet_pton", side_effect=OSError()): assert netutils.add_multicast_member(sock, ('2001:db8::', 1, 1)) is False # type: ignore[arg-type] # No error should return True with patch("socket.socket.setsockopt"): assert netutils.add_multicast_member(sock, interface) is True def test_bind_raises_skips_address(): """Test bind failing in new_socket returns None on EADDRNOTAVAIL.""" err = errno.EADDRNOTAVAIL def _mock_socket(*args, **kwargs): sock = MagicMock() sock.bind = MagicMock(side_effect=OSError(err, f"Error: {err}")) return sock with patch("socket.socket", _mock_socket): assert netutils.new_socket(("0.0.0.0", 0)) is None # type: ignore[arg-type] err = errno.EAGAIN with pytest.raises(OSError), patch("socket.socket", _mock_socket): netutils.new_socket(("0.0.0.0", 0)) # type: ignore[arg-type] def test_new_respond_socket_new_socket_returns_none(): """Test new_respond_socket returns None if new_socket returns None.""" with patch.object(netutils, "new_socket", return_value=None): assert netutils.new_respond_socket(("0.0.0.0", 0)) is None # type: ignore[arg-type] 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!1853 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor