Python twisted.internet.reactor.connectSSL() Examples

The following are 30 code examples of twisted.internet.reactor.connectSSL(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.reactor , or try the search function .
Example #1
Source File: test_ssl.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testImmediateDisconnect(self):
        org = "twisted.test.test_ssl"
        self.setupServerAndClient(
            (org, org + ", client"), {},
            (org, org + ", server"), {})

        # Set up a server, connect to it with a client, which should work since our verifiers
        # allow anything, then disconnect.
        serverProtocolFactory = protocol.ServerFactory()
        serverProtocolFactory.protocol = protocol.Protocol
        self.serverPort = serverPort = reactor.listenSSL(0,
            serverProtocolFactory, self.serverCtxFactory)

        clientProtocolFactory = protocol.ClientFactory()
        clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol
        clientProtocolFactory.connectionDisconnected = defer.Deferred()
        clientConnector = reactor.connectSSL('127.0.0.1',
            serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory)

        return clientProtocolFactory.connectionDisconnected.addCallback(
            lambda ignoredResult: self.serverPort.stopListening()) 
Example #2
Source File: msn.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: client.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: test_ssl.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        test_tcp.PortCleanerUpper.setUp(self)
        self.serverConns = []
        f = protocol.ServerFactory()
        f.protocol = protocol.Protocol
        self.listener = reactor.listenSSL(
            0, f, ssl.DefaultOpenSSLContextFactory(certPath, certPath), interface="127.0.0.1",
        )
        self.ports.append(self.listener)
        f = protocol.ClientFactory()
        f.protocol = test_tcp.ConnectionLosingProtocol

        f.protocol.master = self

        L = []
        def connector():
            p = self.listener.getHost().port
            ctx = ssl.ClientContextFactory()
            return reactor.connectSSL('127.0.0.1', p, f, ctx)
        self.connector = connector

        self.totalConnections = 0 
Example #5
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def loopback(self, serverCertOpts, clientCertOpts,
                 onServerLost=None, onClientLost=None, onData=None):
        if onServerLost is None:
            self.onServerLost = onServerLost = defer.Deferred()
        if onClientLost is None:
            self.onClientLost = onClientLost = defer.Deferred()
        if onData is None:
            onData = defer.Deferred()

        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = DataCallbackProtocol
        serverFactory.onLost = onServerLost
        serverFactory.onData = onData

        clientFactory = protocol.ClientFactory()
        clientFactory.protocol = WritingProtocol
        clientFactory.onLost = onClientLost

        self.serverPort = reactor.listenSSL(0, serverFactory, serverCertOpts)
        self.clientConn = reactor.connectSSL('127.0.0.1',
                self.serverPort.getHost().port, clientFactory, clientCertOpts) 
Example #6
Source File: test_ssl.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
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"]) 
Example #7
Source File: client.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #8
Source File: test_ssl.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testImmediateDisconnect(self):
        org = "twisted.test.test_ssl"
        self.setupServerAndClient(
            (org, org + ", client"), {},
            (org, org + ", server"), {})

        # Set up a server, connect to it with a client, which should work since our verifiers
        # allow anything, then disconnect.
        serverProtocolFactory = protocol.ServerFactory()
        serverProtocolFactory.protocol = protocol.Protocol
        self.serverPort = serverPort = reactor.listenSSL(0,
            serverProtocolFactory, self.serverCtxFactory)

        clientProtocolFactory = protocol.ClientFactory()
        clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol
        clientProtocolFactory.connectionDisconnected = defer.Deferred()
        reactor.connectSSL('127.0.0.1',
            serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory)

        return clientProtocolFactory.connectionDisconnected.addCallback(
            lambda ignoredResult: self.serverPort.stopListening()) 
Example #9
Source File: test_ssl.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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") 
Example #10
Source File: pb.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def getObjectAtSSL(host, port, timeout=None, contextFactory=None):
    """DEPRECATED. Establishes a PB connection over SSL and returns with a RemoteReference.

    @param host: the host to connect to

    @param port: the port number to connect to

    @param timeout: a value in milliseconds to wait before failing by
      default. (OPTIONAL)

    @param contextFactory: A factory object for producing SSL.Context
      objects.  (OPTIONAL)

    @returns: A Deferred which will be passed a remote reference to the
      root object of a PB server.
    """
    warnings.warn("This is deprecated. Use PBClientFactory.", DeprecationWarning, 2)
    bf = PBClientFactory()
    if contextFactory is None:
        from twisted.internet import ssl
        contextFactory = ssl.ClientContextFactory()
    reactor.connectSSL(host, port, bf, contextFactory, timeout)
    return bf.getRootObject() 
Example #11
Source File: twisted_transport.py    From calvin-base with Apache License 2.0 6 votes vote down vote up
def start(self):
        jid = JID(str(self._jid) + "@gcm.googleapis.com")

        secret = _CONF.get(None, 'fcm_server_secret')
        if secret == None:
            _log.error("No secret specified")
            return
        authenticator = client.XMPPAuthenticator(jid, secret)

        callbacks = {'connected': [CalvinCB(self._connected)]}
        xmppfactory = CalvinXMLStreamFactory(authenticator, callbacks, self, self._uri)
        xmppfactory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.authenticated)

        self.protocol_factory = xmppfactory

        cf = ssl.ClientContextFactory()
        reactor.connectSSL("gcm-preprod.googleapis.com", 5236, xmppfactory, cf) 
