我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.internet.ssl.ClientContextFactory()。
def _login(userHandle, passwd, nexusServer, cached=0, authData=''): """ This function is used internally and should not ever be called directly. """ cb = Deferred() def _cb(server, auth): loginFac = ClientFactory() loginFac.protocol = lambda : PassportLogin(cb, userHandle, passwd, server, auth) reactor.connectSSL(_parsePrimitiveHost(server)[0], 443, loginFac, ClientContextFactory()) if cached: _cb(nexusServer, authData) else: fac = ClientFactory() d = Deferred() d.addCallbacks(_cb, callbackArgs=(authData,)) d.addErrback(lambda f: cb.errback(f)) fac.protocol = lambda : PassportNexus(d, nexusServer) reactor.connectSSL(_parsePrimitiveHost(nexusServer)[0], 443, fac, ClientContextFactory()) return cb
def downloadPage(url, file, contextFactory=None, *args, **kwargs): """Download a web page to a file. @param file: path to file on filesystem, or file-like object. See HTTPDownloader to see what extra args can be passed. """ scheme, host, port, path = _parse(url) factory = HTTPDownloader(url, file, *args, **kwargs) if scheme == 'https': from twisted.internet import ssl if contextFactory is None: contextFactory = ssl.ClientContextFactory() reactor.connectSSL(host, port, factory, contextFactory) else: reactor.connectTCP(host, port, factory) return factory.deferred
def testOpenSSLBuffering(self): serverProto = self.serverProto = SingleLineServerProtocol() clientProto = self.clientProto = RecordingClientProtocol() server = protocol.ServerFactory() client = self.client = protocol.ClientFactory() server.protocol = lambda: serverProto client.protocol = lambda: clientProto client.buffer = [] sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath) cCTX = ssl.ClientContextFactory() port = self.port = reactor.listenSSL(0, server, sCTX, interface='127.0.0.1') reactor.connectSSL('127.0.0.1', port.getHost().port, client, cCTX) i = 0 while i < 5000 and not client.buffer: i += 1 reactor.iterate() self.assertEquals(client.buffer, ["+OK <some crap>\r\n"])
def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs): if hasattr(client, '_parse'): scheme, host, port, path = client._parse(url) else: try: from twisted.web.client import _URI as URI except ImportError: from twisted.web.client import URI uri = URI.fromBytes(url) scheme = uri.scheme host = uri.host port = uri.port or (443 if scheme == 'https' else 80) path = uri.path self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs) if scheme == "https": from twisted.internet import ssl if contextFactory is None: contextFactory = ssl.ClientContextFactory() self.connection = reactor.connectSSL(host, port, self.factory, contextFactory) else: self.connection = reactor.connectTCP(host, port, self.factory)
def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs): if hasattr(client, '_parse'): scheme, host, port, path = client._parse(url) else: try: from twisted.web.client import _URI as URI except ImportError: from twisted.web.client import URI uri = URI.fromBytes(url) scheme = uri.scheme host = uri.host port = uri.port path = uri.path self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs) if scheme == 'https': from twisted.internet import ssl if contextFactory is None: contextFactory = ssl.ClientContextFactory() self.connection = reactor.connectSSL(host, port, self.factory, contextFactory) else: self.connection = reactor.connectTCP(host, port, self.factory)
def onClose(self, wasClean, code, reason): # print("onClose") # print("WebSocket connection closed: {0}".format(reason), "code: ", # code, "clean: ", wasClean, "reason: ", reason) self.summary[self.uttNumber]['status']['code'] = code self.summary[self.uttNumber]['status']['reason'] = reason # create a new WebSocket connection if there are still # utterances in the queue that need to be processed self.queue.task_done() if self.factory.prepareUtterance() == False: return # SSL client context: default if self.factory.isSecure: contextFactory = ssl.ClientContextFactory() else: contextFactory = None connectWS(self.factory, contextFactory) # function to check that a value is a positive integer
def getPage(url, contextFactory=None, *args, **kwargs): """Download a web page as a string. Download a page. Return a deferred, which will callback with a page (as a string) or errback with a description of the error. See HTTPClientFactory to see what extra args can be passed. """ scheme, host, port, path = _parse(url) factory = HTTPClientFactory(url, *args, **kwargs) if scheme == 'https': from twisted.internet import ssl if contextFactory is None: contextFactory = ssl.ClientContextFactory() reactor.connectSSL(host, port, factory, contextFactory) else: reactor.connectTCP(host, port, factory) return factory.deferred
def connect_to_cloud_channel(self): """ Connect up to the cloud channel with UUID uuid :param uuid: the UUID of this device. The uuid determines which channel you are connected to :return: """ if self.uuid is None or self.uuid == "": raise RuntimeError("Must have a valid UUID to connect to the cloud") if self.connected_to_cloud: raise RuntimeError("Already Connected to cloud") yield self.get_channel() # cool, now set up the websocket connection to that channel reactor = self._adapter.reactor print "attempting to connect to", self.channel_uri self.cloud_factory = CloudLinkWebsocketClientFactory(self, self.channel_uri, reactor=reactor) self.cloud_factory.protocol = CloudLinkWebsocketClient self.cloud_factory.continueTrying = True # attempt to reconnect if self.channel_uri.startswith("wss"): reactor.connectSSL(self.cloud_factory.host, self.cloud_factory.port, self.cloud_factory, ssl.ClientContextFactory()) else: reactor.connectTCP(self.cloud_factory.host, self.cloud_factory.port, self.cloud_factory)
def send_stats(self): global r global msg global site_seen self.send_data = json.dumps(r.publish()) print "DC: Sending TS our stats!" self.sendLine(self.send_data) #clean up objects and refresh site_seen.clear() r = None msg = [] r = router(q, labels, tkgs, args.fingerprint, args.consensus) for kid, a in zip(r.keys, tkgs): msg.append(r.authority_msg(kid)) time.sleep(dc_reg_delay) for host, port in tkg_info: reactor.connectSSL(host, int(port), c_factory, ssl.ClientContextFactory())
def onClose(self, wasClean, code, reason): print("onClose") print( "WebSocket connection closed: {0}".format(reason), "code: ", code, "clean: ", wasClean, "reason: ", reason) self.summary['status']['code'] = code self.summary['status']['reason'] = reason if (code == 1000): self.summary['status']['successful'] = True if self.factory.prepareUtterance() == False: return # SSL client context: default if self.factory.isSecure: contextFactory = ssl.ClientContextFactory() else: contextFactory = None connectWS(self.factory, contextFactory)
def test_openSSLBuffering(self): serverProto = self.serverProto = SingleLineServerProtocol() clientProto = self.clientProto = RecordingClientProtocol() server = protocol.ServerFactory() client = self.client = protocol.ClientFactory() server.protocol = lambda: serverProto client.protocol = lambda: clientProto sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath) cCTX = ssl.ClientContextFactory() port = reactor.listenSSL(0, server, sCTX, interface='127.0.0.1') self.addCleanup(port.stopListening) clientConnector = reactor.connectSSL('127.0.0.1', port.getHost().port, client, cCTX) self.addCleanup(clientConnector.disconnect) return clientProto.deferred.addCallback( self.assertEqual, b"+OK <some crap>\r\n")
def _getContextFactory(self): """ Get a context factory with which to negotiate TLS. @rtype: L{None} or L{ClientContextFactory <twisted.internet.ssl.ClientContextFactory>} @return: A context factory or L{None} if TLS is not supported on the client. """ try: from twisted.internet import ssl except ImportError: return None else: context = ssl.ClientContextFactory() context.method = ssl.SSL.TLSv1_METHOD return context
def makeService(config): # finger on port 79 msvc = service.MultiService() fix_spec = Spec(config['spec']) fix_service = FixClientService(config) fix_service.setName('txfixclient') fix_service.setServiceParent(msvc) factory = FixClientFactory(fix_service) factory.spec = fix_spec factory.maxDelay = 300 tcp_service = internet.SSLClient( config['hostname'], int(config['port']), factory, ssl.ClientContextFactory() ) tcp_service.setServiceParent(msvc) return msvc
def callRemote(self, method, *args): factory = AuthQueryFactory(self.url, method, *args) if self.secure: from twisted.internet import ssl reactor.connectSSL(self.host, self.port or 443, factory, ssl.ClientContextFactory()) else: reactor.connectTCP(self.host, self.port or 80, factory) return factory.deferred
def do_checkin(self): ''' Called by protocol Refresh the config, and try to connect to the server This function is usually called using loopingCall, so any exceptions will be turned into log messages. ''' # TODO: Refactor common client code - issue #121 self.refresh_config() ts_ip = self.config['tally_server_info']['ip'] ts_port = self.config['tally_server_info']['port'] # turn on reconnecting mode and reset backoff self.resetDelay() logging.info("checking in with TallyServer at {}:{}".format(ts_ip, ts_port)) reactor.connectSSL(ts_ip, ts_port, self, ssl.ClientContextFactory()) # pylint: disable=E1101
def do_checkin(self): ''' Called by protocol Refresh the config, and try to connect to the server This function is usually called using LoopingCall, so any exceptions will be turned into log messages. ''' # TODO: Refactor common client code - issue #121 self.refresh_config() self.check_aggregator() ts_ip = self.config['tally_server_info']['ip'] ts_port = self.config['tally_server_info']['port'] # turn on reconnecting mode and reset backoff self.resetDelay() logging.info("checking in with TallyServer at {}:{}".format(ts_ip, ts_port)) reactor.connectSSL(ts_ip, ts_port, self, ssl.ClientContextFactory()) # pylint: disable=E1101
def proxyViaSSL(self, host, method, path, postData, headers, port): self.save_req("debug_ssl.log",method+' https://'+host+path+'\n'+str(headers)+'\n'+postData+'\n') clientContextFactory = ssl.ClientContextFactory() connectionFactory = ServerConnectionFactory(method, path, postData, headers, self) connectionFactory.protocol = SSLServerConnection self.reactor.connectSSL(host, port, connectionFactory, clientContextFactory)
def proxyViaSSL(self, host, method, path, postData, headers, port): clientContextFactory = ssl.ClientContextFactory() connectionFactory = ServerConnectionFactory(method, path, postData, headers, self) connectionFactory.protocol = SSLServerConnection self.reactor.connectSSL(host, port, connectionFactory, clientContextFactory)
def handleStatus_301(self): l = self.headers.get('location') if not l: self.handleStatusDefault() return url = l[0] if self.followRedirect: scheme, host, port, path = \ _parse(url, defaultPort=self.transport.getPeer().port) self.factory.setURL(url) if self.factory.scheme == 'https': from twisted.internet import ssl contextFactory = ssl.ClientContextFactory() reactor.connectSSL(self.factory.host, self.factory.port, self.factory, contextFactory) else: reactor.connectTCP(self.factory.host, self.factory.port, self.factory) else: self.handleStatusDefault() self.factory.noPage( failure.Failure( error.PageRedirect( self.status, self.message, location = url))) self.quietLoss = 1 self.transport.loseConnection()
def testFactoryInfo(self): url = self.getURL('file') scheme, host, port, path = client._parse(url) factory = client.HTTPClientFactory(url) reactor.connectSSL(host, port, factory, ssl.ClientContextFactory()) # The base class defines _cbFactoryInfo correctly for this return factory.deferred.addCallback(self._cbFactoryInfo, factory)
def callRemote(self, method, *args): factory = _QueryFactory( self.path, self.host, method, self.user, self.password, self.allowNone, args) if self.secure: from twisted.internet import ssl reactor.connectSSL(self.host, self.port or 443, factory, ssl.ClientContextFactory()) else: reactor.connectTCP(self.host, self.port or 80, factory) return factory.deferred
def startTLS(self, contextFactory=None): """ Initiates a 'STARTTLS' request and negotiates the TLS / SSL Handshake. @param contextFactory: The TLS / SSL Context Factory to leverage. If the contextFactory is None the IMAP4Client will either use the current TLS / SSL Context Factory or attempt to create a new one. @type contextFactory: C{ssl.ClientContextFactory} @return: A Deferred which fires when the transport has been secured according to the given contextFactory, or which fails if the transport cannot be secured. """ assert not self.startedTLS, "Client and Server are currently communicating via TLS" if contextFactory is None: contextFactory = self._getContextFactory() if contextFactory is None: return defer.fail(IMAP4Exception( "IMAP4Client requires a TLS context to " "initiate the STARTTLS handshake")) if 'STARTTLS' not in self._capCache: return defer.fail(IMAP4Exception( "Server does not support secure communication " "via TLS / SSL")) tls = interfaces.ITLSTransport(self.transport, None) if tls is None: return defer.fail(IMAP4Exception( "IMAP4Client transport does not implement " "interfaces.ITLSTransport")) d = self.sendCommand(Command('STARTTLS')) d.addCallback(self._startedTLS, contextFactory) d.addCallback(lambda _: self.getCapabilities()) return d
def _getContextFactory(self): if self.context is not None: return self.context try: from twisted.internet import ssl except ImportError: return None else: try: context = ssl.ClientContextFactory() context.method = ssl.SSL.TLSv1_METHOD return context except AttributeError: return None
def getContext(self): try: from twisted.internet import ssl except ImportError: self.ctx = None else: self.ctx = ssl.ClientContextFactory() self.ctx.method = ssl.SSL.TLSv1_METHOD
def startTLS(self, contextFactory=None): """ Initiates a 'STLS' request and negotiates the TLS / SSL Handshake. @type contextFactory: C{ssl.ClientContextFactory} @param contextFactory: The context factory with which to negotiate TLS. If C{None}, try to create a new one. @return: A Deferred which fires when the transport has been secured according to the given contextFactory, or which fails if the transport cannot be secured. """ tls = interfaces.ITLSTransport(self.transport, None) if tls is None: return defer.fail(TLSError( "POP3Client transport does not implement " "interfaces.ITLSTransport")) if contextFactory is None: contextFactory = self._getContextFactory() if contextFactory is None: return defer.fail(TLSError( "POP3Client requires a TLS context to " "initiate the STLS handshake")) d = self.capabilities() d.addCallback(self._startTLS, contextFactory, tls) return d
def _getContextFactory(self): try: from twisted.internet import ssl except ImportError: return None else: context = ssl.ClientContextFactory() context.method = ssl.SSL.TLSv1_METHOD return context
def instantiate_bot(self, user): user_factory = UserBotFactory( self, user, self.channels, self.bridge_nickname, self.nickserv_password, ) reactor.connectSSL( IRC_HOST, IRC_PORT, user_factory, ssl.ClientContextFactory() )
def on_ready(self): connectWS(MarketStreamClientFactory(market_stream), ssl.ClientContextFactory())
def _getContextFactory(self): if self.context is not None: return self.context try: from twisted.internet import ssl except ImportError: return None else: context = ssl.ClientContextFactory() context.method = ssl.SSL.TLSv1_METHOD return context