This commit is contained in:
恍兮惚兮 2024-08-09 21:33:34 +08:00
parent e482d179f7
commit d23939555e
9 changed files with 265 additions and 252 deletions

View File

@ -1,5 +1,5 @@
import gobject, os import gobject, os
from requests import RequestException from requests import RequestException, Timeout
from ctypes import ( from ctypes import (
CDLL, CDLL,
c_void_p, c_void_p,
@ -322,13 +322,21 @@ class AutoCURLHandle(CURL):
class CURLException(RequestException): class CURLException(RequestException):
def __init__(self, code) -> None: def __init__(self, code) -> None:
if isinstance(code, CURLcode): if not isinstance(code, CURLcode):
self.errorcode = code.value
error = curl_easy_strerror(code).decode("utf8")
for _ in dir(CURLcode):
if _.startswith("") and code.value == getattr(CURLcode, _):
error = str(code.value) + " " + _ + " : " + error
break
else:
raise Exception("not a valid CURLException") raise Exception("not a valid CURLException")
self.errorcode = code.value
error = curl_easy_strerror(code).decode("utf8")
for _ in dir(CURLcode):
if _.startswith("") and code.value == getattr(CURLcode, _):
error = f"{_}: {error}"
break
super().__init__(error) super().__init__(error)
def MaybeRaiseException(error: CURLcode):
if not error.value:
return
e = CURLException(error)
if error.value == CURLcode.OPERATION_TIMEDOUT:
raise Timeout(e)
raise e

View File

@ -5,6 +5,8 @@ from requests import ResponseBase, Timeout, Requester_common
from traceback import print_exc from traceback import print_exc
class Response(ResponseBase): class Response(ResponseBase):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
@ -35,22 +37,7 @@ class Response(ResponseBase):
downloadeddata = downloadeddata[chunk_size:] downloadeddata = downloadeddata[chunk_size:]
def raise_for_status(self): def raise_for_status(self):
if self.last_error: MaybeRaiseException(self.last_error)
raise CURLException(self.last_error)
def ExceptionFilter(func):
def _wrapper(*args, **kwargs):
try:
_ = func(*args, **kwargs)
return _
except CURLException as e:
if e.errorcode == CURLcode.OPERATION_TIMEDOUT:
raise Timeout(e)
else:
raise e
return _wrapper
class autostatus: class autostatus:
@ -77,9 +64,7 @@ class Requester(Requester_common):
return curl return curl
def raise_for_status(self): def raise_for_status(self):
if self.last_error: MaybeRaiseException(self.last_error)
raise CURLException(self.last_error)
def _getStatusCode(self, curl): def _getStatusCode(self, curl):
status_code = c_long() status_code = c_long()
self.last_error = curl_easy_getinfo( self.last_error = curl_easy_getinfo(
@ -153,7 +138,6 @@ class Requester(Requester_common):
cookie = self._parsecookie(cookies) cookie = self._parsecookie(cookies)
curl_easy_setopt(curl, CURLoption.COOKIE, cookie.encode("utf8")) curl_easy_setopt(curl, CURLoption.COOKIE, cookie.encode("utf8"))
@ExceptionFilter
def request_impl( def request_impl(
self, self,
method, method,

View File

@ -13,8 +13,7 @@ class WebSocket:
_t = CURLWS_BINARY _t = CURLWS_BINARY
sent = c_size_t() sent = c_size_t()
error = curl_ws_send(self.curl, data, len(data), pointer(sent), 0, _t) error = curl_ws_send(self.curl, data, len(data), pointer(sent), 0, _t)
if error: MaybeRaiseException(error)
raise CURLException(error)
def recv(self): def recv(self):
time.sleep(0.01) time.sleep(0.01)
@ -29,7 +28,7 @@ class WebSocket:
if error.value == CURLcode.AGAIN: if error.value == CURLcode.AGAIN:
time.sleep(0.01) time.sleep(0.01)
elif error: elif error:
raise CURLException(error) MaybeRaiseException(error)
else: else:
break break
if meta.contents.flags & CURLWS_TEXT: if meta.contents.flags & CURLWS_TEXT:
@ -110,5 +109,4 @@ class WebSocket:
curl_easy_setopt(self.curl, CURLoption.HTTPHEADER, lheaders) curl_easy_setopt(self.curl, CURLoption.HTTPHEADER, lheaders)
error = curl_easy_perform(self.curl) error = curl_easy_perform(self.curl)
if error: MaybeRaiseException(error)
raise CURLException(error)

View File

@ -1,6 +1,7 @@
from .winhttp import * from .winhttp import *
from requests import ResponseBase, Timeout, Requester_common from requests import ResponseBase, Timeout, Requester_common
from traceback import print_exc from traceback import print_exc
import windows
import gzip, zlib import gzip, zlib
from ctypes import pointer, create_string_buffer, create_unicode_buffer from ctypes import pointer, create_string_buffer, create_unicode_buffer
@ -12,6 +13,7 @@ except:
print_exc() print_exc()
class Response(ResponseBase): class Response(ResponseBase):
def iter_content_impl(self, chunk_size=1): def iter_content_impl(self, chunk_size=1):
availableSize = DWORD() availableSize = DWORD()
@ -20,7 +22,7 @@ class Response(ResponseBase):
while True: while True:
succ = WinHttpQueryDataAvailable(self.hreq, pointer(availableSize)) succ = WinHttpQueryDataAvailable(self.hreq, pointer(availableSize))
if succ == 0: if succ == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
if availableSize.value == 0: if availableSize.value == 0:
break break
buff = create_string_buffer(availableSize.value) buff = create_string_buffer(availableSize.value)
@ -28,7 +30,7 @@ class Response(ResponseBase):
self.hreq, buff, availableSize, pointer(downloadedSize) self.hreq, buff, availableSize, pointer(downloadedSize)
) )
if succ == 0: if succ == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
if chunk_size: if chunk_size:
downloadeddata += buff[: downloadedSize.value] downloadeddata += buff[: downloadedSize.value]
@ -42,23 +44,7 @@ class Response(ResponseBase):
downloadeddata = downloadeddata[chunk_size:] downloadeddata = downloadeddata[chunk_size:]
def raise_for_status(self): def raise_for_status(self):
error = GetLastError() MaybeRaiseException()
if error:
raise WinhttpException(error)
def ExceptionFilter(func):
def _wrapper(*args, **kwargs):
try:
_ = func(*args, **kwargs)
return _
except WinhttpException as e:
if e.errorcode == WinhttpException.ERROR_WINHTTP_TIMEOUT:
raise Timeout(e)
else:
raise e
return _wrapper
class Requester(Requester_common): class Requester(Requester_common):
@ -99,9 +85,7 @@ class Requester(Requester_common):
None, None,
) )
if bResults == 0: if bResults == 0:
error = GetLastError() MaybeRaiseException()
if error:
raise WinhttpException(error)
return dwStatusCode.value return dwStatusCode.value
def _set_proxy(self, hsess, proxy): def _set_proxy(self, hsess, proxy):
@ -138,9 +122,8 @@ class Requester(Requester_common):
) )
) )
if self.hSession == 0: if self.hSession == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
@ExceptionFilter
def request_impl( def request_impl(
self, self,
method, method,
@ -160,12 +143,11 @@ class Requester(Requester_common):
): ):
headers = self._parseheader(_headers, cookies) headers = self._parseheader(_headers, cookies)
flag = WINHTTP_FLAG_SECURE if scheme == "https" else 0 flag = WINHTTP_FLAG_SECURE if scheme == "https" else 0
# print(server,port,param,databytes)
headers = "\r\n".join(headers) headers = "\r\n".join(headers)
hConnect = AutoWinHttpHandle(WinHttpConnect(self.hSession, server, port, 0)) hConnect = AutoWinHttpHandle(WinHttpConnect(self.hSession, server, port, 0))
if hConnect == 0: if hConnect == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
hRequest = AutoWinHttpHandle( hRequest = AutoWinHttpHandle(
WinHttpOpenRequest( WinHttpOpenRequest(
hConnect, hConnect,
@ -180,7 +162,7 @@ class Requester(Requester_common):
if timeout: if timeout:
WinHttpSetTimeouts(hRequest, timeout, timeout, timeout, timeout) WinHttpSetTimeouts(hRequest, timeout, timeout, timeout, timeout)
if hRequest == 0: if hRequest == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
self._set_verify(hRequest, verify) self._set_verify(hRequest, verify)
self._set_proxy(hRequest, proxy) self._set_proxy(hRequest, proxy)
self._set_allow_redirects(hRequest, allow_redirects) self._set_allow_redirects(hRequest, allow_redirects)
@ -188,11 +170,11 @@ class Requester(Requester_common):
hRequest, headers, -1, databytes, len(databytes), len(databytes), None hRequest, headers, -1, databytes, len(databytes), len(databytes), None
) )
if succ == 0: if succ == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
succ = WinHttpReceiveResponse(hRequest, None) succ = WinHttpReceiveResponse(hRequest, None)
if succ == 0: if succ == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
resp = Response() resp = Response()
resp.headers, resp.cookies = self._parseheader2dict(self._getheaders(hRequest)) resp.headers, resp.cookies = self._parseheader2dict(self._getheaders(hRequest))
@ -208,7 +190,7 @@ class Requester(Requester_common):
while True: while True:
succ = WinHttpQueryDataAvailable(hRequest, pointer(availableSize)) succ = WinHttpQueryDataAvailable(hRequest, pointer(availableSize))
if succ == 0: if succ == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
if availableSize.value == 0: if availableSize.value == 0:
break break
buff = create_string_buffer(availableSize.value) buff = create_string_buffer(availableSize.value)
@ -216,7 +198,7 @@ class Requester(Requester_common):
hRequest, buff, availableSize, pointer(downloadedSize) hRequest, buff, availableSize, pointer(downloadedSize)
) )
if succ == 0: if succ == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
downloadeddata += buff[: downloadedSize.value] downloadeddata += buff[: downloadedSize.value]
resp.content = self.decompress(downloadeddata, resp.headers) resp.content = self.decompress(downloadeddata, resp.headers)