Example #12
Source File: mail.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _sendmail(self, to_addrs, msg):
        # Import twisted.mail here because it is not available in python3
        from twisted.mail.smtp import ESMTPSenderFactory
        msg = BytesIO(msg)
        d = defer.Deferred()
        factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom, \
            to_addrs, msg, d, heloFallback=True, requireAuthentication=False, \
            requireTransportSecurity=self.smtptls)
        factory.noisy = False

        if self.smtpssl:
            reactor.connectSSL(self.smtphost, self.smtpport, factory, ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.smtphost, self.smtpport, factory)

        return d 
Example #13
Source File: test_sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def loopback(self, serverCertOpts, clientCertOpts,
                 onServerLost=None, onClientLost=None, onData=None):
        if onServerLost is None:
            self.onServerLost = onServerLost = defer.Deferred()
        if onClientLost is None:
            self.onClientLost = onClientLost = defer.Deferred()
        if onData is None:
            onData = defer.Deferred()

        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = DataCallbackProtocol
        serverFactory.onLost = onServerLost
        serverFactory.onData = onData

        clientFactory = protocol.ClientFactory()
        clientFactory.protocol = WritingProtocol
        clientFactory.onLost = onClientLost

        self.serverPort = reactor.listenSSL(0, serverFactory, serverCertOpts)
        self.clientConn = reactor.connectSSL('127.0.0.1',
                self.serverPort.getHost().port, clientFactory, clientCertOpts) 
Example #14
Source File: sender.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def send(self, recipient, message):
        self.log.info(
            'Connecting to SMTP server %s:%s' % (self._host, self._port))

        # we construct a defer to pass to the ESMTPSenderFactory
        d = defer.Deferred()
        # we don't pass an ssl context factory to the ESMTPSenderFactory
        # because ssl will be handled by reactor.connectSSL() below.
        factory = smtp.ESMTPSenderFactory(
            "",  # username is blank, no client auth here
            "",  # password is blank, no client auth here
            self._from_address,
            recipient.dest.addrstr,
            StringIO(message),
            d,
            heloFallback=True,
            requireAuthentication=False,
            requireTransportSecurity=True)
        factory.domain = bytes('leap.bitmask.mail-' + __version__)
        reactor.connectSSL(
            self._host, self._port, factory,
            contextFactory=SSLContextFactory(self._key, self._key))
        d.addCallback(lambda result: result[1][0][0])
        d.addErrback(self._send_errback)
        return d 
