Beispiel #1
0
	def __init__(self):
		# Check for any other instances
		if config.pid and os.name != "posix":
			config.pid = ""
		if config.pid:
			twistd.checkPID(config.pid)

		# Do any auto-update stuff
		xdb.housekeep()

		# Daemonise the process and write the PID file
		if daemonizeme and os.name == "posix":
			twistd.daemonize()
		if config.pid:
			self.writePID()

		jid = config.jid
		if config.useXCP and config.compjid: jid = config.compjid

		if config.saslUsername:
			import sasl
			self.c = sasl.buildServiceManager(jid, config.saslUsername, config.secret, "tcp:%s:%s" % (config.mainServer, config.port))
		else:
			self.c = component.buildServiceManager(jid, config.secret, "tcp:%s:%s" % (config.mainServer, config.port))
		self.transportSvc = PyTransport()
		self.transportSvc.setServiceParent(self.c)
		self.c.startService()

		reactor.addSystemEventTrigger('before', 'shutdown', self.shuttingDown)
Beispiel #2
0
    def run_command(self, kw):
        """Run a twistd webserver."""
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.

        self.prepare_kwds(kw)
        conf = os.path.join(kw["directory"], "twistedconf.tac")
        if platformType != "win32":
            from twisted.scripts._twistd_unix import checkPID

            try:
                checkPID(kw["pidfile"])
            except SystemExit as e:
                pid = int(open(kw["pidfile"]).read())

                if str(e).startswith("Another twistd server is running,"):
                    print "Another Sage Notebook server is running, PID %d." % pid

                    old_interface, old_port, old_secure = self.get_old_settings(conf)
                    if (kw["automatic_login"] or kw["upload"]) and old_port:
                        old_interface = old_interface or "localhost"
                        if kw["upload"]:
                            import urllib

                            startpath = "/upload_worksheet?url=file://%s" % (urllib.quote(kw["upload"]))
                        else:
                            startpath = "/"

                        print "Opening web browser at http%s://%s:%s%s ..." % (
                            "s" if old_secure else "",
                            old_interface,
                            old_port,
                            startpath,
                        )

                        from sagenb.misc.misc import open_page as browse_to

                        browse_to(old_interface, old_port, old_secure, startpath)
                        return None
                    print "\nPlease either stop the old server or run the new server in a different directory."
                    return None

        ## Create the config file
        if kw["secure"]:
            kw["strport"] = (
                "ssl:%(port)s:interface=%(interface)s:privateKey=%(private_pem)s:certKey=%(public_pem)s" % kw
            )
        else:
            kw["strport"] = "tcp:%(port)s:interface=%(interface)s" % kw

        with open(conf, "w") as config:
            config.write((self.config_stub + self.TWISTD_NOTEBOOK_CONFIG) % kw)

        if kw["profile"]:
            profilecmd = "--profile=%s --profiler=cprofile --savestats" % self.profile_file(kw["profile"])
        else:
            profilecmd = ""
        cmd = 'twistd %s --pidfile="%s" -ny "%s"' % (profilecmd, kw["pidfile"], conf)
        return cmd
Beispiel #3
0
    def run_command(self, kw):
        """Run a twistd webserver."""
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.

        self.prepare_kwds(kw)
        conf = os.path.join(kw['directory'], 'twistedconf.tac')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(kw['pidfile'])
            except SystemExit as e:
                pid = int(open(kw['pidfile']).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid

                    old_interface, old_port, old_secure = self.get_old_settings(conf)
                    if (kw['automatic_login'] or kw['upload']) and old_port:
                        old_interface = old_interface or 'localhost'
                        if kw['upload']:
                            import urllib
                            startpath = '/upload_worksheet?url=file://%s' % (urllib.quote(kw['upload']))
                        else:
                            startpath = '/'

                        print 'Opening web browser at http%s://%s:%s%s ...' % (
                            's' if old_secure else '', old_interface, old_port, startpath)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, startpath)
                        return None
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return None

        ## Create the config file
        if kw['secure']:
            kw['strport'] = 'ssl:%(port)s:interface=%(interface)s:privateKey=%(private_pem)s:certKey=%(public_pem)s'%kw
        else:
            kw['strport'] = 'tcp:%(port)s:interface=%(interface)s'%kw


        with open(conf, 'w') as config:
            config.write((self.config_stub+self.TWISTD_NOTEBOOK_CONFIG)%kw)

        if kw['profile']:
            profilecmd = '--profile=%s --profiler=cprofile --savestats'%self.profile_file(kw['profile'])
        else:
            profilecmd=''
        cmd = 'twistd %s --pidfile="%s" -ny "%s"' % (profilecmd, kw['pidfile'], conf)
        return cmd
