Initial commit

This commit is contained in:
Samuel FORESTIER 2023-06-13 23:03:09 +02:00
commit c9aa596e6c
8 changed files with 506 additions and 0 deletions

176
.gitignore vendored Normal file

@ -0,0 +1,176 @@
# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml
# ruff
.ruff_cache/
# LSP config files
pyrightconfig.json
# End of https://www.toptal.com/developers/gitignore/api/python

21
LICENSE Normal file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Samuel FORESTIER
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

61
README.md Normal file

@ -0,0 +1,61 @@
# hosts_resolver
> Zero-dependency Python module to resolve names using /etc/hosts alone
## Rationale
Sometimes we only want to resolve names using /etc/hosts entries without performing DNS requests (thus `socket.getaddrinfo` is out of the equation).
So there are three options :
* manually parse /etc/hosts
* call `getent` program and parse its output
* use this module (which binds libc `gethostent` function) !
## Limitations
- `gethostent` is not reentrant (see GETHOSTBYNAME(3))
- `gethostent` is not thread-safe (see GETHOSTBYNAME(3))
- glibc implementations does not support IPv6 addresses (see GETHOSTBYNAME(3))
- behavior is **undefined** when using multiple context managers simultaneously
## Installation
```bash
pip3 install hosts_resolver-*-py3-none-any.whl
```
## Usage
### From API
```python
from hosts_resolver import get_hosts_resolver
with get_hosts_resolver() as hosts_resolver:
print(hosts_resolver.resolve("localhost"))
# -> IPv4Address('127.0.0.1')
```
### From CLI
> Why bother ?? You should be looking at `getent` !
```bash
python3 hosts_resolver.py -j localhost
# -> {"localhost": "127.0.0.1"}
```
## Development
```bash
pip3 install -r requirements-dev.txt
pylint src/
mypy src/
isort --check src/
black --check src/
python3 -m build
```

59
pyproject.toml Normal file

@ -0,0 +1,59 @@
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "hosts_resolver"
version = "1.0.0"
authors = [
{name = "Samuel FORESTIER", email = "dev+hostsresolver@samuel.domains"},
]
description = "Zero-dependency Python module to resolve names using /etc/hosts alone"
readme = "README.md"
requires-python = ">=3.6"
keywords = ["DNS", "gethostent", "hosts"]
license = {text = "MIT"}
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: POSIX :: BSD",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Internet :: Name Service (DNS)",
]
[project.scripts]
hosts_resolver = "hosts_resolver.hosts_resolver:main"
[project.urls]
Repository = "https://git.forestier.app/HorlogeSkynet/hosts_resolver"
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
hosts_resolver = ["py.typed"]
[tool.pylint.MASTER]
load-plugins = ["pylint_secure_coding_standard"]
[tool.black]
line-length = 100
target-version = ["py36"]
[tool.isort]
profile = "black"
line_length = 100
py_version = 36

6
requirements-dev.txt Normal file

@ -0,0 +1,6 @@
black~=23.3.0
build~=0.10.0
isort~=5.12.0
mypy~=1.3.0
pylint~=2.17.4
pylint-secure-coding-standard~=1.4.1

3
setup.py Normal file

@ -0,0 +1,3 @@
from setuptools import setup
setup()

