2019-03-17 03:44:05 +00:00
|
|
|
"""The ping component."""
|
2021-03-31 13:06:49 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-10-20 21:46:33 +00:00
|
|
|
from dataclasses import dataclass
|
2021-03-31 13:06:49 +00:00
|
|
|
import logging
|
|
|
|
|
|
|
|
from icmplib import SocketPermissionError, ping as icmp_ping
|
2020-08-28 17:40:30 +00:00
|
|
|
|
2022-01-02 15:35:23 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
2023-06-01 15:30:15 +00:00
|
|
|
from homeassistant.helpers import config_validation as cv
|
2021-03-31 13:06:49 +00:00
|
|
|
from homeassistant.helpers.reload import async_setup_reload_service
|
2022-01-02 15:35:23 +00:00
|
|
|
from homeassistant.helpers.typing import ConfigType
|
2021-03-31 13:06:49 +00:00
|
|
|
|
2023-10-20 21:46:33 +00:00
|
|
|
from .const import DOMAIN, PLATFORMS
|
2021-03-31 13:06:49 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
2020-09-09 20:19:14 +00:00
|
|
|
|
2023-06-01 15:30:15 +00:00
|
|
|
CONFIG_SCHEMA = cv.platform_only_config_schema(DOMAIN)
|
|
|
|
|
2020-09-09 20:19:14 +00:00
|
|
|
|
2023-10-20 21:46:33 +00:00
|
|
|
@dataclass(slots=True)
|
|
|
|
class PingDomainData:
|
|
|
|
"""Dataclass to store privileged status."""
|
|
|
|
|
|
|
|
privileged: bool | None
|
|
|
|
|
|
|
|
|
2022-01-02 15:35:23 +00:00
|
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
2023-05-28 15:11:46 +00:00
|
|
|
"""Set up the ping integration."""
|
2021-03-31 13:06:49 +00:00
|
|
|
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
|
2023-10-20 21:46:33 +00:00
|
|
|
|
|
|
|
hass.data[DOMAIN] = PingDomainData(
|
|
|
|
privileged=await hass.async_add_executor_job(_can_use_icmp_lib_with_privilege),
|
|
|
|
)
|
|
|
|
|
2021-03-31 13:06:49 +00:00
|
|
|
return True
|
2020-09-09 20:19:14 +00:00
|
|
|
|
|
|
|
|
2021-03-31 13:06:49 +00:00
|
|
|
def _can_use_icmp_lib_with_privilege() -> None | bool:
|
|
|
|
"""Verify we can create a raw socket."""
|
|
|
|
try:
|
|
|
|
icmp_ping("127.0.0.1", count=0, timeout=0, privileged=True)
|
|
|
|
except SocketPermissionError:
|
|
|
|
try:
|
|
|
|
icmp_ping("127.0.0.1", count=0, timeout=0, privileged=False)
|
|
|
|
except SocketPermissionError:
|
|
|
|
_LOGGER.debug(
|
2022-12-23 12:27:27 +00:00
|
|
|
"Cannot use icmplib because privileges are insufficient to create the"
|
|
|
|
" socket"
|
2021-03-31 13:06:49 +00:00
|
|
|
)
|
|
|
|
return None
|
2023-01-18 13:10:13 +00:00
|
|
|
|
|
|
|
_LOGGER.debug("Using icmplib in privileged=False mode")
|
|
|
|
return False
|
|
|
|
|
|
|
|
_LOGGER.debug("Using icmplib in privileged=True mode")
|
|
|
|
return True
|