Beispiel #4
0
    def run_command(self, kw):
        """Run a twistd webserver."""
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.

        self.prepare_kwds(kw)
        conf = os.path.join(kw['directory'], 'twistedconf.tac')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(kw['pidfile'])
            except SystemExit as e:
                pid = int(open(kw['pidfile']).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid

                    old_interface, old_port, old_secure = self.get_old_settings(conf)
                    if (kw['automatic_login'] or kw['upload']) and old_port:
                        old_interface = old_interface or 'localhost'
                        if kw['upload']:
                            import urllib
                            startpath = '/upload_worksheet?url=file://%s' % (urllib.quote(kw['upload']))
                        else:
                            startpath = '/'

                        print 'Opening web browser at http%s://%s:%s%s ...' % (
                            's' if old_secure else '', old_interface, old_port, startpath)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, startpath)
                        return None
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return None

        ## Create the config file
        if kw['secure']:
            kw['strport'] = 'ssl:%(port)s:interface=%(interface)s:privateKey=%(private_pem)s:certKey=%(public_pem)s'%kw
        else:
            kw['strport'] = 'tcp:%(port)s:interface=%(interface)s'%kw


        with open(conf, 'w') as config:
            config.write((self.config_stub+self.TWISTD_NOTEBOOK_CONFIG)%kw)

        if kw['profile']:
            profilecmd = '--profile=%s --profiler=cprofile --savestats'%self.profile_file(kw['profile'])
        else:
            profilecmd=''
        cmd = 'twistd %s --pidfile="%s" -ny "%s"' % (profilecmd, kw['pidfile'], conf)
        return cmd