View File

@ -12,9 +12,7 @@ class WebSocket:
_t = WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE _t = WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
datalen = len(data) datalen = len(data)
dwError = WinHttpWebSocketSend(self.hWebSocketHandle, _t, data, datalen) dwError = WinHttpWebSocketSend(self.hWebSocketHandle, _t, data, datalen)
MaybeRaiseException(dwError)
if ERROR_SUCCESS != dwError:
raise WinhttpException(dwError)
def recv(self): def recv(self):
eBufferType = DWORD(0) eBufferType = DWORD(0)
@ -30,19 +28,18 @@ class WebSocket:
pointer(dwBytesTransferred), pointer(dwBytesTransferred),
pointer(eBufferType), pointer(eBufferType),
) )
if dwError == ERROR_SUCCESS: MaybeRaiseException(dwError)
if eBufferType.value in [
WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE, if eBufferType.value in [
WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE, WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE,
]: WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE,
return pbCurrentBufferPointer[: dwBytesTransferred.value].decode("utf8") ]:
elif eBufferType.value in [ return pbCurrentBufferPointer[: dwBytesTransferred.value].decode("utf8")
WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE, elif eBufferType.value in [
WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE, WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE,
]: WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE,
return pbCurrentBufferPointer[: dwBytesTransferred.value] ]:
else: return pbCurrentBufferPointer[: dwBytesTransferred.value]
raise WinhttpException(dwError)
def close(self): def close(self):
if self.hWebSocketHandle: if self.hWebSocketHandle:
@ -70,7 +67,7 @@ class WebSocket:
elif scheme == "ws": elif scheme == "ws":
ishttps = False ishttps = False
else: else:
raise WinhttpException("unknown scheme " + scheme) raise RequestException("unknown scheme " + scheme)
spl = server.split(":") spl = server.split(":")
if len(spl) == 2: if len(spl) == 2:
server = spl[0] server = spl[0]
@ -82,7 +79,7 @@ class WebSocket:
else: else:
port = INTERNET_DEFAULT_HTTP_PORT port = INTERNET_DEFAULT_HTTP_PORT
else: else:
raise WinhttpException("invalid url") raise RequestException("invalid url")
if len(query): if len(query):
path += "?" + query path += "?" + query
return ishttps, server, port, path return ishttps, server, port, path
@ -114,13 +111,13 @@ class WebSocket:
) )
) )
if self.hSession == 0: if self.hSession == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
self._setproxy(self.hSession, http_proxy_host, http_proxy_port) self._setproxy(self.hSession, http_proxy_host, http_proxy_port)
self.hConnect = AutoWinHttpHandle( self.hConnect = AutoWinHttpHandle(
WinHttpConnect(self.hSession, server, port, 0) WinHttpConnect(self.hSession, server, port, 0)
) )
if self.hConnect == 0: if self.hConnect == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
hRequest = AutoWinHttpHandle( hRequest = AutoWinHttpHandle(
WinHttpOpenRequest( WinHttpOpenRequest(
self.hConnect, self.hConnect,
@ -133,26 +130,26 @@ class WebSocket:
) )
) )
if hRequest == 0: if hRequest == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
fStatus = WinHttpSetOption( fStatus = WinHttpSetOption(
hRequest, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, NULL, 0 hRequest, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, NULL, 0
) )
if fStatus == 0: if fStatus == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
fStatus = WinHttpSendRequest( fStatus = WinHttpSendRequest(
hRequest, self._parseheader(header), -1, WINHTTP_NO_REQUEST_DATA, 0, 0, None hRequest, self._parseheader(header), -1, WINHTTP_NO_REQUEST_DATA, 0, 0, None
) )
if fStatus == 0: if fStatus == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
fStatus = WinHttpReceiveResponse(hRequest, 0) fStatus = WinHttpReceiveResponse(hRequest, 0)
if fStatus == 0: if fStatus == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
self.hWebSocketHandle = AutoWinHttpHandle( self.hWebSocketHandle = AutoWinHttpHandle(
WinHttpWebSocketCompleteUpgrade(hRequest, NULL) WinHttpWebSocketCompleteUpgrade(hRequest, NULL)
) )
if self.hWebSocketHandle == 0: if self.hWebSocketHandle == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()

