Пример #1
0
def installCommonReactor():
    try:
        from twisted.internet import kqreactor
        kqreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
    try:
        from twisted.internet import epollreactor
        epollreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
    try:
        from twisted.internet import pollreactor
        pollreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
Пример #2
0
def installCommonReactor():
    try:
        from twisted.internet import kqreactor
        kqreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
    try:
        from twisted.internet import epollreactor
        epollreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
    try:
        from twisted.internet import pollreactor
        pollreactor.install()
        return
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass
Пример #3
0
def test():
    port = 8443
    from twisted.internet import pollreactor

    pollreactor.install()
    from twisted.internet import reactor

    reactor.listenTCP(port, create_server_factory())

    cm = app_managers["x"] = ChannelManager()
    cid = cm.create()
    ch = cm.get(cid)
    print "cid = %s" % cid

    # and add some things
    def add_one():
        import time

        msg = {"time": time.time()}
        print "put %r" % msg
        ch.put(msg)
        reactor.callLater(1, add_one)

    reactor.callLater(1, add_one)

    reactor.run()
Пример #4
0
    def set_reactor():
        import platform

        REACTORNAME = DEFAULT_REACTORS.get(platform.system(), "select")
        # get the reactor in here
        if REACTORNAME == "kqueue":
            from twisted.internet import kqreactor

            kqreactor.install()
        elif REACTORNAME == "epoll":
            from twisted.internet import epollreactor

            epollreactor.install()
        elif REACTORNAME == "poll":
            from twisted.internet import pollreactor

            pollreactor.install()
        else:  # select is the default
            from twisted.internet import selectreactor

            selectreactor.install()

        from twisted.internet import reactor

        set_reactor = lambda: reactor
        return reactor
Пример #5
0
def run():
    if platform.system() != "Windows":
        if not sys.modules.has_key('twisted.internet.reactor'):
            print "installing poll reactor"
            from twisted.internet import pollreactor
            pollreactor.install()
        else:
            print "poll reactor already installed"
    from twisted.internet import reactor
    application = makeApplication(sys.argv)
    app.startApplication(application, None)
    reactor.run()
Пример #6
0
def run():
    if platform.system() != "Windows":
        if not sys.modules.has_key('twisted.internet.reactor'):
                print "installing poll reactor"
                from twisted.internet import pollreactor
                pollreactor.install()
        else:
                print "poll reactor already installed"
    from twisted.internet import reactor
    application = makeApplication(sys.argv)
    app.startApplication(application, None)
    reactor.run()