Beispiel #5
0
    def run(port, subnets):
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.
        pidfile = os.path.join(directory, 'twistd.pid')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(pidfile)
            except SystemExit as e:
                pid = int(open(pidfile).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid
                    old_interface, old_port, old_secure = get_old_settings(conf)
                    if open_viewer and old_port:
                        old_interface = old_interface or 'localhost'

                        print 'Opening web browser at http%s://%s:%s/ ...' % (
                            's' if old_secure else '', old_interface, old_port)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, '/')
                        return
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return

        ## Create the config file
        if secure:
            if (not os.path.exists(private_pem) or
                not os.path.exists(public_pem)):
                print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()."
                print "Now running notebook.setup()"
                notebook_setup()
            if (not os.path.exists(private_pem) or
                not os.path.exists(public_pem)):
                print "Failed to setup notebook.  Please try notebook.setup() again manually."
            strport = '%s:%s:interface=%s:privateKey=%s:certKey=%s' % (
                protocol, port, interface, private_pem, public_pem)
        else:
            strport = 'tcp:%s:interface=%s' % (port, interface)

        notebook_opts = '"%s",interface="%s",port=%s,secure=%s' % (
            os.path.abspath(directory), interface, port, secure)

        if open_viewer:
            if require_login:
                start_path = "'/?startup_token=%s' % startup_token"
            else:
                start_path = "'/'"
            if interface:
                hostname = interface
            else:
                hostname = 'localhost'
            open_page = "from sagenb.misc.misc import open_page; open_page('%s', %s, %s, %s)" % (hostname, port, secure, start_path)
        else:
            open_page = ''

        config = open(conf, 'w')

        if subnets is None:
            factory = "factory = channel.HTTPFactory(site)"
        else:
            if not isinstance(subnets, (list, tuple)):
                subnets = [subnets]
            factory = """
# See http://stackoverflow.com/questions/1273297/python-twisted-restricting-access-by-ip-address
from sagenb.misc.ipaddr import IPNetwork
subnets = eval(r"%s")
if not any(s.startswith('127') for s in subnets):
    subnets.insert(0, '127.0.0.0/8')
subnets = [IPNetwork(x) for x in subnets]
class RestrictedIPFactory(channel.HTTPFactory):
    def buildProtocol(self, addr):
        a = str(addr.host)
        for X in subnets:
            if a in X:
                return channel.HTTPFactory.buildProtocol(self, addr)
        print 'Ignoring all requests from IP address '+str(addr.host)

factory = RestrictedIPFactory(site)
""" % tuple([subnets])

        config.write("""
####################################################################
# WARNING -- Do not edit this file!   It is autogenerated each time
# the notebook(...) command is executed.
####################################################################
from twisted.internet import reactor

# Now set things up and start the notebook
import sagenb.notebook.notebook
sagenb.notebook.notebook.JSMATH=True
import sagenb.notebook.notebook as notebook
import sagenb.notebook.twist as twist
twist.notebook = notebook.load_notebook(%s)
twist.SAGETEX_PATH = %r
twist.OPEN_MODE = %s
twist.SID_COOKIE = str(hash(%r))
twist.DIR = %r
twist.reactor = reactor
twist.init_updates()
import sagenb.notebook.worksheet as worksheet

import signal, sys, random
def save_notebook():
    from twisted.internet.error import ReactorNotRunning
    print "Quitting all running worksheets..."
    twist.notebook.quit()
    print "Saving notebook..."
    twist.notebook.save()
    print "Notebook cleanly saved."

def my_sigint(x, n):
    try:
        reactor.stop()
    except ReactorNotRunning:
        pass
    signal.signal(signal.SIGINT, signal.SIG_DFL)


signal.signal(signal.SIGINT, my_sigint)

## Disable client-side certificate request for gnutls
try:
    import gnutls.connection
    gnutls.connection.CERT_REQUEST = 0
except (OSError, ImportError):
    print "Note: GNUTLS not available."


## Authentication framework (ported from Knooboo)
from twisted.web2 import log, server, channel
from twisted.cred import portal, checkers, credentials
import sagenb.notebook.guard as guard
import sagenb.notebook.avatars as avatars

from twisted.cred import portal

realm = avatars.LoginSystem()
p = portal.Portal(realm)
startup_token = '%%x' %% random.randint(0, 2**128)
startup_checker = avatars.OneTimeTokenChecker()
startup_checker.token = startup_token
p.registerChecker(startup_checker)
password_checker = avatars.PasswordChecker()
p.registerChecker(password_checker)
p.registerChecker(checkers.AllowAnonymousAccess())
rsrc = guard.MySessionWrapper(p)
log.DefaultCommonAccessLoggingObserver().start()
site = server.Site(rsrc)
%s
from twisted.web2 import channel
from twisted.application import service, strports
application = service.Application("SAGE Notebook")
s = strports.service(%r, factory)
%s
s.setServiceParent(application)

reactor.addSystemEventTrigger('before', 'shutdown', save_notebook)

""" % (notebook_opts, sagetex_path, not require_login,
       os.path.abspath(directory), cwd, factory,
       strport, open_page))

        config.close()

        ## Start up twisted
        cmd = 'twistd --pidfile="%s" -ny "%s"' % (pidfile, conf)
        if not quiet:
            print_open_msg('localhost' if not interface else interface,
                           port, secure=secure)
        if secure and not quiet:
            print "There is an admin account.  If you do not remember the password,"
            print "quit the notebook and type notebook(reset=True)."

        if fork:
            import pexpect
            return pexpect.spawn(cmd)
        else:
            e = os.system(cmd)

        os.chdir(cwd)
        if e == 256:
            raise socket.error

        return True