Example #15
Source File: test_ssl.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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") 
Example #16
Source File: msn.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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 
Example #17
Source File: test_sslverify.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def loopback(self, serverCertOpts, clientCertOpts,
                 onServerLost=None, onClientLost=None, onData=None):
        if onServerLost is None:
            self.onServerLost = onServerLost = defer.Deferred()
        if onClientLost is None:
            self.onClientLost = onClientLost = defer.Deferred()
        if onData is None:
            onData = defer.Deferred()

        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = DataCallbackProtocol
        serverFactory.onLost = onServerLost
        serverFactory.onData = onData

        clientFactory = protocol.ClientFactory()
        clientFactory.protocol = WritingProtocol
        clientFactory.onLost = onClientLost

        self.serverPort = reactor.listenSSL(0, serverFactory, serverCertOpts)
        self.clientConn = reactor.connectSSL('127.0.0.1',
                self.serverPort.getHost().port, clientFactory, clientCertOpts) 
Example #18
Source File: test_ssl.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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)

        reactor.connectSSL('127.0.0.1', port.getHost().port, client, cCTX)

        return clientProto.deferred.addCallback(
            self.assertEquals, "+OK <some crap>\r\n") 
Example #19
Source File: Luciana.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def spin_ssl(host, port, factory, contextFactory, timeout=30, bindAddress=None):
    factory = HookedFactory(factory)
    connector = selectreactor.connectSSL(host, port, factory, contextFactory,
                                         timeout, bindAddress)
    return connector 
Example #20
Source File: client.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #21
Source File: Luciana.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def spin_ssl(host, port, factory, contextFactory, timeout=30, bindAddress=None):
    factory = HookedFactory(factory)
    connector = selectreactor.connectSSL(host, port, factory, contextFactory,
                                         timeout, bindAddress)
    return connector 
Example #22
Source File: test_ssl.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testFailedVerify(self):
        org = "twisted.test.test_ssl"
        self.setupServerAndClient(
            (org, org + ", client"), {},
            (org, org + ", server"), {})

        def verify(*a):
            return False
        self.clientCtxFactory.getContext().set_verify(SSL.VERIFY_PEER, verify)

        serverConnLost = defer.Deferred()
        serverProtocol = protocol.Protocol()
        serverProtocol.connectionLost = serverConnLost.callback
        serverProtocolFactory = protocol.ServerFactory()
        serverProtocolFactory.protocol = lambda: serverProtocol
        self.serverPort = serverPort = reactor.listenSSL(0,
            serverProtocolFactory, self.serverCtxFactory)

        clientConnLost = defer.Deferred()
        clientProtocol = protocol.Protocol()
        clientProtocol.connectionLost = clientConnLost.callback
        clientProtocolFactory = protocol.ClientFactory()
        clientProtocolFactory.protocol = lambda: clientProtocol
        clientConnector = reactor.connectSSL('127.0.0.1',
            serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory)

        dl = defer.DeferredList([serverConnLost, clientConnLost], consumeErrors=True)
        return dl.addCallback(self._cbLostConns) 
Example #23
Source File: test_webclient.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #24
Source File: app.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def connectSSL(self, host, port, factory, ctxFactory, timeout=30, bindAddress=None):
        """Connect a given client protocol factory to a specific SSL server."""
        self.sslConnectors.append((host, port, factory, ctxFactory, timeout, bindAddress))
        if self.running:
            from twisted.internet import reactor
            return reactor.connectSSL(host, port, factory, ctxFactory, timeout, bindAddress) 
Example #25
Source File: test_webclient.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_connectHTTPS(self):
        """
        L{Agent._connect} uses C{connectSSL} to set up a connection to
        a server when passed a scheme of C{'https'} and returns a
        L{Deferred} which fires (when that connection is established)
        with the protocol associated with that connection.
        """
        expectedHost = 'example.com'
        expectedPort = 4321
        d = self.agent._connect('https', expectedHost, expectedPort)
        host, port, factory, contextFactory = self.reactor.sslClients.pop()[:4]
        self.assertEquals(host, expectedHost)
        self.assertEquals(port, expectedPort)
        context = contextFactory.getContext()

        # This is a pretty weak assertion.  It's true that the context must be
        # an instance of OpenSSL.SSL.Context, Unfortunately these are pretty
        # opaque and there's not much more than checking its type that we could
        # do here.  It would be nice if the SSL APIs involved more testable (ie,
        # inspectable) objects.
        self.assertIsInstance(context, ContextType)

        protocol = factory.buildProtocol(IPv4Address('TCP', '10.0.0.1', port))
        self.assertIsInstance(protocol, HTTP11ClientProtocol)
        self.completeConnection()
        d.addCallback(self.assertIdentical, protocol)
        return d 