@ -0,0 +1,180 @@
"""hosts_resolver module"""
import argparse
import contextlib
import ctypes
import ipaddress
import json
import logging
import os
import socket
import sys
import typing
from pathlib import Path
class _Hostent(ctypes.Structure): # pylint: disable=too-few-public-methods
"""hostent netdb.h structure ctypes mapping"""
_fields_ = [
("h_name", ctypes.c_char_p),
("h_aliases", ctypes.POINTER(ctypes.c_char_p)),
("h_addrtype", ctypes.c_int),
("h_length", ctypes.c_int),
("h_addr_list", ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte))),
]
_IPAddress = typing.Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
_libc = ctypes.CDLL("libc.so.6")
# From <netdb.h> :
## struct hostent *gethostent(void);
_gethostent = _libc.gethostent
_gethostent.restype = ctypes.POINTER(_Hostent)
_gethostent.argtypes = ()
# void endhostent(void);
_endhostent = _libc.endhostent
_endhostent.restype = None
_endhostent.argtypes = ()
_logger = logging.getLogger(Path(__file__).stem)
class _HostsResolver:
"""
_HostsResolver context manager definition.
Use this CM to resolve name using /etc/hosts entries without any DNS request or subprocess call.
Known limitations:
- `gethostent` is not reentrant (see GETHOSTBYNAME(3))
- `gethostent` is not thread-safe (see GETHOSTBYNAME(3))
- glibc implementations does not support IPv6 addresses (see GETHOSTBYNAME(3))
- behavior is **undefined** when using multiple context managers simultaneously
"""
def __init__(self) -> None:
self._cached_aliases: typing.Dict[str, _IPAddress] = {}
def __enter__(self) -> "_HostsResolver":
return self
def __exit__(self, _, __, ___):
_endhostent()
def resolve(self, name: typing.Union[str, _IPAddress]) -> _IPAddress:
"""Try to lazily resolve `name` using /etc/hosts entries. Results are cached"""
# don't try to resolve IP addresses for idempotency !
with contextlib.suppress(ValueError):
return ipaddress.ip_address(name)
while True:
# fetch result from cache (if present)
with contextlib.suppress(KeyError):
return self._cached_aliases[name] # type: ignore[index]
# fetch "next" hosts entry
entry_ptr = ctypes.cast(_gethostent(), ctypes.POINTER(_Hostent))
if not entry_ptr:
_logger.debug("no more hosts entry")
break
# dereference structure pointer
entry = entry_ptr.contents
# decode entry "name"
aliases = [entry.h_name.decode("ascii")]
_logger.debug("got new hosts entry: %s", aliases[0])
# decode entry "aliases"
i = 0
h_aliases = ctypes.cast(entry.h_aliases, ctypes.POINTER(ctypes.c_char_p))
while h_aliases[i]:
aliases.append(h_aliases[i].decode("ascii"))
_logger.debug("found new alias for %s: %s", aliases[0], aliases[-1])
i += 1
# decode "network addresses" from raw bytes array
addresses = ctypes.cast(
entry.h_addr_list,
ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte * entry.h_length)),
)
address = ipaddress.ip_address(bytes(addresses[0].contents))
# populate cache with all entry aliases
for alias in aliases:
_logger.debug("caching %s as %s...", address, alias)
self._cached_aliases[alias] = address
raise socket.gaierror(f"could not resolve: {name}")
@contextlib.contextmanager
def get_hosts_resolver() -> typing.Generator[_HostsResolver, None, None]:
"""Return an `_HostsResolver` instance to use as a context manager"""
with _HostsResolver() as hosts_resolver:
yield hosts_resolver
def main() -> typing.NoReturn:
"""Main entry point"""
parser = argparse.ArgumentParser(
description="Zero-dependency Python module to resolve names using /etc/hosts alone"
)
parser.add_argument(
"-v",
"--version",
action="version",
version="%(prog)s 1.0.0",
)
parser.add_argument(
"-d",
"--debug",
action="store_true",
help="enable debug mode",
)
parser.add_argument(
"-j",
"--json",
action="store_true",
help="output results as JSON",
)
parser.add_argument(
"names",
nargs="+",
help="names to resolve using /etc/hosts",
)
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)
results: typing.Dict[str, typing.Optional[str]] = {}
with get_hosts_resolver() as hosts_resolver:
for name in args.names:
try:
results[name] = str(hosts_resolver.resolve(name))
except socket.gaierror:
# if JSON output is disabled, exit fast to prevent inconsistent output
if not args.json:
raise
_logger.exception("resolution failed for %s", name)
results[name] = None
if args.json:
print(json.dumps(results, indent=4 if args.debug else None))
else:
print(os.linesep.join(results.values())) # type: ignore[arg-type]
# exit with error if (at least) a resolution failed
sys.exit(not all(results.values()))
if __name__ == "__main__":
main()