Beispiel #6
0
    def run(port):
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.
        pidfile = os.path.join(directory, 'twistd.pid')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(pidfile)
            except SystemExit as e:
                pid = int(open(pidfile).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid
                    old_interface, old_port, old_secure = get_old_settings(conf)
                    if open_viewer and old_port:
                        old_interface = old_interface or 'localhost'

                        print 'Opening web browser at http%s://%s:%s/ ...' % (
                            's' if old_secure else '', old_interface, old_port)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, '/')
                        return
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return

        ## Create the config file
        if secure:
            if (not os.path.exists(private_pem) or
                not os.path.exists(public_pem)):
                print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()."
                print "Now running notebook.setup()"
                notebook_setup()
            if (not os.path.exists(private_pem) or
                not os.path.exists(public_pem)):
                print "Failed to setup notebook.  Please try notebook.setup() again manually."
            strport = '%s:%s:interface=%s:privateKey=%s:certKey=%s'%(
                protocol, port, interface, private_pem, public_pem)
        else:
            strport = 'tcp:%s:interface=%s' % (port, interface)

        notebook_opts = '"%s",interface="%s",port=%s,secure=%s' % (
            os.path.abspath(directory), interface, port, secure)

        if open_viewer:
            start_path = "'/?startup_token=%s' % startup_token"
            if interface:
                hostname = interface
            else:
                hostname = 'localhost'
            open_page = "from sagenb.misc.misc import open_page; open_page('%s', %s, %s, %s)" % (hostname, port, secure, start_path)
        else:
            open_page = ''

        config = open(conf, 'w')

        config.write(FLASK_NOTEBOOK_CONFIG%{'notebook_opts': notebook_opts, 'sagetex_path': sagetex_path,
                                            'do_not_require_login': not require_login,
                                            'dir': os.path.abspath(directory), 'cwd':cwd, 
                                            'strport': strport,
                                            'open_page': open_page})


        config.close()                     

        ## Start up twisted
        cmd = 'twistd --pidfile="%s" -ny "%s"' % (pidfile, conf)
        if not quiet:
            print_open_msg('localhost' if not interface else interface,
            port, secure=secure)
        if secure and not quiet:
            print "There is an admin account.  If you do not remember the password,"
            print "quit the notebook and type notebook(reset=True)."

        if fork:
            import pexpect
            return pexpect.spawn(cmd)
        else:
            e = os.system(cmd)

        os.chdir(cwd)
        if e == 256:
            raise socket.error

        return True
