| 1 |
# This code is part of the Ansible collection community.docker, but is an independent component. |
| 2 |
# This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/) |
| 3 |
# |
| 4 |
# Copyright (c) 2016-2022 Docker, Inc. |
| 5 |
# |
| 6 |
# It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection) |
| 7 |
# SPDX-License-Identifier: Apache-2.0 |
| 8 |
|
| 9 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 10 |
# Do not use this from other collections or standalone plugins/modules! |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
import functools |
| 15 |
import io |
| 16 |
import time |
| 17 |
import traceback |
| 18 |
import typing as t |
| 19 |
|
| 20 |
PYWIN32_IMPORT_ERROR: str | None # pylint: disable=invalid-name |
| 21 |
try: |
| 22 |
import pywintypes |
| 23 |
import win32api |
| 24 |
import win32event |
| 25 |
import win32file |
| 26 |
import win32pipe |
| 27 |
except ImportError: |
| 28 |
PYWIN32_IMPORT_ERROR = traceback.format_exc() # pylint: disable=invalid-name |
| 29 |
else: |
| 30 |
PYWIN32_IMPORT_ERROR = None # pylint: disable=invalid-name |
| 31 |
|
| 32 |
if t.TYPE_CHECKING: |
| 33 |
from collections.abc import Buffer, Callable |
| 34 |
|
| 35 |
_Self = t.TypeVar("_Self") |
| 36 |
_P = t.ParamSpec("_P") |
| 37 |
_R = t.TypeVar("_R") |
| 38 |
|
| 39 |
|
| 40 |
ERROR_PIPE_BUSY = 0xE7 |
| 41 |
SECURITY_SQOS_PRESENT = 0x100000 |
| 42 |
SECURITY_ANONYMOUS = 0 |
| 43 |
|
| 44 |
MAXIMUM_RETRY_COUNT = 10 |
| 45 |
|
| 46 |
|
| 47 |
def check_closed( |
| 48 |
f: Callable[t.Concatenate[_Self, _P], _R], |
| 49 |
) -> Callable[t.Concatenate[_Self, _P], _R]: |
| 50 |
@functools.wraps(f) |
| 51 |
def wrapped(self: _Self, *args: _P.args, **kwargs: _P.kwargs) -> _R: |
| 52 |
if self._closed: # type: ignore |
| 53 |
raise RuntimeError("Can not reuse socket after connection was closed.") |
| 54 |
return f(self, *args, **kwargs) |
| 55 |
|
| 56 |
return wrapped |
| 57 |
|
| 58 |
|
| 59 |
class NpipeSocket: |
| 60 |
"""Partial implementation of the socket API over windows named pipes. |
| 61 |
This implementation is only designed to be used as a client socket, |
| 62 |
and server-specific methods (bind, listen, accept...) are not |
| 63 |
implemented. |
| 64 |
""" |
| 65 |
|
| 66 |
def __init__(self, handle: t.Any | None = None) -> None: |
| 67 |
self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT |
| 68 |
self._handle = handle |
| 69 |
self._address: str | None = None |
| 70 |
self._closed = False |
| 71 |
self.flags: int | None = None |
| 72 |
|
| 73 |
def accept(self) -> t.NoReturn: |
| 74 |
raise NotImplementedError() |
| 75 |
|
| 76 |
def bind(self, address: t.Any) -> t.NoReturn: |
| 77 |
raise NotImplementedError() |
| 78 |
|
| 79 |
def close(self) -> None: |
| 80 |
if self._handle is None: |
| 81 |
raise ValueError("Handle not present") |
| 82 |
self._handle.Close() |
| 83 |
self._closed = True |
| 84 |
|
| 85 |
@check_closed |
| 86 |
def connect(self, address: str, retry_count: int = 0) -> None: |
| 87 |
try: |
| 88 |
handle = win32file.CreateFile( |
| 89 |
address, |
| 90 |
win32file.GENERIC_READ | win32file.GENERIC_WRITE, |
| 91 |
0, |
| 92 |
None, |
| 93 |
win32file.OPEN_EXISTING, |
| 94 |
( |
| 95 |
SECURITY_ANONYMOUS |
| 96 |
| SECURITY_SQOS_PRESENT |
| 97 |
| win32file.FILE_FLAG_OVERLAPPED |
| 98 |
), |
| 99 |
0, |
| 100 |
) |
| 101 |
except win32pipe.error as e: |
| 102 |
# See Remarks: |
| 103 |
# https://msdn.microsoft.com/en-us/library/aa365800.aspx |
| 104 |
if e.winerror == ERROR_PIPE_BUSY: |
| 105 |
# Another program or thread has grabbed our pipe instance |
| 106 |
# before we got to it. Wait for availability and attempt to |
| 107 |
# connect again. |
| 108 |
retry_count = retry_count + 1 |
| 109 |
if retry_count < MAXIMUM_RETRY_COUNT: |
| 110 |
time.sleep(1) |
| 111 |
return self.connect(address, retry_count) |
| 112 |
raise e |
| 113 |
|
| 114 |
self.flags = win32pipe.GetNamedPipeInfo(handle)[0] # type: ignore |
| 115 |
|
| 116 |
self._handle = handle |
| 117 |
self._address = address |
| 118 |
|
| 119 |
@check_closed |
| 120 |
def connect_ex(self, address: str) -> None: |
| 121 |
self.connect(address) |
| 122 |
|
| 123 |
@check_closed |
| 124 |
def detach(self) -> t.Any: |
| 125 |
self._closed = True |
| 126 |
return self._handle |
| 127 |
|
| 128 |
@check_closed |
| 129 |
def dup(self) -> NpipeSocket: |
| 130 |
return NpipeSocket(self._handle) |
| 131 |
|
| 132 |
def getpeername(self) -> str | None: |
| 133 |
return self._address |
| 134 |
|
| 135 |
def getsockname(self) -> str | None: |
| 136 |
return self._address |
| 137 |
|
| 138 |
def getsockopt( |
| 139 |
self, level: t.Any, optname: t.Any, buflen: t.Any = None |
| 140 |
) -> t.NoReturn: |
| 141 |
raise NotImplementedError() |
| 142 |
|
| 143 |
def ioctl(self, control: t.Any, option: t.Any) -> t.NoReturn: |
| 144 |
raise NotImplementedError() |
| 145 |
|
| 146 |
def listen(self, backlog: t.Any) -> t.NoReturn: |
| 147 |
raise NotImplementedError() |
| 148 |
|
| 149 |
def makefile(self, mode: str, bufsize: int | None = None) -> t.IO[bytes]: |
| 150 |
if mode.strip("b") != "r": |
| 151 |
raise NotImplementedError() |
| 152 |
rawio = NpipeFileIOBase(self) |
| 153 |
if bufsize is None or bufsize <= 0: |
| 154 |
bufsize = io.DEFAULT_BUFFER_SIZE |
| 155 |
return io.BufferedReader(rawio, buffer_size=bufsize) |
| 156 |
|
| 157 |
@check_closed |
| 158 |
def recv(self, bufsize: int, flags: int = 0) -> str: |
| 159 |
if self._handle is None: |
| 160 |
raise ValueError("Handle not present") |
| 161 |
dummy_err, data = win32file.ReadFile(self._handle, bufsize) |
| 162 |
return data |
| 163 |
|
| 164 |
@check_closed |
| 165 |
def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[str, str | None]: |
| 166 |
data = self.recv(bufsize, flags) |
| 167 |
return (data, self._address) |
| 168 |
|
| 169 |
@check_closed |
| 170 |
def recvfrom_into( |
| 171 |
self, buf: Buffer, nbytes: int = 0, flags: int = 0 |
| 172 |
) -> tuple[int, str | None]: |
| 173 |
return self.recv_into(buf, nbytes), self._address |
| 174 |
|
| 175 |
@check_closed |
| 176 |
def recv_into(self, buf: Buffer, nbytes: int = 0) -> int: |
| 177 |
if self._handle is None: |
| 178 |
raise ValueError("Handle not present") |
| 179 |
readbuf = buf if isinstance(buf, memoryview) else memoryview(buf) |
| 180 |
|
| 181 |
event = win32event.CreateEvent(None, True, True, None) |
| 182 |
try: |
| 183 |
overlapped = pywintypes.OVERLAPPED() |
| 184 |
overlapped.hEvent = event |
| 185 |
dummy_err, dummy_data = win32file.ReadFile( # type: ignore |
| 186 |
self._handle, readbuf[:nbytes] if nbytes else readbuf, overlapped |
| 187 |
) |
| 188 |
wait_result = win32event.WaitForSingleObject(event, self._timeout) |
| 189 |
if wait_result == win32event.WAIT_TIMEOUT: |
| 190 |
win32file.CancelIo(self._handle) |
| 191 |
raise TimeoutError |
| 192 |
return win32file.GetOverlappedResult(self._handle, overlapped, 0) |
| 193 |
finally: |
| 194 |
win32api.CloseHandle(event) |
| 195 |
|
| 196 |
@check_closed |
| 197 |
def send(self, string: Buffer, flags: int = 0) -> int: |
| 198 |
if self._handle is None: |
| 199 |
raise ValueError("Handle not present") |
| 200 |
event = win32event.CreateEvent(None, True, True, None) |
| 201 |
try: |
| 202 |
overlapped = pywintypes.OVERLAPPED() |
| 203 |
overlapped.hEvent = event |
| 204 |
win32file.WriteFile(self._handle, string, overlapped) # type: ignore |
| 205 |
wait_result = win32event.WaitForSingleObject(event, self._timeout) |
| 206 |
if wait_result == win32event.WAIT_TIMEOUT: |
| 207 |
win32file.CancelIo(self._handle) |
| 208 |
raise TimeoutError |
| 209 |
return win32file.GetOverlappedResult(self._handle, overlapped, 0) |
| 210 |
finally: |
| 211 |
win32api.CloseHandle(event) |
| 212 |
|
| 213 |
@check_closed |
| 214 |
def sendall(self, string: Buffer, flags: int = 0) -> int: |
| 215 |
return self.send(string, flags) |
| 216 |
|
| 217 |
@check_closed |
| 218 |
def sendto(self, string: Buffer, address: str) -> int: |
| 219 |
self.connect(address) |
| 220 |
return self.send(string) |
| 221 |
|
| 222 |
def setblocking(self, flag: bool) -> None: |
| 223 |
if flag: |
| 224 |
return self.settimeout(None) |
| 225 |
return self.settimeout(0) |
| 226 |
|
| 227 |
def settimeout(self, value: int | float | None) -> None: |
| 228 |
if value is None: |
| 229 |
# Blocking mode |
| 230 |
self._timeout = win32event.INFINITE |
| 231 |
elif not isinstance(value, (float, int)) or value < 0: |
| 232 |
raise ValueError("Timeout value out of range") |
| 233 |
else: |
| 234 |
# Timeout mode - Value converted to milliseconds |
| 235 |
self._timeout = int(value * 1000) |
| 236 |
|
| 237 |
def gettimeout(self) -> int | float | None: |
| 238 |
return self._timeout |
| 239 |
|
| 240 |
def setsockopt(self, level: t.Any, optname: t.Any, value: t.Any) -> t.NoReturn: |
| 241 |
raise NotImplementedError() |
| 242 |
|
| 243 |
@check_closed |
| 244 |
def shutdown(self, how: t.Any) -> None: |
| 245 |
return self.close() |
| 246 |
|
| 247 |
|
| 248 |
class NpipeFileIOBase(io.RawIOBase): |
| 249 |
def __init__(self, npipe_socket: NpipeSocket | None) -> None: |
| 250 |
self.sock = npipe_socket |
| 251 |
|
| 252 |
def close(self) -> None: |
| 253 |
super().close() |
| 254 |
self.sock = None |
| 255 |
|
| 256 |
def fileno(self) -> int: |
| 257 |
if self.sock is None: |
| 258 |
raise RuntimeError("socket is closed") |
| 259 |
# TODO: This is definitely a bug, NpipeSocket.fileno() does not exist! |
| 260 |
return self.sock.fileno() # type: ignore |
| 261 |
|
| 262 |
def isatty(self) -> bool: |
| 263 |
return False |
| 264 |
|
| 265 |
def readable(self) -> bool: |
| 266 |
return True |
| 267 |
|
| 268 |
def readinto(self, buf: Buffer) -> int: |
| 269 |
if self.sock is None: |
| 270 |
raise RuntimeError("socket is closed") |
| 271 |
return self.sock.recv_into(buf) |
| 272 |
|
| 273 |
def seekable(self) -> bool: |
| 274 |
return False |
| 275 |
|
| 276 |
def writable(self) -> bool: |
| 277 |
return False |