diff options
Diffstat (limited to 'ldap3/strategy')
-rw-r--r-- | ldap3/strategy/base.py | 77 | ||||
-rw-r--r-- | ldap3/strategy/restartable.py | 515 | ||||
-rw-r--r-- | ldap3/strategy/safeSync.py | 32 | ||||
-rw-r--r-- | ldap3/strategy/sync.py | 2 |
4 files changed, 338 insertions, 288 deletions
diff --git a/ldap3/strategy/base.py b/ldap3/strategy/base.py index 568459e..1acc732 100644 --- a/ldap3/strategy/base.py +++ b/ldap3/strategy/base.py @@ -24,15 +24,20 @@ # If not, see <http://www.gnu.org/licenses/>. import socket +try: # try to discover if unix sockets are available for LDAP over IPC (ldapi:// scheme) + # noinspection PyUnresolvedReferences + from socket import AF_UNIX + unix_socket_available = True +except ImportError: + unix_socket_available = False from struct import pack from platform import system -from time import sleep from random import choice from .. import SYNC, ANONYMOUS, get_config_parameter, BASE, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, NO_ATTRIBUTES from ..core.results import DO_NOT_RAISE_EXCEPTIONS, RESULT_REFERRAL from ..core.exceptions import LDAPOperationResult, LDAPSASLBindInProgressError, LDAPSocketOpenError, LDAPSessionTerminatedByServerError,\ - LDAPUnknownResponseError, LDAPUnknownRequestError, LDAPReferralError, communication_exception_factory, \ + LDAPUnknownResponseError, LDAPUnknownRequestError, LDAPReferralError, communication_exception_factory, LDAPStartTLSError, \ LDAPSocketSendError, LDAPExceptionError, LDAPControlError, LDAPResponseTimeoutError, LDAPTransactionError from ..utils.uri import parse_uri from ..protocol.rfc4511 import LDAPMessage, ProtocolOp, MessageID, SearchResultEntry @@ -78,6 +83,7 @@ class BaseStrategy(object): self.pooled = None # Indicates a connection with a connection pool self.can_stream = None # indicates if a strategy keeps a stream of responses (i.e. LdifProducer can accumulate responses with a single header). Stream must be initialized and closed in _start_listen() and _stop_listen() self.referral_cache = {} + self.thread_safe = False # Indicates that connection can be used in a multithread application if log_enabled(BASIC): log(BASIC, 'instantiated <%s>: <%s>', self.__class__.__name__, self) @@ -141,9 +147,6 @@ class BaseStrategy(object): if log_enabled(ERROR): log(ERROR, 'unable to open socket for <%s>', self.connection) raise LDAPSocketOpenError('unable to open socket', exception_history) - if log_enabled(ERROR): - log(ERROR, 'unable to open socket for <%s>', self.connection) - raise LDAPSocketOpenError('unable to open socket', exception_history) elif not self.connection.server.current_address: if log_enabled(ERROR): log(ERROR, 'invalid server address for <%s>', self.connection) @@ -151,7 +154,6 @@ class BaseStrategy(object): self.connection._deferred_open = False self._start_listen() - # self.connection.do_auto_bind() if log_enabled(NETWORK): log(NETWORK, 'connection open for <%s>', self.connection) @@ -199,7 +201,6 @@ class BaseStrategy(object): log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection) # raise communication_exception_factory(LDAPSocketOpenError, exc)(self.connection.last_error) raise communication_exception_factory(LDAPSocketOpenError, type(e)(str(e)))(self.connection.last_error) - # Try to bind the socket locally before connecting to the remote address # We go through our connection's source ports and try to bind our socket to our connection's source address # with them. @@ -210,25 +211,26 @@ class BaseStrategy(object): # issue when no source address/port is specified if the system checking server availability is running # as a very unprivileged user. last_bind_exc = None - socket_bind_succeeded = False - for source_port in self.connection.source_port_list: - try: - self.connection.socket.bind((self.connection.source_address, source_port)) - socket_bind_succeeded = True - break - except Exception as bind_ex: - last_bind_exc = bind_ex - # we'll always end up logging at error level if we cannot bind any ports to the address locally. - # but if some work and some don't you probably don't want the ones that don't at ERROR level - if log_enabled(NETWORK): - log(NETWORK, 'Unable to bind to local address <%s> with source port <%s> due to <%s>', - self.connection.source_address, source_port, bind_ex) - if not socket_bind_succeeded: - self.connection.last_error = 'socket connection error while locally binding: ' + str(last_bind_exc) - if log_enabled(ERROR): - log(ERROR, 'Unable to locally bind to local address <%s> with any of the source ports <%s> for connection <%s due to <%s>', - self.connection.source_address, self.connection.source_port_list, self.connection, last_bind_exc) - raise communication_exception_factory(LDAPSocketOpenError, type(last_bind_exc)(str(last_bind_exc)))(last_bind_exc) + if unix_socket_available and self.connection.socket.family != socket.AF_UNIX: + socket_bind_succeeded = False + for source_port in self.connection.source_port_list: + try: + self.connection.socket.bind((self.connection.source_address, source_port)) + socket_bind_succeeded = True + break + except Exception as bind_ex: + last_bind_exc = bind_ex + # we'll always end up logging at error level if we cannot bind any ports to the address locally. + # but if some work and some don't you probably don't want the ones that don't at ERROR level + if log_enabled(NETWORK): + log(NETWORK, 'Unable to bind to local address <%s> with source port <%s> due to <%s>', + self.connection.source_address, source_port, bind_ex) + if not socket_bind_succeeded: + self.connection.last_error = 'socket connection error while locally binding: ' + str(last_bind_exc) + if log_enabled(ERROR): + log(ERROR, 'Unable to locally bind to local address <%s> with any of the source ports <%s> for connection <%s due to <%s>', + self.connection.source_address, self.connection.source_port_list, self.connection, last_bind_exc) + raise communication_exception_factory(LDAPSocketOpenError, type(last_bind_exc)(str(last_bind_exc)))(last_bind_exc) try: # set socket timeout for opening connection if self.connection.server.connect_timeout: @@ -273,7 +275,6 @@ class BaseStrategy(object): self.connection.last_error = 'socket ssl wrapping error: ' + str(e) if log_enabled(ERROR): log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection) - # raise communication_exception_factory(LDAPSocketOpenError, exc)(self.connection.last_error) raise communication_exception_factory(LDAPSocketOpenError, type(e)(str(e)))(self.connection.last_error) if self.connection.usage: self.connection._usage.open_sockets += 1 @@ -693,13 +694,20 @@ class BaseStrategy(object): search_scope=BASE, dereference_aliases=request['dereferenceAlias'], attributes=[attr_type + ';range=' + str(int(high_range) + 1) + '-*']) - if isinstance(result, bool): - if result: - current_response = self.connection.response[0] + if self.connection.strategy.thread_safe: + status, result, _response, _ = result + else: + status = result + result = self.connection.result + _response = self.connection.response + + if self.connection.strategy.sync: + if status: + current_response = _response[0] else: done = True else: - current_response, _ = self.get_response(result) + current_response, _ = self.get_response(status) current_response = current_response[0] if not done: @@ -778,7 +786,12 @@ class BaseStrategy(object): referral_connection.open() referral_connection.strategy._referrals = self._referrals if self.connection.tls_started and not referral_server.ssl: # if the original server was in start_tls mode and the referral server is not in ssl then start_tls on the referral connection - referral_connection.start_tls() + if not referral_connection.start_tls(): + error = 'start_tls in referral not successful' + (' - ' + referral_connection.last_error if referral_connection.last_error else '') + if log_enabled(ERROR): + log(ERROR, '%s for <%s>', error, self) + self.unbind() + raise LDAPStartTLSError(error) if self.connection.bound: referral_connection.bind() diff --git a/ldap3/strategy/restartable.py b/ldap3/strategy/restartable.py index d739f41..bd689f9 100644 --- a/ldap3/strategy/restartable.py +++ b/ldap3/strategy/restartable.py @@ -1,255 +1,260 @@ -"""
-"""
-
-# Created on 2014.03.04
-#
-# Author: Giovanni Cannata
-#
-# Copyright 2014 - 2020 Giovanni Cannata
-#
-# This file is part of ldap3.
-#
-# ldap3 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 3 of the License, or
-# (at your option) any later version.
-#
-# ldap3 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 ldap3 in the COPYING and COPYING.LESSER files.
-# If not, see <http://www.gnu.org/licenses/>.
-
-from time import sleep
-import socket
-
-from .. import get_config_parameter
-from .sync import SyncStrategy
-from ..core.exceptions import LDAPSocketOpenError, LDAPOperationResult, LDAPMaximumRetriesError
-from ..utils.log import log, log_enabled, ERROR, BASIC
-
-
-# noinspection PyBroadException,PyProtectedMember
-class RestartableStrategy(SyncStrategy):
- def __init__(self, ldap_connection):
- SyncStrategy.__init__(self, ldap_connection)
- self.sync = True
- self.no_real_dsa = False
- self.pooled = False
- self.can_stream = False
- self.restartable_sleep_time = get_config_parameter('RESTARTABLE_SLEEPTIME')
- self.restartable_tries = get_config_parameter('RESTARTABLE_TRIES')
- self._restarting = False
- self._last_bind_controls = None
- self._current_message_type = None
- self._current_request = None
- self._current_controls = None
- self._restart_tls = None
- self.exception_history = []
-
- def open(self, reset_usage=False, read_server_info=True):
- SyncStrategy.open(self, reset_usage, read_server_info)
-
- def _open_socket(self, address, use_ssl=False, unix_socket=False):
- """
- Try to open and connect a socket to a Server
- raise LDAPExceptionError if unable to open or connect socket
- if connection is restartable tries for the number of restarting requested or forever
- """
- try:
- SyncStrategy._open_socket(self, address, use_ssl, unix_socket) # try to open socket using SyncWait
- self._reset_exception_history()
- return
- except Exception as e: # machinery for restartable connection
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
-
- if not self._restarting: # if not already performing a restart
- self._restarting = True
- counter = self.restartable_tries
- while counter > 0: # includes restartable_tries == True
- if log_enabled(BASIC):
- log(BASIC, 'try #%d to open Restartable connection <%s>', self.restartable_tries - counter, self.connection)
- sleep(self.restartable_sleep_time)
- if not self.connection.closed:
- try: # resetting connection
- self.connection.unbind()
- except (socket.error, LDAPSocketOpenError): # don't trace catch socket errors because socket could already be closed
- pass
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
- try: # reissuing same operation
- if self.connection.server_pool:
- new_server = self.connection.server_pool.get_server(self.connection) # get a server from the server_pool if available
- if self.connection.server != new_server:
- self.connection.server = new_server
- if self.connection.usage:
- self.connection._usage.servers_from_pool += 1
- SyncStrategy._open_socket(self, address, use_ssl, unix_socket) # calls super (not restartable) _open_socket()
- if self.connection.usage:
- self.connection._usage.restartable_successes += 1
- self.connection.closed = False
- self._restarting = False
- self._reset_exception_history()
- return
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
- if self.connection.usage:
- self.connection._usage.restartable_failures += 1
- if not isinstance(self.restartable_tries, bool):
- counter -= 1
- self._restarting = False
- self.connection.last_error = 'restartable connection strategy failed while opening socket'
- if log_enabled(ERROR):
- log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
- raise LDAPMaximumRetriesError(self.connection.last_error, self.exception_history, self.restartable_tries)
-
- def send(self, message_type, request, controls=None):
- self._current_message_type = message_type
- self._current_request = request
- self._current_controls = controls
- if not self._restart_tls: # RFCs doesn't define how to stop tls once started
- self._restart_tls = self.connection.tls_started
- if message_type == 'bindRequest': # stores controls used in bind operation to be used again when restarting the connection
- self._last_bind_controls = controls
-
- try:
- message_id = SyncStrategy.send(self, message_type, request, controls) # tries to send using SyncWait
- self._reset_exception_history()
- return message_id
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
- if not self._restarting: # machinery for restartable connection
- self._restarting = True
- counter = self.restartable_tries
- while counter > 0:
- if log_enabled(BASIC):
- log(BASIC, 'try #%d to send in Restartable connection <%s>', self.restartable_tries - counter, self.connection)
- sleep(self.restartable_sleep_time)
- if not self.connection.closed:
- try: # resetting connection
- self.connection.unbind()
- except (socket.error, LDAPSocketOpenError): # don't trace socket errors because socket could already be closed
- pass
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
- failure = False
- try: # reopening connection
- self.connection.open(reset_usage=False, read_server_info=False)
- if self._restart_tls: # restart tls if start_tls was previously used
- self.connection.start_tls(read_server_info=False)
- if message_type != 'bindRequest':
- self.connection.bind(read_server_info=False, controls=self._last_bind_controls) # binds with previously used controls unless the request is already a bindRequest
- if not self.connection.server.schema and not self.connection.server.info:
- self.connection.refresh_server_info()
- else:
- self.connection._fire_deferred(read_info=False) # in case of lazy connection, not open by the refresh_server_info
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
- failure = True
-
- if not failure:
- try: # reissuing same operation
- ret_value = self.connection.send(message_type, request, controls)
- if self.connection.usage:
- self.connection._usage.restartable_successes += 1
- self._restarting = False
- self._reset_exception_history()
- return ret_value # successful send
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
- failure = True
-
- if failure and self.connection.usage:
- self.connection._usage.restartable_failures += 1
-
- if not isinstance(self.restartable_tries, bool):
- counter -= 1
-
- self._restarting = False
-
- self.connection.last_error = 'restartable connection failed to send'
- if log_enabled(ERROR):
- log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
- raise LDAPMaximumRetriesError(self.connection.last_error, self.exception_history, self.restartable_tries)
-
- def post_send_single_response(self, message_id):
- try:
- ret_value = SyncStrategy.post_send_single_response(self, message_id)
- self._reset_exception_history()
- return ret_value
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
-
- # if an LDAPExceptionError is raised then resend the request
- try:
- ret_value = SyncStrategy.post_send_single_response(self, self.send(self._current_message_type, self._current_request, self._current_controls))
- self._reset_exception_history()
- return ret_value
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
- if not isinstance(e, LDAPOperationResult):
- self.connection.last_error = 'restartable connection strategy failed in post_send_single_response'
- if log_enabled(ERROR):
- log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
- raise
-
- def post_send_search(self, message_id):
- try:
- ret_value = SyncStrategy.post_send_search(self, message_id)
- self._reset_exception_history()
- return ret_value
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
-
- # if an LDAPExceptionError is raised then resend the request
- try:
- ret_value = SyncStrategy.post_send_search(self, self.connection.send(self._current_message_type, self._current_request, self._current_controls))
- self._reset_exception_history()
- return ret_value
- except Exception as e:
- if log_enabled(ERROR):
- log(ERROR, '<%s> while restarting <%s>', e, self.connection)
- self._add_exception_to_history(type(e)(str(e)))
- if not isinstance(e, LDAPOperationResult):
- self.connection.last_error = e.args
- if log_enabled(ERROR):
- log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
- raise e
-
- def _add_exception_to_history(self, exc):
- if not isinstance(self.restartable_tries, bool): # doesn't accumulate when restarting forever
- if not isinstance(exc, LDAPMaximumRetriesError): # doesn't add the LDAPMaximumRetriesError exception
- self.exception_history.append(exc)
-
- def _reset_exception_history(self):
- if self.exception_history:
- self.exception_history = []
-
- def get_stream(self):
- raise NotImplementedError
-
- def set_stream(self, value):
- raise NotImplementedError
+""" +""" + +# Created on 2014.03.04 +# +# Author: Giovanni Cannata +# +# Copyright 2014 - 2020 Giovanni Cannata +# +# This file is part of ldap3. +# +# ldap3 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 3 of the License, or +# (at your option) any later version. +# +# ldap3 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 ldap3 in the COPYING and COPYING.LESSER files. +# If not, see <http://www.gnu.org/licenses/>. + +from time import sleep +import socket + +from .. import get_config_parameter +from .sync import SyncStrategy +from ..core.exceptions import LDAPSocketOpenError, LDAPOperationResult, LDAPMaximumRetriesError, LDAPStartTLSError +from ..utils.log import log, log_enabled, ERROR, BASIC + + +# noinspection PyBroadException,PyProtectedMember +class RestartableStrategy(SyncStrategy): + def __init__(self, ldap_connection): + SyncStrategy.__init__(self, ldap_connection) + self.sync = True + self.no_real_dsa = False + self.pooled = False + self.can_stream = False + self.restartable_sleep_time = get_config_parameter('RESTARTABLE_SLEEPTIME') + self.restartable_tries = get_config_parameter('RESTARTABLE_TRIES') + self._restarting = False + self._last_bind_controls = None + self._current_message_type = None + self._current_request = None + self._current_controls = None + self._restart_tls = None + self.exception_history = [] + + def open(self, reset_usage=False, read_server_info=True): + SyncStrategy.open(self, reset_usage, read_server_info) + + def _open_socket(self, address, use_ssl=False, unix_socket=False): + """ + Try to open and connect a socket to a Server + raise LDAPExceptionError if unable to open or connect socket + if connection is restartable tries for the number of restarting requested or forever + """ + try: + SyncStrategy._open_socket(self, address, use_ssl, unix_socket) # try to open socket using SyncWait + self._reset_exception_history() + return + except Exception as e: # machinery for restartable connection + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + + if not self._restarting: # if not already performing a restart + self._restarting = True + counter = self.restartable_tries + while counter > 0: # includes restartable_tries == True + if log_enabled(BASIC): + log(BASIC, 'try #%d to open Restartable connection <%s>', self.restartable_tries - counter, self.connection) + sleep(self.restartable_sleep_time) + if not self.connection.closed: + try: # resetting connection + self.connection.unbind() + except (socket.error, LDAPSocketOpenError): # don't trace catch socket errors because socket could already be closed + pass + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + try: # reissuing same operation + if self.connection.server_pool: + new_server = self.connection.server_pool.get_server(self.connection) # get a server from the server_pool if available + if self.connection.server != new_server: + self.connection.server = new_server + if self.connection.usage: + self.connection._usage.servers_from_pool += 1 + SyncStrategy._open_socket(self, address, use_ssl, unix_socket) # calls super (not restartable) _open_socket() + if self.connection.usage: + self.connection._usage.restartable_successes += 1 + self.connection.closed = False + self._restarting = False + self._reset_exception_history() + return + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + if self.connection.usage: + self.connection._usage.restartable_failures += 1 + if not isinstance(self.restartable_tries, bool): + counter -= 1 + self._restarting = False + self.connection.last_error = 'restartable connection strategy failed while opening socket' + if log_enabled(ERROR): + log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection) + raise LDAPMaximumRetriesError(self.connection.last_error, self.exception_history, self.restartable_tries) + + def send(self, message_type, request, controls=None): + self._current_message_type = message_type + self._current_request = request + self._current_controls = controls + if not self._restart_tls: # RFCs doesn't define how to stop tls once started + self._restart_tls = self.connection.tls_started + if message_type == 'bindRequest': # stores controls used in bind operation to be used again when restarting the connection + self._last_bind_controls = controls + + try: + message_id = SyncStrategy.send(self, message_type, request, controls) # tries to send using SyncWait + self._reset_exception_history() + return message_id + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + if not self._restarting: # machinery for restartable connection + self._restarting = True + counter = self.restartable_tries + while counter > 0: + if log_enabled(BASIC): + log(BASIC, 'try #%d to send in Restartable connection <%s>', self.restartable_tries - counter, self.connection) + sleep(self.restartable_sleep_time) + if not self.connection.closed: + try: # resetting connection + self.connection.unbind() + except (socket.error, LDAPSocketOpenError): # don't trace socket errors because socket could already be closed + pass + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + failure = False + try: # reopening connection + self.connection.open(reset_usage=False, read_server_info=False) + if self._restart_tls: # restart tls if start_tls was previously used + if self.connection.start_tls(read_server_info=False): + error = 'restart tls in restartable not successful' + (' - ' + self.connection.last_error if self.connection.last_error else '') + if log_enabled(ERROR): + log(ERROR, '%s for <%s>', error, self) + self.connection.unbind() + raise LDAPStartTLSError(error) + if message_type != 'bindRequest': + self.connection.bind(read_server_info=False, controls=self._last_bind_controls) # binds with previously used controls unless the request is already a bindRequest + if not self.connection.server.schema and not self.connection.server.info: + self.connection.refresh_server_info() + else: + self.connection._fire_deferred(read_info=False) # in case of lazy connection, not open by the refresh_server_info + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + failure = True + + if not failure: + try: # reissuing same operation + ret_value = self.connection.send(message_type, request, controls) + if self.connection.usage: + self.connection._usage.restartable_successes += 1 + self._restarting = False + self._reset_exception_history() + return ret_value # successful send + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + failure = True + + if failure and self.connection.usage: + self.connection._usage.restartable_failures += 1 + + if not isinstance(self.restartable_tries, bool): + counter -= 1 + + self._restarting = False + + self.connection.last_error = 'restartable connection failed to send' + if log_enabled(ERROR): + log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection) + raise LDAPMaximumRetriesError(self.connection.last_error, self.exception_history, self.restartable_tries) + + def post_send_single_response(self, message_id): + try: + ret_value = SyncStrategy.post_send_single_response(self, message_id) + self._reset_exception_history() + return ret_value + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + + # if an LDAPExceptionError is raised then resend the request + try: + ret_value = SyncStrategy.post_send_single_response(self, self.send(self._current_message_type, self._current_request, self._current_controls)) + self._reset_exception_history() + return ret_value + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + if not isinstance(e, LDAPOperationResult): + self.connection.last_error = 'restartable connection strategy failed in post_send_single_response' + if log_enabled(ERROR): + log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection) + raise + + def post_send_search(self, message_id): + try: + ret_value = SyncStrategy.post_send_search(self, message_id) + self._reset_exception_history() + return ret_value + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + + # if an LDAPExceptionError is raised then resend the request + try: + ret_value = SyncStrategy.post_send_search(self, self.connection.send(self._current_message_type, self._current_request, self._current_controls)) + self._reset_exception_history() + return ret_value + except Exception as e: + if log_enabled(ERROR): + log(ERROR, '<%s> while restarting <%s>', e, self.connection) + self._add_exception_to_history(type(e)(str(e))) + if not isinstance(e, LDAPOperationResult): + self.connection.last_error = e.args + if log_enabled(ERROR): + log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection) + raise e + + def _add_exception_to_history(self, exc): + if not isinstance(self.restartable_tries, bool): # doesn't accumulate when restarting forever + if not isinstance(exc, LDAPMaximumRetriesError): # doesn't add the LDAPMaximumRetriesError exception + self.exception_history.append(exc) + + def _reset_exception_history(self): + if self.exception_history: + self.exception_history = [] + + def get_stream(self): + raise NotImplementedError + + def set_stream(self, value): + raise NotImplementedError diff --git a/ldap3/strategy/safeSync.py b/ldap3/strategy/safeSync.py new file mode 100644 index 0000000..dcd2b92 --- /dev/null +++ b/ldap3/strategy/safeSync.py @@ -0,0 +1,32 @@ +"""
+"""
+
+# Created on 2020.07.12
+#
+# Author: Giovanni Cannata
+#
+# Copyright 2013 - 2020 Giovanni Cannata
+#
+# This file is part of ldap3.
+#
+# ldap3 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 3 of the License, or
+# (at your option) any later version.
+#
+# ldap3 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 ldap3 in the COPYING and COPYING.LESSER files.
+# If not, see <http://www.gnu.org/licenses/>.
+
+from .sync import SyncStrategy
+
+
+class SafeSyncStrategy(SyncStrategy):
+ def __init__(self, ldap_connection):
+ SyncStrategy.__init__(self, ldap_connection)
+ self.thread_safe = True
diff --git a/ldap3/strategy/sync.py b/ldap3/strategy/sync.py index fdb1441..19883a6 100644 --- a/ldap3/strategy/sync.py +++ b/ldap3/strategy/sync.py @@ -54,7 +54,7 @@ class SyncStrategy(BaseStrategy): def open(self, reset_usage=True, read_server_info=True): BaseStrategy.open(self, reset_usage, read_server_info) - if read_server_info: + if read_server_info and not self.connection._deferred_open: try: self.connection.refresh_server_info() except LDAPOperationResult: # catch errors from server if raise_exception = True |