Beispiel #7
0
    def run(port, subnets):
        ## Create the config file
        if secure:
            if not os.path.exists(private_pem) or not os.path.exists(public_pem):
                print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()."
                print "Now running notebook.setup()"
                notebook_setup()
            if not os.path.exists(private_pem) or not os.path.exists(public_pem):
                print "Failed to setup notebook.  Please try notebook.setup() again manually."
            strport = '%s:%s:interface=%s:privateKey=%s:certKey=%s'%(protocol, port, interface, private_pem, public_pem)
        else:
            strport = 'tcp:%s:interface=%s'%(port, interface)

        notebook_opts = '"%s",interface="%s",port=%s,secure=%s' % (os.path.abspath(directory),
                interface, port, secure)

        if open_viewer:
            start_path = "'/?startup_token=%s' % startup_token"
            if interface:
                hostname = interface
            else:
                hostname = 'localhost'
            open_page = "from sagenb.misc.misc import open_page; open_page('%s', %s, %s, %s)"%(hostname, port, secure, start_path)
        else:
            open_page = ''
        
        config = open(conf, 'w')

        if subnets is None:
            factory = "factory = channel.HTTPFactory(site)"
        else:
            if not isinstance(subnets, (list, tuple)):
                subnets = [subnets]
            factory = """
# See http://stackoverflow.com/questions/1273297/python-twisted-restricting-access-by-ip-address
from sagenb.misc.ipaddr import IPNetwork
subnets = eval(r"%s")
if not any(s.startswith('127') for s in subnets):
    subnets.insert(0, '127.0.0.0/8')
subnets = [IPNetwork(x) for x in subnets]
class RestrictedIPFactory(channel.HTTPFactory):
    def buildProtocol(self, addr):
        a = str(addr.host)
        for X in subnets:
            if a in X:
                return channel.HTTPFactory.buildProtocol(self, addr)
        print 'Ignoring all requests from IP address '+str(addr.host)
        
factory = RestrictedIPFactory(site)
"""%tuple([subnets])

        config.write(FLASK_NOTEBOOK_CONFIG%{'notebook_opts': notebook_opts, 'sagetex_path': sagetex_path,
                                            'do_not_require_login': not require_login,
                                            'dir': os.path.abspath(directory), 'cwd':cwd, 
                                            'factory': factory, 'strport': strport,
                                            'open_page': open_page})


        config.close()                     

        pidfile = os.path.join(directory, 'twistd.pid')
        cmd = 'twistd --pidfile="%s" -ny "%s"' % (pidfile, os.path.join(directory, 'twistedconf.tac'))

        # Check if a Twistd PID exists in the given directory
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(pidfile)
            except SystemExit as e:
                pid = int(open(pidfile).read())
                if str(e).startswith('Another twistd server is running,'):
                    sys.exit("""\
Another Sage Notebook server is running, PID %d.

Please either stop the old server or run the new server in a different directory.
""" % pid)
        ## Start up twisted
        if not quiet:
            print_open_msg('localhost' if not interface else interface, port, secure=secure)
        if secure and not quiet:
            print "There is an admin account.  If you do not remember the password,"
            print "quit the notebook and type notebook(reset=True)."

        if fork:
            import pexpect
            return pexpect.spawn(cmd)
        else:
            e = os.system(cmd)

        os.chdir(cwd)
        if e == 256:
            raise socket.error

        return True
Beispiel #8
0
def startTwisted(application,
                 startDir='./',
                 nodaemon=0,
                 logfile=None,
                 rundir='.',
                 appname='tums',
                 pidfile='/var/run/tums.pid'):
    """ A freezable twistd bootstrap layer """
    from twisted.application import service, internet, strports, app
    from twisted.python import log, syslog
    try:
        from twisted.scripts import _twistd_unix as twistd
    except:
        from twisted.scripts import twistd

    config = {
        'profile': None,
        'reactor': None,
        'encrypted': 0,
        'syslog': 0,
        'prefix': appname,
        'report-profile': None,
        'euid': 0,
        'file': 'twistd.tap',
        'originalname': appname,
        'rundir': rundir,
        'logfile': logfile,
        'nodaemon': nodaemon,
        'uid': None,
        'xml': None,
        'chroot': None,
        'no_save': True,
        'quiet': 0,
        'source': None,
        'nothotshot': 0,
        'gid': None,
        'savestats': 0,
        'debug': False,
        'pidfile': pidfile,
        'umask': None
    }

    twistd.checkPID(config['pidfile'])

    config['nodaemon'] = config['nodaemon'] or config['debug']

    oldstdout = sys.stdout
    oldstderr = sys.stderr

    try:
        twistd.startLogging(config['logfile'], config['syslog'],
                            config['prefix'], config['nodaemon'])
        app.initialLog()
    except:
        pass

    try:
        twistd.startApplication(config, application)
        AR = None
    except:
        AR = twistd.UnixApplicationRunner(config)
        AR.application = application
        AR.preApplication()

        AR.logger.start(application)

        AR.postApplication()
        AR.logger.stop()

        return
        #AR.startApplication(application)

    app.runReactorWithLogging(config, oldstdout, oldstderr)

    twistd.removePID(config['pidfile'])

    app.reportProfile(config['report-profile'],
                      service.IProcess(application).processName)
    log.msg("Server Shut Down.")
Beispiel #9
0
def startTwisted(application,
                 startDir='./',
                 nodaemon=0,
                 logfile=None,
                 rundir='.',
                 appname='enamel',
                 pidfile='/var/run/enamel.pid'):
    """ A freezable twistd bootstrap layer """
    config = {
        'profile': None,
        'reactor': None,
        'encrypted': 0,
        'syslog': None,
        'prefix': appname,
        'report-profile': None,
        'euid': 0,
        'file': 'twistd.tap',
        'originalname': appname,
        'rundir': rundir,
        'logfile': logfile,
        'nodaemon': nodaemon,
        'uid': None,
        'xml': None,
        'chroot': None,
        'no_save': True,
        'quiet': 0,
        'source': None,
        'nothotshot': 0,
        'gid': None,
        'savestats': 0,
        'debug': False,
        'pidfile': pidfile,
        'umask': None,
    }

    #application = compat.convert(application)

    twistd.checkPID(config['pidfile'])
    #app.installReactor(config['reactor'])

    config['nodaemon'] = config['nodaemon'] or config['debug']

    oldstdout = sys.stdout
    oldstderr = sys.stderr
    try:
        twistd.startLogging(config['logfile'], config['syslog'],
                            config['prefix'], config['nodaemon'])
        passDeprecate = False
    except AttributeError:
        passDeprecate = True
        if config['nodaemon']:
            config['logfile'] = "-"

    #if not passDeprecate:
    #app.initialLog()

    try:
        twistd.startApplication(config, application)
        print "twisted 2.5"
    except AttributeError:
        print "wt?"
        # Use hotshot in Twisted 8.x
        config['profiler'] = 'hotshot'
        AR = twistd.UnixApplicationRunner(config)
        AR.startApplication(application)
        AR.logger.start(application)

    app.runReactorWithLogging(config, oldstdout, oldstderr)

    try:
        twistd.removePID(config['pidfile'])
    except AttributeError:
        AR.removePID(config['pidfile'])

    if not passDeprecate:
        app.reportProfile(config['report-profile'],
                          service.IProcess(application).processName)
    log.msg("Server Shut Down.")
Beispiel #10
0
    def run(port, subnets):
        ## Create the config file
        if secure:
            if not os.path.exists(private_pem) or not os.path.exists(
                    public_pem):
                print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()."
                print "Now running notebook.setup()"
                notebook_setup()
            if not os.path.exists(private_pem) or not os.path.exists(
                    public_pem):
                print "Failed to setup notebook.  Please try notebook.setup() again manually."
            strport = '%s:%s:interface=%s:privateKey=%s:certKey=%s' % (
                protocol, port, interface, private_pem, public_pem)
        else:
            strport = 'tcp:%s:interface=%s' % (port, interface)

        notebook_opts = '"%s",interface="%s",port=%s,secure=%s' % (
            os.path.abspath(directory), interface, port, secure)

        if open_viewer:
            start_path = "'/?startup_token=%s' % startup_token"
            if interface:
                hostname = interface
            else:
                hostname = 'localhost'
            open_page = "from sagenb.misc.misc import open_page; open_page('%s', %s, %s, %s)" % (
                hostname, port, secure, start_path)
        else:
            open_page = ''

        config = open(conf, 'w')

        if subnets is None:
            factory = "factory = channel.HTTPFactory(site)"
        else:
            if not isinstance(subnets, (list, tuple)):
                subnets = [subnets]
            factory = """
# See http://stackoverflow.com/questions/1273297/python-twisted-restricting-access-by-ip-address
from sagenb.misc.ipaddr import IPNetwork
subnets = eval(r"%s")
if not any(s.startswith('127') for s in subnets):
    subnets.insert(0, '127.0.0.0/8')
subnets = [IPNetwork(x) for x in subnets]
class RestrictedIPFactory(channel.HTTPFactory):
    def buildProtocol(self, addr):
        a = str(addr.host)
        for X in subnets:
            if a in X:
                return channel.HTTPFactory.buildProtocol(self, addr)
        print 'Ignoring all requests from IP address '+str(addr.host)
        
factory = RestrictedIPFactory(site)
""" % tuple([subnets])

        config.write(
            FLASK_NOTEBOOK_CONFIG % {
                'notebook_opts': notebook_opts,
                'sagetex_path': sagetex_path,
                'do_not_require_login': not require_login,
                'dir': os.path.abspath(directory),
                'cwd': cwd,
                'factory': factory,
                'strport': strport,
                'open_page': open_page
            })

        config.close()

        pidfile = os.path.join(directory, 'twistd.pid')
        cmd = 'twistd --pidfile="%s" -ny "%s"' % (
            pidfile, os.path.join(directory, 'twistedconf.tac'))

        # Check if a Twistd PID exists in the given directory
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(pidfile)
            except SystemExit as e:
                pid = int(open(pidfile).read())
                if str(e).startswith('Another twistd server is running,'):
                    sys.exit("""\
Another Sage Notebook server is running, PID %d.

Please either stop the old server or run the new server in a different directory.
""" % pid)
        ## Start up twisted
        if not quiet:
            print_open_msg('localhost' if not interface else interface,
                           port,
                           secure=secure)
        if secure and not quiet:
            print "There is an admin account.  If you do not remember the password,"
            print "quit the notebook and type notebook(reset=True)."

        if fork:
            import pexpect
            return pexpect.spawn(cmd)
        else:
            e = os.system(cmd)

        os.chdir(cwd)
        if e == 256:
            raise socket.error

        return True
Beispiel #11
0
    def run(port):
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.
        pidfile = os.path.join(directory, 'twistd.pid')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(pidfile)
            except SystemExit as e:
                pid = int(open(pidfile).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid
                    old_interface, old_port, old_secure = get_old_settings(
                        conf)
                    if open_viewer and old_port:
                        old_interface = old_interface or 'localhost'

                        print 'Opening web browser at http%s://%s:%s/ ...' % (
                            's' if old_secure else '', old_interface, old_port)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, '/')
                        return
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return

        ## Create the config file
        if secure:
            if (not os.path.exists(private_pem)
                    or not os.path.exists(public_pem)):
                print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()."
                print "Now running notebook.setup()"
                notebook_setup()
            if (not os.path.exists(private_pem)
                    or not os.path.exists(public_pem)):
                print "Failed to setup notebook.  Please try notebook.setup() again manually."
            strport = '%s:%s:interface=%s:privateKey=%s:certKey=%s' % (
                protocol, port, interface, private_pem, public_pem)
        else:
            strport = 'tcp:%s:interface=%s' % (port, interface)

        notebook_opts = '"%s",interface="%s",port=%s,secure=%s' % (
            os.path.abspath(directory), interface, port, secure)

        if open_viewer:
            start_path = "'/?startup_token=%s' % startup_token"
            if interface:
                hostname = interface
            else:
                hostname = 'localhost'
            open_page = "from sagenb.misc.misc import open_page; open_page('%s', %s, %s, %s)" % (
                hostname, port, secure, start_path)
        else:
            open_page = ''

        config = open(conf, 'w')

        config.write(
            FLASK_NOTEBOOK_CONFIG % {
                'notebook_opts': notebook_opts,
                'sagetex_path': sagetex_path,
                'do_not_require_login': not require_login,
                'dir': os.path.abspath(directory),
                'cwd': cwd,
                'strport': strport,
                'open_page': open_page
            })

        config.close()

        ## Start up twisted
        cmd = 'twistd --pidfile="%s" -ny "%s"' % (pidfile, conf)
        if not quiet:
            print_open_msg('localhost' if not interface else interface,
                           port,
                           secure=secure)
        if secure and not quiet:
            print "There is an admin account.  If you do not remember the password,"
            print "quit the notebook and type notebook(reset=True)."

        if fork:
            import pexpect
            return pexpect.spawn(cmd)
        else:
            e = os.system(cmd)

        os.chdir(cwd)
        if e == 256:
            raise socket.error

        return True