View File

@ -1,6 +1,148 @@
from ctypes import windll, POINTER, pointer, Structure, sizeof from ctypes import windll, POINTER, pointer, Structure, sizeof
from ctypes.wintypes import LPCWSTR, DWORD, LPVOID, WORD, BOOL, LPCVOID, LPWSTR, USHORT from ctypes.wintypes import LPCWSTR, DWORD, LPVOID, WORD, BOOL, LPCVOID, LPWSTR, USHORT
from requests import RequestException from requests import RequestException, Timeout
import windows
# typedef
HINTERNET = LPVOID
INTERNET_PORT = WORD
DWORD_PTR = POINTER(DWORD)
LPDWORD = POINTER(DWORD)
# const
NULL = None
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0
WINHTTP_NO_PROXY_NAME = None
WINHTTP_NO_PROXY_BYPASS = None
INTERNET_DEFAULT_PORT = 0
INTERNET_DEFAULT_HTTP_PORT = 80
INTERNET_DEFAULT_HTTPS_PORT = 443
WINHTTP_NO_REFERER = None
WINHTTP_DEFAULT_ACCEPT_TYPES = None
# WINHTTP_FLAG_REFRESH
WINHTTP_FLAG_SECURE = 0x00800000 # https
WINHTTP_NO_ADDITIONAL_HEADERS = None
WINHTTP_NO_REQUEST_DATA = None
WINHTTP_QUERY_SET_COOKIE = 43
WINHTTP_QUERY_RAW_HEADERS_CRLF = 22
WINHTTP_HEADER_NAME_BY_INDEX = None
WINHTTP_NO_HEADER_INDEX = None
ERROR_INSUFFICIENT_BUFFER = 122
WINHTTP_OPTION_PROXY = 38
WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3
WINHTTP_QUERY_STATUS_CODE = 19
WINHTTP_QUERY_FLAG_NUMBER = 0x20000000
WINHTTP_OPTION_SECURITY_FLAGS = 31
SECURITY_FLAG_IGNORE_UNKNOWN_CA = 0x00000100
SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE = 0x00000200
SECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000 # bad common name in X509 Cert.
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = 0x00002000 # expired X509 Cert.
SECURITY_FLAG_IGNORE_ALL_CERT_ERRORS = (
SECURITY_FLAG_IGNORE_UNKNOWN_CA
| SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE
| SECURITY_FLAG_IGNORE_CERT_CN_INVALID
| SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
)
# function
kernel32 = windll.kernel32
Winhttp = windll.Winhttp
WinHttpOpen = Winhttp.WinHttpOpen
WinHttpOpen.argtypes = LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD
WinHttpOpen.restype = HINTERNET
WinHttpCloseHandle = Winhttp.WinHttpCloseHandle
WinHttpCloseHandle.argtypes = (HINTERNET,)
WinHttpSetTimeouts = Winhttp.WinHttpSetTimeouts
WinHttpSetTimeouts.argtypes = HINTERNET, DWORD, DWORD, DWORD, DWORD
WinHttpSetTimeouts.restype = BOOL
WinHttpConnect = Winhttp.WinHttpConnect
WinHttpConnect.argtypes = HINTERNET, LPCWSTR, INTERNET_PORT, DWORD
WinHttpConnect.restype = HINTERNET
WinHttpOpenRequest = Winhttp.WinHttpOpenRequest
WinHttpOpenRequest.argtypes = (
HINTERNET,
LPCWSTR,
LPCWSTR,
LPCWSTR,
LPCWSTR,
POINTER(LPCWSTR),
DWORD,
)
WinHttpOpenRequest.restype = HINTERNET
WinHttpSendRequest = Winhttp.WinHttpSendRequest
WinHttpSendRequest.argtypes = HINTERNET, LPCWSTR, DWORD, LPVOID, DWORD, DWORD, DWORD_PTR
WinHttpSendRequest.restype = BOOL
WinHttpReceiveResponse = Winhttp.WinHttpReceiveResponse
WinHttpReceiveResponse.argtypes = HINTERNET, LPVOID
WinHttpReceiveResponse.restype = BOOL
WinHttpQueryDataAvailable = Winhttp.WinHttpQueryDataAvailable
WinHttpQueryDataAvailable.argtypes = HINTERNET, LPDWORD
WinHttpQueryDataAvailable.restype = BOOL
WinHttpReadData = Winhttp.WinHttpReadData
WinHttpReadData.argtypes = HINTERNET, LPVOID, DWORD, LPDWORD
WinHttpReadData.restype = BOOL
WinHttpWriteData = Winhttp.WinHttpWriteData
WinHttpWriteData.argtypes = HINTERNET, LPCVOID, DWORD, LPDWORD
WinHttpWriteData.restype = BOOL
WinHttpQueryHeaders = Winhttp.WinHttpQueryHeaders
WinHttpQueryHeaders.argtypes = HINTERNET, DWORD, LPCWSTR, LPVOID, LPDWORD, LPDWORD
WinHttpQueryHeaders.restype = BOOL
WinHttpSetOption = Winhttp.WinHttpSetOption
WinHttpSetOption.argtypes = HINTERNET, DWORD, LPVOID, DWORD
WinHttpSetOption.restype = BOOL
class WINHTTP_PROXY_INFO(Structure):
_fields_ = [
("dwAccessType", DWORD),
("lpszProxy", LPWSTR),
("lpszProxyBypass", LPWSTR),
]
class AutoWinHttpHandle(HINTERNET):
def __del__(self):
if self:
WinHttpCloseHandle(self)
try:
WinHttpWebSocketCompleteUpgrade = Winhttp.WinHttpWebSocketCompleteUpgrade
WinHttpWebSocketCompleteUpgrade.argtypes = HINTERNET, DWORD_PTR
WinHttpWebSocketCompleteUpgrade.restype = HINTERNET
WinHttpWebSocketSend = Winhttp.WinHttpWebSocketSend
WinHttpWebSocketSend.argtypes = HINTERNET, DWORD, LPVOID, DWORD
WinHttpWebSocketSend.restype = DWORD
WinHttpWebSocketReceive = Winhttp.WinHttpWebSocketReceive
WinHttpWebSocketReceive.argtypes = HINTERNET, LPVOID, DWORD, DWORD_PTR, DWORD_PTR
WinHttpWebSocketReceive.restype = DWORD
WinHttpWebSocketClose = Winhttp.WinHttpWebSocketClose
WinHttpWebSocketClose.argtypes = HINTERNET, USHORT, LPVOID, DWORD_PTR
WinHttpWebSocketClose.restype = DWORD
except:
def _undefined(*args):
raise Exception("undefined websocket functions for windows 7-")
WinHttpWebSocketCompleteUpgrade = WinHttpWebSocketSend = WinHttpWebSocketReceive = (
WinHttpWebSocketClose
) = _undefined
WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET = 114
WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE = 0
WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE = 1
WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE = 2
WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE = 3
WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE = 4
ERROR_SUCCESS = 0
WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS = 1000
WINHTTP_OPTION_REDIRECT_POLICY = 88
WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS = 2
WINHTTP_OPTION_REDIRECT_POLICY_NEVER = 0
class WinhttpException(RequestException): class WinhttpException(RequestException):
@ -64,116 +206,33 @@ class WinhttpException(RequestException):
ERROR_WINHTTP_FEATURE_DISABLED = WINHTTP_ERROR_BASE + 192 ERROR_WINHTTP_FEATURE_DISABLED = WINHTTP_ERROR_BASE + 192
def __init__(self, code) -> None: def __init__(self, code) -> None:
self.errorcode = code module = None
if type(code) == int: if (
error = "UNKNOWN ERROR " + str(code) WinhttpException.WINHTTP_ERROR_BASE <= code
for _ in dir(self): and code <= WinhttpException.ERROR_WINHTTP_FEATURE_DISABLED
if _.startswith("ERROR") and code == getattr(self, _): ):
error = _ + " " + str(code) module = Winhttp._handle
break message = windows.FormatMessage(code, module)
else: error = f"UNKNOWN ERROR {code}"
error = code for _ in dir(self):
if _.startswith("ERROR") and code == getattr(self, _):
error = _
break
if message:
error += f": {message}"
super().__init__(error) super().__init__(error)
# typedef def MaybeRaiseException(error=None):
HINTERNET = LPVOID if error is None:
INTERNET_PORT = WORD error = windows.GetLastError()
DWORD_PTR = POINTER(DWORD) if error == ERROR_SUCCESS:
LPDWORD = POINTER(DWORD) return
# const exception = WinhttpException(error)
NULL = None if error == WinhttpException.ERROR_WINHTTP_TIMEOUT:
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0 raise Timeout(exception)
WINHTTP_NO_PROXY_NAME = None raise exception
WINHTTP_NO_PROXY_BYPASS = None
INTERNET_DEFAULT_PORT = 0
INTERNET_DEFAULT_HTTP_PORT = 80
INTERNET_DEFAULT_HTTPS_PORT = 443
WINHTTP_NO_REFERER = None
WINHTTP_DEFAULT_ACCEPT_TYPES = None
# WINHTTP_FLAG_REFRESH
WINHTTP_FLAG_SECURE = 0x00800000 # https
WINHTTP_NO_ADDITIONAL_HEADERS = None
WINHTTP_NO_REQUEST_DATA = None
WINHTTP_QUERY_SET_COOKIE = 43
WINHTTP_QUERY_RAW_HEADERS_CRLF = 22
WINHTTP_HEADER_NAME_BY_INDEX = None
WINHTTP_NO_HEADER_INDEX = None
ERROR_INSUFFICIENT_BUFFER = 122
WINHTTP_OPTION_PROXY = 38
WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3
WINHTTP_QUERY_STATUS_CODE = 19
WINHTTP_QUERY_FLAG_NUMBER = 0x20000000
WINHTTP_OPTION_SECURITY_FLAGS = 31
SECURITY_FLAG_IGNORE_UNKNOWN_CA = 0x00000100
SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE = 0x00000200
SECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000 # bad common name in X509 Cert.
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = 0x00002000 # expired X509 Cert.
SECURITY_FLAG_IGNORE_ALL_CERT_ERRORS = (
SECURITY_FLAG_IGNORE_UNKNOWN_CA
| SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE
| SECURITY_FLAG_IGNORE_CERT_CN_INVALID
| SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
)
# function
kernel32 = windll.kernel32
GetLastError = kernel32.GetLastError
GetLastError.restype = DWORD
Winhttp = windll.Winhttp
WinHttpOpen = Winhttp.WinHttpOpen
WinHttpOpen.argtypes = LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD
WinHttpOpen.restype = HINTERNET
WinHttpCloseHandle = Winhttp.WinHttpCloseHandle
WinHttpCloseHandle.argtypes = (HINTERNET,)
WinHttpSetTimeouts = Winhttp.WinHttpSetTimeouts
WinHttpSetTimeouts.argtypes = HINTERNET, DWORD, DWORD, DWORD, DWORD
WinHttpSetTimeouts.restype = BOOL
WinHttpConnect = Winhttp.WinHttpConnect
WinHttpConnect.argtypes = HINTERNET, LPCWSTR, INTERNET_PORT, DWORD
WinHttpConnect.restype = HINTERNET
WinHttpOpenRequest = Winhttp.WinHttpOpenRequest
WinHttpOpenRequest.argtypes = (
HINTERNET,
LPCWSTR,
LPCWSTR,
LPCWSTR,
LPCWSTR,
POINTER(LPCWSTR),
DWORD,
)
WinHttpOpenRequest.restype = HINTERNET
WinHttpSendRequest = Winhttp.WinHttpSendRequest
WinHttpSendRequest.argtypes = HINTERNET, LPCWSTR, DWORD, LPVOID, DWORD, DWORD, DWORD_PTR
WinHttpSendRequest.restype = BOOL
WinHttpReceiveResponse = Winhttp.WinHttpReceiveResponse
WinHttpReceiveResponse.argtypes = HINTERNET, LPVOID
WinHttpReceiveResponse.restype = BOOL
WinHttpQueryDataAvailable = Winhttp.WinHttpQueryDataAvailable
WinHttpQueryDataAvailable.argtypes = HINTERNET, LPDWORD
WinHttpQueryDataAvailable.restype = BOOL
WinHttpReadData = Winhttp.WinHttpReadData
WinHttpReadData.argtypes = HINTERNET, LPVOID, DWORD, LPDWORD
WinHttpReadData.restype = BOOL
WinHttpWriteData = Winhttp.WinHttpWriteData
WinHttpWriteData.argtypes = HINTERNET, LPCVOID, DWORD, LPDWORD
WinHttpWriteData.restype = BOOL
WinHttpQueryHeaders = Winhttp.WinHttpQueryHeaders
WinHttpQueryHeaders.argtypes = HINTERNET, DWORD, LPCWSTR, LPVOID, LPDWORD, LPDWORD
WinHttpQueryHeaders.restype = BOOL
WinHttpSetOption = Winhttp.WinHttpSetOption
WinHttpSetOption.argtypes = HINTERNET, DWORD, LPVOID, DWORD
WinHttpSetOption.restype = BOOL
class WINHTTP_PROXY_INFO(Structure):
_fields_ = [
("dwAccessType", DWORD),
("lpszProxy", LPWSTR),
("lpszProxyBypass", LPWSTR),
]
def winhttpsetproxy(hreq, proxy): def winhttpsetproxy(hreq, proxy):
@ -185,49 +244,4 @@ def winhttpsetproxy(hreq, proxy):
hreq, WINHTTP_OPTION_PROXY, pointer(proxyInfo), sizeof(proxyInfo) hreq, WINHTTP_OPTION_PROXY, pointer(proxyInfo), sizeof(proxyInfo)
) )
if succ == 0: if succ == 0:
raise WinhttpException(GetLastError()) MaybeRaiseException()
# raise WinhttpException('invalid proxy: {}'.format(proxy))
class AutoWinHttpHandle(HINTERNET):
def __del__(self):
if self:
WinHttpCloseHandle(self)
try:
WinHttpWebSocketCompleteUpgrade = Winhttp.WinHttpWebSocketCompleteUpgrade
WinHttpWebSocketCompleteUpgrade.argtypes = HINTERNET, DWORD_PTR
WinHttpWebSocketCompleteUpgrade.restype = HINTERNET
WinHttpWebSocketSend = Winhttp.WinHttpWebSocketSend
WinHttpWebSocketSend.argtypes = HINTERNET, DWORD, LPVOID, DWORD
WinHttpWebSocketSend.restype = DWORD
WinHttpWebSocketReceive = Winhttp.WinHttpWebSocketReceive
WinHttpWebSocketReceive.argtypes = HINTERNET, LPVOID, DWORD, DWORD_PTR, DWORD_PTR
WinHttpWebSocketReceive.restype = DWORD
WinHttpWebSocketClose = Winhttp.WinHttpWebSocketClose
WinHttpWebSocketClose.argtypes = HINTERNET, USHORT, LPVOID, DWORD_PTR
WinHttpWebSocketClose.restype = DWORD
except:
def _undefined(*args):
raise Exception("undefined websocket functions for windows 7-")
WinHttpWebSocketCompleteUpgrade = WinHttpWebSocketSend = WinHttpWebSocketReceive = (
WinHttpWebSocketClose
) = _undefined
WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET = 114
WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE = 0
WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE = 1
WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE = 2
WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE = 3
WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE = 4
ERROR_SUCCESS = 0
WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS = 1000
WINHTTP_OPTION_REDIRECT_POLICY = 88
WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS = 2
WINHTTP_OPTION_REDIRECT_POLICY_NEVER = 0

