def _handshake(s, resolved_address, der_encoded_server_certificate, **config):
local_port = s.getsockname()[<NUM_LIT:1>]<EOL>supported_versions = [<NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:0>]<EOL>handshake = [MAGIC_PREAMBLE] + supported_versions<EOL>log_debug("<STR_LIT>", local_port, MAGIC_PREAMBLE)<EOL>log_debug("<STR_LIT>", local_port, *supported_versions)<EOL>data = b"<STR_LIT>".join(struct_pack("<STR_LIT>", num) for num in handshake)<EOL>s.sendall(data)<EOL>ready_to_read = False<EOL>while not ready_to_read:<EOL><INDENT>ready_to_read, _, _ = select((s,), (), (), <NUM_LIT:1>)<EOL><DEDENT>try:<EOL><INDENT>data = s.recv(<NUM_LIT:4>)<EOL><DEDENT>except (IOError, OSError):  <EOL><INDENT>raise ServiceUnavailable("<STR_LIT>".format(resolved_address))<EOL><DEDENT>data_size = len(data)<EOL>if data_size == <NUM_LIT:0>:<EOL><INDENT>log_debug("<STR_LIT>", local_port)<EOL>s.close()<EOL>raise ServiceUnavailable("<STR_LIT>" % (resolved_address,))<EOL><DEDENT>if data_size != <NUM_LIT:4>:<EOL><INDENT>log_debug("<STR_LIT>", local_port)<EOL>s.close()<EOL>raise ProtocolError("<STR_LIT>"<EOL>"<STR_LIT>" % (resolved_address, data))<EOL><DEDENT>agreed_version, = struct_unpack("<STR_LIT>", data)<EOL>log_debug("<STR_LIT>", local_port, agreed_version)<EOL>if agreed_version == <NUM_LIT:0>:<EOL><INDENT>log_debug("<STR_LIT>", local_port)<EOL>s.shutdown(SHUT_RDWR)<EOL>s.close()<EOL><DEDENT>elif agreed_version in (<NUM_LIT:1>, <NUM_LIT:2>):<EOL><INDENT>connection = Connection(agreed_version, resolved_address, s,<EOL>der_encoded_server_certificate=der_encoded_server_certificate,<EOL>**config)<EOL>connection.init()<EOL>return connection<EOL><DEDENT>elif agreed_version in (<NUM_LIT:3>,):<EOL><INDENT>connection = Connection(agreed_version, resolved_address, s,<EOL>der_encoded_server_certificate=der_encoded_server_certificate,<EOL>**config)<EOL>connection.hello()<EOL>return connection<EOL><DEDENT>elif agreed_version == <NUM_LIT>:<EOL><INDENT>log_debug("<STR_LIT>", local_port)<EOL>s.close()<EOL>raise ServiceUnavailable("<STR_LIT>"<EOL>"<STR_LIT>".format(resolved_address))<EOL><DEDENT>else:<EOL><INDENT>log_debug("<STR_LIT>", local_port)<EOL>s.close()<EOL>raise ProtocolError("<STR_LIT>".format(agreed_version))<EOL><DEDENT>
:param s:
:return: