You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

213 lines
11 KiB

  1. """
  2. """
  3. # Created on 2013.07.15
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2013 - 2018 Giovanni Cannata
  8. #
  9. # This file is part of ldap3.
  10. #
  11. # ldap3 is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU Lesser General Public License as published
  13. # by the Free Software Foundation, either version 3 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # ldap3 is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU Lesser General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU Lesser General Public License
  22. # along with ldap3 in the COPYING and COPYING.LESSER files.
  23. # If not, see <http://www.gnu.org/licenses/>.
  24. import socket
  25. from .. import SEQUENCE_TYPES, get_config_parameter
  26. from ..core.exceptions import LDAPSocketReceiveError, communication_exception_factory, LDAPExceptionError, LDAPExtensionError, LDAPOperationResult
  27. from ..strategy.base import BaseStrategy, SESSION_TERMINATED_BY_SERVER, RESPONSE_COMPLETE, TRANSACTION_ERROR
  28. from ..protocol.rfc4511 import LDAPMessage
  29. from ..utils.log import log, log_enabled, ERROR, NETWORK, EXTENDED, format_ldap_message
  30. from ..utils.asn1 import decoder, decode_message_fast
  31. LDAP_MESSAGE_TEMPLATE = LDAPMessage()
  32. # noinspection PyProtectedMember
  33. class SyncStrategy(BaseStrategy):
  34. """
  35. This strategy is synchronous. You send the request and get the response
  36. Requests return a boolean value to indicate the result of the requested Operation
  37. Connection.response will contain the whole LDAP response for the messageId requested in a dict form
  38. Connection.request will contain the result LDAP message in a dict form
  39. """
  40. def __init__(self, ldap_connection):
  41. BaseStrategy.__init__(self, ldap_connection)
  42. self.sync = True
  43. self.no_real_dsa = False
  44. self.pooled = False
  45. self.can_stream = False
  46. self.socket_size = get_config_parameter('SOCKET_SIZE')
  47. def open(self, reset_usage=True, read_server_info=True):
  48. BaseStrategy.open(self, reset_usage, read_server_info)
  49. if read_server_info:
  50. try:
  51. self.connection.refresh_server_info()
  52. except LDAPOperationResult: # catch errors from server if raise_exception = True
  53. self.connection.server._dsa_info = None
  54. self.connection.server._schema_info = None
  55. def _start_listen(self):
  56. if not self.connection.listening and not self.connection.closed:
  57. self.connection.listening = True
  58. def receiving(self):
  59. """
  60. Receives data over the socket
  61. Checks if the socket is closed
  62. """
  63. messages = []
  64. receiving = True
  65. unprocessed = b''
  66. data = b''
  67. get_more_data = True
  68. exc = None
  69. while receiving:
  70. if get_more_data:
  71. try:
  72. data = self.connection.socket.recv(self.socket_size)
  73. except (OSError, socket.error, AttributeError) as e:
  74. self.connection.last_error = 'error receiving data: ' + str(e)
  75. try: # try to close the connection before raising exception
  76. self.close()
  77. except (socket.error, LDAPExceptionError):
  78. pass
  79. if log_enabled(ERROR):
  80. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  81. # raise communication_exception_factory(LDAPSocketReceiveError, exc)(self.connection.last_error)
  82. raise communication_exception_factory(LDAPSocketReceiveError, type(e)(str(e)))(self.connection.last_error)
  83. unprocessed += data
  84. if len(data) > 0:
  85. length = BaseStrategy.compute_ldap_message_size(unprocessed)
  86. if length == -1: # too few data to decode message length
  87. get_more_data = True
  88. continue
  89. if len(unprocessed) < length:
  90. get_more_data = True
  91. else:
  92. if log_enabled(NETWORK):
  93. log(NETWORK, 'received %d bytes via <%s>', len(unprocessed[:length]), self.connection)
  94. messages.append(unprocessed[:length])
  95. unprocessed = unprocessed[length:]
  96. get_more_data = False
  97. if len(unprocessed) == 0:
  98. receiving = False
  99. else:
  100. receiving = False
  101. if log_enabled(NETWORK):
  102. log(NETWORK, 'received %d ldap messages via <%s>', len(messages), self.connection)
  103. return messages
  104. def post_send_single_response(self, message_id):
  105. """
  106. Executed after an Operation Request (except Search)
  107. Returns the result message or None
  108. """
  109. responses, result = self.get_response(message_id)
  110. self.connection.result = result
  111. if result['type'] == 'intermediateResponse': # checks that all responses are intermediates (there should be only one)
  112. for response in responses:
  113. if response['type'] != 'intermediateResponse':
  114. self.connection.last_error = 'multiple messages received error'
  115. if log_enabled(ERROR):
  116. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  117. raise LDAPSocketReceiveError(self.connection.last_error)
  118. responses.append(result)
  119. return responses
  120. def post_send_search(self, message_id):
  121. """
  122. Executed after a search request
  123. Returns the result message and store in connection.response the objects found
  124. """
  125. responses, result = self.get_response(message_id)
  126. self.connection.result = result
  127. if isinstance(responses, SEQUENCE_TYPES):
  128. self.connection.response = responses[:] # copy search result entries
  129. return responses
  130. self.connection.last_error = 'error receiving response'
  131. if log_enabled(ERROR):
  132. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  133. raise LDAPSocketReceiveError(self.connection.last_error)
  134. def _get_response(self, message_id):
  135. """
  136. Performs the capture of LDAP response for SyncStrategy
  137. """
  138. ldap_responses = []
  139. response_complete = False
  140. while not response_complete:
  141. responses = self.receiving()
  142. if responses:
  143. for response in responses:
  144. if len(response) > 0:
  145. if self.connection.usage:
  146. self.connection._usage.update_received_message(len(response))
  147. if self.connection.fast_decoder:
  148. ldap_resp = decode_message_fast(response)
  149. dict_response = self.decode_response_fast(ldap_resp)
  150. else:
  151. ldap_resp, _ = decoder.decode(response, asn1Spec=LDAP_MESSAGE_TEMPLATE) # unprocessed unused because receiving() waits for the whole message
  152. dict_response = self.decode_response(ldap_resp)
  153. if log_enabled(EXTENDED):
  154. log(EXTENDED, 'ldap message received via <%s>:%s', self.connection, format_ldap_message(ldap_resp, '<<'))
  155. if int(ldap_resp['messageID']) == message_id:
  156. ldap_responses.append(dict_response)
  157. if dict_response['type'] not in ['searchResEntry', 'searchResRef', 'intermediateResponse']:
  158. response_complete = True
  159. elif int(ldap_resp['messageID']) == 0: # 0 is reserved for 'Unsolicited Notification' from server as per RFC4511 (paragraph 4.4)
  160. if dict_response['responseName'] == '1.3.6.1.4.1.1466.20036': # Notice of Disconnection as per RFC4511 (paragraph 4.4.1)
  161. return SESSION_TERMINATED_BY_SERVER
  162. elif dict_response['responseName'] == '2.16.840.1.113719.1.27.103.4': # Novell LDAP transaction error unsolicited notification
  163. return TRANSACTION_ERROR
  164. else:
  165. self.connection.last_error = 'unknown unsolicited notification from server'
  166. if log_enabled(ERROR):
  167. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  168. raise LDAPSocketReceiveError(self.connection.last_error)
  169. elif int(ldap_resp['messageID']) != message_id and dict_response['type'] == 'extendedResp':
  170. self.connection.last_error = 'multiple extended responses to a single extended request'
  171. if log_enabled(ERROR):
  172. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  173. raise LDAPExtensionError(self.connection.last_error)
  174. # pass # ignore message with invalid messageId when receiving multiple extendedResp. This is not allowed by RFC4511 but some LDAP server do it
  175. else:
  176. self.connection.last_error = 'invalid messageId received'
  177. if log_enabled(ERROR):
  178. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  179. raise LDAPSocketReceiveError(self.connection.last_error)
  180. # response = unprocessed
  181. # if response: # if this statement is removed unprocessed data will be processed as another message
  182. # self.connection.last_error = 'unprocessed substrate error'
  183. # if log_enabled(ERROR):
  184. # log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  185. # raise LDAPSocketReceiveError(self.connection.last_error)
  186. else:
  187. return SESSION_TERMINATED_BY_SERVER
  188. ldap_responses.append(RESPONSE_COMPLETE)
  189. return ldap_responses
  190. def set_stream(self, value):
  191. raise NotImplementedError
  192. def get_stream(self):
  193. raise NotImplementedError