Пример #7
0
def main():
    
    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=443, type='int', dest='port', help='This option lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    parser.add_option('-m', '--maxConnections', default=None, type='int', dest='maxConnections', help='You can limit the number of maximum simultaneous connections with that switch')
    parser.add_option('-f', '--forcebuild', default=None, dest='customHostname', help='This option will force rebuild the certificate using the custom hostname and exit.')
    parser.add_option('-n', '--noSSL', action="store_true", default=False, dest='sslDisabled', help='You can switch off SSL with this switch.')
    (options, _) = parser.parse_args()
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    
    if not options.sslDisabled:
        create_self_signed_cert(options.customHostname)
        if options.customHostname != None:
            return
    
    try: 
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    
    x.info("Starting server on port {0}".format(options.port))
    if options.sslDisabled:
        x.warning("Starting, as requested, without SSL, connections are not secured and can be altered and eavesdropped on from client to server")
        reactor.listenTCP(options.port, SiriFactory(options.maxConnections))
    else:
        reactor.listenSSL(options.port, SiriFactory(options.maxConnections), ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE, SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Пример #8
0
def main():
    
    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    parser.add_option('-m', '--maxConnections', default=None, type='int', dest='maxConnections', help='You can limit the number of maximum simultaneous connections with that switch')
    parser.add_option('-f', '--forcelanguage', action='store_true', default=False, dest='forcelanguage', help='Force the server use language by region of device and ignore the Siri Settings language. Usefull with anyvoice cydia package. Adds functionallity for unsupported languages')
    (options, _) = parser.parse_args()
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    
    if options.forcelanguage != False:
        config.forcelanguage=True
        x.info("Forcing languages to device region and ignoring Siri Languge settings")
    else:
        config.forcelanguage=False
    
    create_self_signed_cert()
    
    try: 
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    
    x.info("Starting server on port {0}".format(options.port))
    reactor.listenSSL(options.port, SiriFactory(options.maxConnections), ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE, SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Пример #9
0
def installReactor():
    # Tries to install epoll first, then poll, and if neither are
    # available, the default select reactor will install when
    # twisted.internet.reactor is imported.
    try:
        from select import epoll
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        try:
            from select import poll
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            pass
Пример #10
0
def installReactor():
    # Tries to install epoll first, then poll, and if neither are
    # available, the default select reactor will install when
    # twisted.internet.reactor is imported.
    try:
        from select import epoll
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        try:
            from select import poll
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            pass
Пример #11
0
def set_reactor():
    import platform
    REACTORNAME = DEFAULT_REACTORS.get(platform.system(), 'select')
    #get the reactor in here
    if REACTORNAME == 'kqueue':
        from twisted.internet import kqreactor
        kqreactor.install()
    elif REACTORNAME == 'epoll':
        from twisted.internet import epollreactor
        epollreactor.install()
    elif REACTORNAME == 'poll':
        from twisted.internet import pollreactor
        pollreactor.install()
    else:  #select is the default
        from twisted.internet import selectreactor
        selectreactor.install()

    from twisted.internet import reactor
    set_reactor = lambda: reactor
    return reactor
Пример #12
0
def main():
    
    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=4443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    (options, _) = parser.parse_args()
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    
    create_self_signed_cert()
    
    try: 
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    
    x.info("Starting server on port {0}".format(options.port))
    reactor.listenSSL(options.port, SiriFactory(), ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE, SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Пример #13
0
    def run(self):
        self._log.debug( 'enter run' )
        try:
#
# With Coherence around we cannot guarantee to run early enough to chose a reactor
# So if you get errors here select the platform default reactor.
#
            if self._reactor == "poll":
                from twisted.internet import pollreactor
                pollreactor.install()

            from twisted.internet import reactor

            self._log.debug( 'twisted reactor is %s', sys.modules['twisted.internet.reactor'] )

            #from twisted.internet import task
            #l = task.LoopingCall(self.dummyCall)
            #l.start(dummyCallTime)

            reactor.run(installSignalHandlers=0)
        except Exception, ex:
            self._log.exception( ex )
Пример #14
0
    def set_reactor(self):
        """sets the reactor up"""
        #get the reactor in here
        if self.REACTORNAME == 'kqueue':
            from twisted.internet import kqreactor
            kqreactor.install()
        elif self.REACTORNAME == 'epoll':
            from twisted.internet import epollreactor
            epollreactor.install()
        elif self.REACTORNAME == 'poll':
            from twisted.internet import pollreactor
            pollreactor.install()
        else:  #select is the default
            from twisted.internet import selectreactor
            selectreactor.install()

        from twisted.internet import reactor
        self.reactor = reactor
        #shouldn't have to, but sys.exit is scary
        self.reactor.callWhenRunning(self._protect)
        #prevent this from being called ever again
        self.set_reactor = lambda: None
Пример #15
0
    def set_reactor(self):
        """sets the reactor up"""
        #get the reactor in here
        if self.REACTORNAME == 'kqueue':
            from twisted.internet import kqreactor
            kqreactor.install()
        elif self.REACTORNAME == 'epoll':
            from twisted.internet import epollreactor
            epollreactor.install()
        elif self.REACTORNAME == 'poll':
            from twisted.internet import pollreactor
            pollreactor.install()
        else: #select is the default
            from twisted.internet import selectreactor
            selectreactor.install()

        from twisted.internet import reactor
        self.reactor = reactor
        #shouldn't have to, but sys.exit is scary
        self.reactor.callWhenRunning(self._protect)
        #prevent this from being called ever again
        self.set_reactor = lambda: None
Пример #16
0
 def call():
     from twisted.internet import pollreactor
     pollreactor.install()
     from twisted.internet import reactor
     reactor.listenTCP(port, create_server_factory())
     reactor.run(installSignalHandlers=0) # we are in thread
Пример #17
0
from twisted.internet import pollreactor
from twsited.internet import reactor

pollreactor.install()  # Install the Polling reactor
reactor.run()  # Runs the Polling Reactor since its installed
Пример #18
0
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
import sys
sys.path.insert(0, "..")

from os import popen
from os.path import exists

from twisted.application import internet, service, app
from twisted.internet import pollreactor
if not sys.modules.has_key('twisted.internet.reactor'):
    pollreactor.install()                    #pragma: no cover
from twisted.internet import reactor
from twisted.python import components
from twisted.persisted import sob
from twisted.internet import error, defer

from pokernetwork import pokernetworkconfig
from pokernetwork.pokerclientpackets import *
from pokernetwork.pokerclient import PokerClientFactory
from pokernetwork.pokerclientpackets import *
from pokerstats.statslogic import PokerStats

class PokerStatsFactory(PokerClientFactory):

    def __init__(self, *args, **kwargs):
        PokerClientFactory.__init__(self, *args, **kwargs)
######################################################################
#
# Copyright (C) Zenoss, Inc. 2014, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is
# installed.
#
######################################################################
import sys

from twisted.internet import pollreactor
pollreactor.install()  # to use more than 1024 sockets

from twisted.internet import reactor, udp
from twistedsnmp import agent, agentprotocol, bisectoidstore

from bridge_oids import Network, binary_tree_topology


def main():
    '''
        Create network topology, and then
        print zenbatchdump for modeling those topology,
        if dump is a first argument
        else start simulation.
    '''
    network = Network(binary_tree_topology(deepness=14))
    if len(sys.argv) > 1 and sys.argv[1] == 'dump':
        print network.get_batchdump()
        return
Пример #20
0
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
import sys
sys.path.insert(0, "..")

from os import popen
from os.path import exists

from twisted.application import internet, service, app
from twisted.internet import pollreactor
if 'twisted.internet.reactor' not in sys.modules:
    pollreactor.install()  #pragma: no cover
from twisted.internet import reactor
from twisted.python import components
from twisted.persisted import sob
from twisted.internet import error, defer

from pokernetwork import pokernetworkconfig
from pokernetwork.pokerclient import PokerClientFactory
from pokerpackets.packets import *
from pokerpackets.networkpackets import *
from pokerpackets.clientpackets import *
from pokerstats.statslogic import PokerStats


class PokerStatsFactory(PokerClientFactory):
    def __init__(self, *args, **kwargs):
Пример #21
0
def main():
    
    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=4443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    parser.add_option('-d', '--daemon', default=None, dest='daemon', action="store_true", help='run SiriServer as a daemon')
    parser.add_option('--kill', default=None, dest='kill', help='kills a running daemon by the provided pidfile')
    (options, _) = parser.parse_args()

    createPID = False
    
    if options.daemon:
        if options.logfile:
            daemonize()        
            reatePID = True
        else:
            options.logfile = "/var/log/SiriServer.log"
            daemonize()
            createPID = True   
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    

    if options.kill != None:
        PIDFILE = options.kill
        if os.path.exists(PIDFILE):
            try:
                pidtokill = open(PIDFILE, 'r').read()
                os.kill(int(pidtokill), signal.SIGTERM)
                os.unlink(PIDFILE)
                x.info("SiriServer successfully killed")
            except:
                x.info("Error trying to Kill " + str(pidtokill))
            exit()
        else:
            x.info("Seems like SiriServer is not running...")
            exit()


    create_self_signed_cert()
    
    try: 
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    if createPID:
        PIDFILE = tempfile.mkstemp(suffix=".pid", prefix="SiriServer-", dir="/var/run")
        PIDFILE = PIDFILE[1]
        pid = str(os.getpid())
        x.info(u"Writing PID " + pid + " to " + str(PIDFILE))
        file(PIDFILE, 'w').write(pid)


    x.info("Starting server on port {0}".format(options.port))
    reactor.listenSSL(options.port, SiriFactory(), ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE, SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
######################################################################
#
# Copyright (C) Zenoss, Inc. 2014, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is
# installed.
#
######################################################################
import sys

from twisted.internet import pollreactor
pollreactor.install()  # to use more than 1024 sockets

from twisted.internet import reactor, udp
from twistedsnmp import agent, agentprotocol, bisectoidstore

from bridge_oids import Network, binary_tree_topology


def main():
    '''
        Create network topology, and then
        print zenbatchdump for modeling those topology,
        if dump is a first argument
        else start simulation.
    '''
    network = Network(binary_tree_topology(deepness=14))
    if len(sys.argv) > 1 and sys.argv[1] == 'dump':
        print network.get_batchdump()
        return
Пример #23
0
def main():

    parser = OptionParser()
    parser.add_option(
        '-l',
        '--loglevel',
        default='info',
        dest='logLevel',
        help=
        'This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info'
    )
    parser.add_option(
        '-p',
        '--port',
        default=443,
        type='int',
        dest='port',
        help=
        'This option lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)'
    )
    parser.add_option('--logfile',
                      default=None,
                      dest='logfile',
                      help='Log to a file instead of stdout.')
    parser.add_option(
        '-m',
        '--maxConnections',
        default=None,
        type='int',
        dest='maxConnections',
        help=
        'You can limit the number of maximum simultaneous connections with that switch'
    )
    parser.add_option(
        '-f',
        '--forcebuild',
        default=None,
        dest='customHostname',
        help=
        'This option will force rebuild the certificate using the custom hostname and exit.'
    )
    parser.add_option('-n',
                      '--noSSL',
                      action="store_true",
                      default=False,
                      dest='sslDisabled',
                      help='You can switch off SSL with this switch.')
    (options, _) = parser.parse_args()

    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])

    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()

    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)

    if not options.sslDisabled:
        create_self_signed_cert(options.customHostname)
        if options.customHostname != None:
            return

    try:
        from twisted.internet import epollreactor
        epollreactor.install()
    except ImportError:
        x.debug("System does not support epoll")
        x.debug("-> Will use simple poll")
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except ImportError:
            x.debug("System does not support poll")
            x.debug("-> Will use default select interface")
    from twisted.internet import reactor

    x.info("Starting server on port {0}".format(options.port))
    if options.sslDisabled:
        x.warning(
            "Starting, as requested, without SSL, connections are not secured and can be altered and eavesdropped on from client to server"
        )
        reactor.listenTCP(options.port, SiriFactory(options.maxConnections))
    else:
        reactor.listenSSL(
            options.port, SiriFactory(options.maxConnections),
            ssl.DefaultOpenSSLContextFactory(SERVER_KEY_FILE,
                                             SERVER_CERT_FILE))
    reactor.run()
    x.info("Server shutdown complete")
Пример #24
0
try:
    from twisted.internet import pollreactor
    pollreactor.install()
except:
    pass
from twisted.internet import protocol, reactor, defer, task
from twisted.web import http, proxy, resource, server
from twisted.python import log
import sys, time
import urlparse
import socket
import simplejson
import re

SSH_USER = '******'
AUTHORIZED_KEYS = '/home/localtunnel/.ssh/authorized_keys'
PORT_RANGE = [32000, 64000]
BANNER = "This localtunnel service is brought to you by Twilio."
SSH_OPTIONS = 'command="/bin/echo Shell access denied",no-agent-forwarding,no-pty,no-user-rc,no-X11-forwarding '
KEY_REGEX = re.compile(r'^ssh-(\w{3}) [^\n]+$')


def port_available(port):
    try:
        socket.create_connection(['127.0.0.1', port]).close()
        return False
    except socket.error:
        return True


def baseN(num, b=32, numerals="23456789abcdefghijkmnpqrstuvwxyz"):
Пример #25
0
from monocle import launch

# prefer fast reactors
# FIXME: this should optionally refuse to use slow ones
if not "twisted.internet.reactor" in sys.modules:
    try:
        from twisted.internet import epollreactor
        epollreactor.install()
    except:
        try:
            from twisted.internet import kqreactor
            kqreactor.install()
        except:
            try:
                from twisted.internet import pollreactor
                pollreactor.install()
            except:
                pass

from twisted.internet import reactor
try:
    from twisted.internet.error import ReactorNotRunning
except ImportError:
    ReactorNotRunning = RuntimeError


# thanks to Peter Norvig
def singleton(object, message="singleton class already instantiated",
              instantiated=[]):
    """
    Raise an exception if an object of this class has been instantiated before.
Пример #26
0
#!/usr/bin/env python

import sys, os
script_path = os.path.realpath(os.path.dirname(sys.argv[0]))
gnutls_path = os.path.realpath(os.path.join(script_path, '..'))
sys.path[0:0] = [gnutls_path]

from application.debug.timing import timer

from optparse import OptionParser

from twisted.internet import pollreactor; pollreactor.install()
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineOnlyReceiver
from twisted.internet import reactor

from gnutls.crypto import *
from gnutls.connection import *
from gnutls.errors import *
from gnutls.interfaces.twisted import X509Credentials

class EchoProtocol(LineOnlyReceiver):

    def connectionMade(self):
        self.sendLine('GET /')
        #self.transport.loseConnection()

    def lineReceived(self, line):
        self.transport.loseConnection()

    def connectionLost(self, reason):