Beispiel #1
0
 def render(self, request):
     if self.port == 80:
         host = self.host
     else:
         host = "%s:%d" % (self.host, self.port)
     request.received_headers['host'] = host
     request.content.seek(0, 0)
     qs = urlparse.urlparse(request.uri)[4]
     if qs:
         rest = self.path + '?' + qs + '&format=json'
     else:
         rest = self.path + '?format=json'
     request_headers = request.getAllHeaders()
     request_headers['X-Auth-Token'] = self.session.get_key()
     clientFactory = self.proxyClientFactoryClass(
         self.session,
         request.method,
         rest,
         request.clientproto,
         request_headers,
         request.content.read(),
         request
     )
     if self.port == 443:
         context = SSLContextFactory()
         if hasattr(context, 'set_expected_host'):
             context.set_expected_host(self.host)
             context.raise_exception()
         self.reactor.connectSSL(self.host, self.port, clientFactory, context)
     else:
         self.reactor.connectTCP(self.host, self.port, clientFactory)
     return NOT_DONE_YET
Beispiel #2
0
 def _request(self):
     method = self.request.method.upper()
     scheme = self.request.url.scheme.lower()
     if scheme == 'https':
         context = SSLContextFactory()
         if hasattr(context, 'set_expected_host'):
             context.set_expected_host(self.request.url.netloc)
         agent = Agent(reactor, context)
     elif scheme == 'http':
         agent = Agent(reactor)
     else:
         raise TransportError('only HTTP and HTTPS schemes are supported')
     producer = StringProducer(self.request.body) if self.request.body else None
     self.request.start_timer()
     return agent.request(
         method,
         urlunsplit(self.request.url),
         Headers(self.request.headers),
         producer
     )
Beispiel #3
0
 def do_http_request(self, method='', url='', post_data={}, headers={}):
     '''
     
         Performs an HTTP or HTTPS request and returns a deferred that fires
         the callback when the request is complete.
     
     '''
     
     method = method.upper()
     if method not in self.METHODS:
         raise TransportException('invalid HTTP method specified: {0}'.format(method))
     
     url_parts = urlsplit(url)
     scheme = url_parts.scheme.lower()
     if scheme == 'https':
         context = SSLContextFactory()
         if hasattr(context, 'set_expected_host'):
             context.set_expected_host(url)
         agent = Agent(reactor, context)
     elif scheme == 'http':
         agent = Agent(reactor)
     else:
         raise TransportException('only HTTP and HTTPS schemes are supported')
     
     if type(post_data) != dict:
         raise TransportException('post_data must be a dictionary')
     if method == self.METHOD_POST and not post_data:
         raise TransportException('post_data must contain data when the method is POST')
     
     producer = HttpStreamProducer(urlencode(OrderedDict(post_data))) if post_data else None
     headers['User-Agent'] = ['txmailgunrelay' + ' v' + appver]
     if method == self.METHOD_POST:
         headers['Content-Type'] = ['application/x-www-form-urlencoded']
     
     #print 'method:', method
     #print 'url:', url
     #print 'headers:', headers
     #print 'data:', post_data
     
     return agent.request(method, url, Headers(headers), producer)
Beispiel #4
0
 def _do_request(self):
     '''
         Constructs a request using the child operation parameters and
         returns an HTTPClientFactory instance.
     '''
     
     def _got_response(response):
         '''
             Got a response, if we're expecting a body then wait for the
             protocol to return, otherwise fire the callback immediately.
         '''
         #print getattr(response, 'printTraceback', str)()
         if self._get_expected_body():
             d = Deferred()
             d.addCallback(_got_data, response).addErrback(_got_data, response)
             stream = self._object.get_stream() if self._object else None
             response.deliverBody(DownstreamTransportProtocol(d, stream))
             return d
         else:
             _got_data('', response)
             
     def _got_data(data, response):
         '''
             Check the response for failure. Note twisted raises a 'Failure'
             for things like HTTP 204's with no content, despite this being
             normal behaviour for the API.
         '''
         binary_data, json_data = self._parse_response_data(data)
         headers, metadata = self._parse_headers(list(response.headers.getAllRawHeaders()))
         actual_code, status_code = self._verify_response(response.code, headers, binary_data, json_data)
         response_class = Response if status_code > 0 else ResponseError
         self._request_parser(response_class(
             request=self,
             transfer_id=headers.get('X-Trans-Id', ''),
             status_code=actual_code,
             headers=headers,
             metadata=metadata,
             binary_body=binary_data,
             json_body=json_data,
             body_type=self._get_expected_body()
         ))
     
     request_type = self._get_request_type()
     if request_type == Request.REQUEST_STORAGE or request_type == Request.REQUEST_CDN:
         self.set_header(('X-Auth-Token', self._session.get_key()))
     request_headers = self._get_request_headers()
     request_headers['User-Agent'] = [USER_AGENT]
     url = self._get_request_url()
     producer = None
     if self._get_required_body() and self._object:
         producer = self._object.get_stream() if self._object.is_stream() else BlockProducer(self._body)
     context = SSLContextFactory()
     if hasattr(context, 'set_expected_host'):
         context.set_expected_host(url)
     agent = Agent(reactor, context)
     d = agent.request(
         self._get_request_method(),
         url,
         Headers(request_headers),
         producer
     )
     d.addCallback(_got_response)
     d.addErrback(_got_response)
    
    def dataReceived(self, data):
        self.b += data
    
    def connectionLost(self, reason):
        self.d.callback(self.b)

def der_to_pem(cert):
    r = ''
    for c in cert.split('\\'):
        if c:
            r += chr(int(c, 8))
    return ''.join(r).encode('base64').strip()

if __name__ == '__main__':
    context = VerifyingSSLContext()
    context.set_expected_host(CERT_SOURCE)
    agent = Agent(reactor, context)
    a = agent.request('GET', CERT_SOURCE)
    
    def got_error(e):
        print e
        e.printTraceback()
        reactor.stop()
    
    def got_data(data):
        print '# -*- coding: utf-8 -*-'
        print
        print '# root certificate list generated:', datetime.now().isoformat()
        print '# source:', CERT_SOURCE
        print