Example #26
Source File: electruminterface.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def start_electrum_proto(self, electrum_server=None):
        self.server, self.port = self.get_server(electrum_server)
        self.factory = TxElectrumClientProtocolFactory(self)
        if DEFAULT_PROTO == 's':
            ctx = ClientContextFactory()
            reactor.connectSSL(self.server, self.port, self.factory, ctx)
        elif DEFAULT_PROTO == 't':
            reactor.connectTCP(self.server, self.port, self.factory)
        else:
            raise Exception("Unrecognized connection protocol to Electrum, "
                            "should be one of 't' or 's' (TCP or SSL), "
                            "critical error, quitting.") 
Example #27
Source File: irc.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def build_irc(self):
        """The main starting method that creates a protocol object
        according to the config variables, ready for whenever
        the reactor starts running.
        """
        wlog('building irc')
        if self.tx_irc_client:
            raise Exception('irc already built')
        if self.usessl.lower() == 'true':
            ctx = ClientContextFactory()
        if self.usessl.lower() == 'true' and not self.socks5.lower() == 'true':
            factory = TxIRCFactory(self)
            reactor.connectSSL(self.serverport[0], self.serverport[1],
                               factory, ctx)
        elif self.socks5.lower() == 'true':
            factory = TxIRCFactory(self)
            #str() casts needed else unicode error
            torEndpoint = TCP4ClientEndpoint(reactor, str(self.socks5_host),
                                             self.socks5_port)
            if self.usessl.lower() == 'true':
                use_tls = ctx
            else:
                use_tls = False
            ircEndpoint = TorSocksEndpoint(torEndpoint, self.serverport[0],
                                           self.serverport[1], tls=use_tls)
            myRS = ClientService(ircEndpoint, factory)
            myRS.startService()
        else:
            try:
                factory = TxIRCFactory(self)
                wlog('build_irc: ', self.serverport[0], str(self.serverport[1]),
                     self.channel)
                self.tcp_connector = reactor.connectTCP(
                        self.serverport[0], self.serverport[1], factory)
            except Exception as e:
                wlog('error in buildirc: ' + repr(e)) 
Example #28
Source File: util.py    From tapas with GNU General Public License v2.0 5 votes vote down vote up
def getPage(url, contextFactory=None, *args, **kwargs):
    """Download a web page as a string.

    Download a page. Return a HTTPClientFactory

    See HTTPClientFactory to see what extra args can be passed.
    """
    #scheme, host, port, path = client._parse(url)
    scheme, _ = url.split('://', 1)
    
    host_port, path = _.split('/', 1)
    try:
        host, port = host_port.split(':')
        port = int(port)
    except Exception:
        host = host_port
        port = 80
    path = '/'+path
    factory = client.HTTPClientFactory(url, *args, **kwargs)
    factory.noisy = False
    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

### files usage 
Example #29
Source File: util.py    From tapas with GNU General Public License v2.0 5 votes vote down vote up
def send_json(url, **kw):
    qurl =url+'?'+urlencode(kw.get('postdata', {}))
    # debug(0,'URLSTATS: %s',qurl)
    factory = HTTPClientFactory(str(qurl))
    factory.noisy = False
    if url.startswith('http://'):
        reactor.connectTCP(factory.host, factory.port, factory)
    elif url.startswith('https://'):
        reactor.connectSSL(factory.host, factory.port, factory, 
            ssl.ClientContextFactory())
    else:
        raise Exception('Url error: %s' %url)
    return factory 
Example #30
Source File: unreal.py    From dtella with GNU General Public License v2.0 5 votes vote down vote up
def startService(self, main):
        ifactory = IRCFactory(main)
        bind = (getBindIP(), 0)
        if self.ssl:
            from twisted.internet import ssl
            sslContext = ssl.ClientContextFactory()
            reactor.connectSSL(
                self.host, self.port, ifactory, sslContext, bindAddress=bind)
        else:
            reactor.connectTCP(self.host, self.port, ifactory, bindAddress=bind)