View File

@ -124,7 +124,7 @@ class basetransdev(basetrans):
return res["result"] return res["result"]
except: except:
print(res) print(res)
raise Exception() raise Exception(res)
def _createtarget(self): def _createtarget(self):
if self.using == False: if self.using == False:

View File

@ -33,6 +33,8 @@ from ctypes.wintypes import (
HKEY, HKEY,
LPDWORD, LPDWORD,
LPBYTE, LPBYTE,
LPCVOID,
LPWSTR,
WPARAM, WPARAM,
LPARAM, LPARAM,
INT, INT,
@ -619,11 +621,8 @@ def CreateMutex(bInitialOwner, lpName, secu=get_SECURITY_ATTRIBUTES()):
return _CreateMutexW(pointer(secu), bInitialOwner, lpName) return _CreateMutexW(pointer(secu), bInitialOwner, lpName)
_GetLastError = _kernel32.GetLastError GetLastError = _kernel32.GetLastError
GetLastError.restype = DWORD
def GetLastError():
return _GetLastError()
ERROR_ALREADY_EXISTS = 183 ERROR_ALREADY_EXISTS = 183
@ -958,3 +957,34 @@ GetWindowLongPtr.restype = c_void_p
WM_LBUTTONDOWN = 0x0201 WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202 WM_LBUTTONUP = 0x0202
WM_MOUSEMOVE = 0x0200 WM_MOUSEMOVE = 0x0200
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100
FORMAT_MESSAGE_FROM_HMODULE = 0x800
FORMAT_MESSAGE_FROM_SYSTEM = 0x1000
FORMAT_MESSAGE_IGNORE_INSERTS = 0x200
FormatMessageW = _kernel32.FormatMessageW
FormatMessageW.argtypes = DWORD, LPCVOID, DWORD, DWORD, LPWSTR, DWORD, LPCVOID
FormatMessageW.restype = c_size_t
LocalFree = _kernel32.LocalFree
LocalFree.argtypes = (c_void_p,)
def FormatMessage(code, module=None):
mess = LPWSTR()
flag = (
FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
)
if module:
flag |= FORMAT_MESSAGE_FROM_HMODULE
length = FormatMessageW(
flag, module, code, 0x400, cast(pointer(mess), LPWSTR), 0, None
)
if mess.value is None:
return ""
res = mess.value[:length]
if length:
LocalFree(mess)
return res.strip()

View File

@ -29,7 +29,7 @@ include(generate_product_version)
set(VERSION_MAJOR 5) set(VERSION_MAJOR 5)
set(VERSION_MINOR 23) set(VERSION_MINOR 23)
set(VERSION_PATCH 6) set(VERSION_PATCH 7)
add_library(pch pch.cpp) add_library(pch pch.cpp)
target_precompile_headers(pch PUBLIC pch.h) target_precompile_headers(pch PUBLIC pch.h)