synapse-product/synapse/crypto/keyclient.py

137 lines
4.4 KiB
Python
Raw Normal View History

2014-08-12 10:10:52 -04:00
# -*- coding: utf-8 -*-
2016-01-06 23:26:29 -05:00
# Copyright 2014-2016 OpenMarket Ltd
2014-08-12 10:10:52 -04:00
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
2014-08-12 10:10:52 -04:00
from twisted.web.http import HTTPClient
from twisted.internet.protocol import Factory
2014-08-12 10:10:52 -04:00
from twisted.internet import defer, reactor
from synapse.http.endpoint import matrix_federation_endpoint
from synapse.util.logcontext import (
preserve_context_over_fn, preserve_context_over_deferred
)
2015-02-11 09:23:10 -05:00
import simplejson as json
2014-08-12 10:10:52 -04:00
import logging
logger = logging.getLogger(__name__)
KEY_API_V1 = b"/_matrix/key/v1/"
2015-04-22 09:21:08 -04:00
2014-08-12 10:10:52 -04:00
@defer.inlineCallbacks
def fetch_server_key(server_name, ssl_context_factory, path=KEY_API_V1):
2014-08-12 10:10:52 -04:00
"""Fetch the keys for a remote server."""
factory = SynapseKeyClientFactory()
factory.path = path
2016-03-11 05:29:05 -05:00
factory.host = server_name
endpoint = matrix_federation_endpoint(
reactor, server_name, ssl_context_factory, timeout=30
)
2014-08-12 10:10:52 -04:00
for i in range(5):
try:
protocol = yield preserve_context_over_fn(
endpoint.connect, factory
)
server_response, server_certificate = yield preserve_context_over_deferred(
protocol.remote_key
)
defer.returnValue((server_response, server_certificate))
return
except SynapseKeyClientError as e:
logger.exception("Error getting key for %r" % (server_name,))
if e.status.startswith("4"):
# Don't retry for 4xx responses.
raise IOError("Cannot get key for %r" % server_name)
except Exception as e:
logger.exception(e)
raise IOError("Cannot get key for %r" % server_name)
2014-08-12 10:10:52 -04:00
class SynapseKeyClientError(Exception):
"""The key wasn't retrieved from the remote server."""
status = None
2014-08-12 10:10:52 -04:00
pass
class SynapseKeyClientProtocol(HTTPClient):
"""Low level HTTPS client which retrieves an application/json response from
the server and extracts the X.509 certificate for the remote peer from the
SSL connection."""
timeout = 30
def __init__(self):
self.remote_key = defer.Deferred()
self.host = None
2014-08-12 10:10:52 -04:00
def connectionMade(self):
self.host = self.transport.getHost()
logger.debug("Connected to %s", self.host)
self.sendCommand(b"GET", self.path)
2016-03-11 05:29:05 -05:00
if self.host:
self.sendHeader(b"Host", self.host)
2014-08-12 10:10:52 -04:00
self.endHeaders()
self.timer = reactor.callLater(
self.timeout,
2014-08-12 10:10:52 -04:00
self.on_timeout
)
def errback(self, error):
if not self.remote_key.called:
self.remote_key.errback(error)
def callback(self, result):
if not self.remote_key.called:
self.remote_key.callback(result)
2014-08-12 10:10:52 -04:00
def handleStatus(self, version, status, message):
if status != b"200":
2015-02-10 12:58:36 -05:00
# logger.info("Non-200 response from %s: %s %s",
# self.transport.getHost(), status, message)
2015-04-22 09:21:08 -04:00
error = SynapseKeyClientError(
"Non-200 response %r from %r" % (status, self.host)
)
error.status = status
self.errback(error)
2014-08-12 10:10:52 -04:00
self.transport.abortConnection()
def handleResponse(self, response_body_bytes):
try:
json_response = json.loads(response_body_bytes)
except ValueError:
2015-02-10 12:58:36 -05:00
# logger.info("Invalid JSON response from %s",
# self.transport.getHost())
2014-08-12 10:10:52 -04:00
self.transport.abortConnection()
return
certificate = self.transport.getPeerCertificate()
self.callback((json_response, certificate))
2014-08-12 10:10:52 -04:00
self.transport.abortConnection()
self.timer.cancel()
def on_timeout(self):
logger.debug("Timeout waiting for response from %s", self.host)
self.errback(IOError("Timeout waiting for response"))
2014-08-12 10:10:52 -04:00
self.transport.abortConnection()
class SynapseKeyClientFactory(Factory):
def protocol(self):
protocol = SynapseKeyClientProtocol()
protocol.path = self.path
return protocol