Beispiel #1
0
def __initConfig():
    from SkunkWeb import Configuration
    Configuration.mergeDefaults(
        DocumentTimeout=30,
        PostResponseTimeout=20,
        #                                job=None)
    )
def __initConfig():
    from AE import cfg
    from SkunkWeb import Configuration
    # set our defaults from AE defaults
    Configuration.mergeDefaults(
        documentRoot="%s/docroot" % Configuration.SkunkRoot,
        compileCacheRoot="%s/cache" % Configuration.SkunkRoot,
        componentCacheRoot="%s/cache" % Configuration.SkunkRoot,
        failoverComponentCacheRoot="%s/failoverCache" %
        Configuration.SkunkRoot,
        mimeTypesFile="%s/etc/mime.types" % Configuration.SkunkRoot,
        componentCommentLevel=0,
    )
    dd = {}
    for k, v in cfg.Configuration._d.items():
        if k not in [
                'documentRoot', 'compileCacheRoot', 'componentCacheRoot',
                'failoverComponentCacheRoot', 'mimeTypesFile',
                'componentCommentLevel'
        ]:
            dd[k] = v
    Configuration.mergeDefaults(dd)

    # set AE's config object to ours
    cfg.Configuration = Configuration
    __checkScopes(Configuration.matchers)
def __initConfig():
    import SkunkWeb.Configuration as C
    import os
    C.mergeDefaults(
        webdavDB=os.join(C.SkunkRoot, 'var/run/WEBDAVdb'),
        webdavFS=fs.WebdavFS(),
        )
Beispiel #4
0
def doUserDirPre(connection, sessionDict):
    """
    hook for web.protocol.PreHandleConnection
    """
    
    if not Configuration.userDir:
        return
    if connection.uri[:2] != '/~':
        return
    else:
        DEBUG(USERDIR, 'is userdir!')
        uri = connection.uri[2:]
        slashind = uri.find('/')
        if slashind == -1: slashind = len(uri)
        uname = uri[:slashind]
        rest_of_path = uri[slashind:]
        DEBUG(USERDIR, 'new uri is %s' % rest_of_path)
        DEBUG(USERDIR, 'user is %s' % uname)
        try:
            info = pwd.getpwnam(uname)
        except KeyError:
            return #allow it to pass through

        newdocroot = info[5] + '/' + Configuration.userDirPath
        sessionDict['UserDir'] = 1
        sessionDict['UserDirDocRoot'] = Configuration.documentRoot
        sessionDict['UserDirCC'] = Configuration.compileCacheRoot

        cacheroot="%s/~%s/" % (Configuration.compileCacheRoot, uname)
        connection.uri = rest_of_path
        # this will clean itself up when the Configuration is trimmed
        Configuration.push({'documentRoot' : newdocroot,
                            'compileCacheRoot' : cacheroot,
                            'componentCacheRoot' : cacheroot})
        return
Beispiel #5
0
def _processRequest(requestData, sessionDict):
    """
    request handling functioning for requestHandler's
    HandleRequest hook.
    """
    response = None

    DEBUG(WEB, 'creating Connection')
    DEBUG(WEB, 'requestData is %s' % str(requestData))
    connection = HTTPConnection(requestData)

    sessionDict[constants.CONNECTION] = connection
    sessionDict[constants.HOST] = connection.host
    sessionDict[constants.LOCATION] = connection.uri
    try:
        DEBUG(WEB, 'executing HaveConnection hook')
        HaveConnection(Configuration.job, connection, sessionDict)
        DEBUG(WEB, 'survived HaveConnection hook')

        # overlay of config information
        Configuration.trim()
        Configuration.scope(sessionDict)
        #Configuration.saveMash()

        DEBUG(WEB, 'executing PreHandleConnection hook')
        PreHandleConnection(Configuration.job, connection, sessionDict)

    except PreemptiveResponse, pr:
        DEBUG(WEB, 'got preemptive response')
        response = pr.responseData
def doUserDirPre(connection, sessionDict):
    """
    hook for web.protocol.PreHandleConnection
    """
    
    if not Configuration.userDir:
        return
    if connection.uri[:2] != '/~':
        return
    else:
        DEBUG(USERDIR, 'is userdir!')
        uri = connection.uri[2:]
        slashind = uri.find('/')
        if slashind == -1: slashind = len(uri)
        uname = uri[:slashind]
        rest_of_path = uri[slashind:]
        DEBUG(USERDIR, 'new uri is %s' % rest_of_path)
        DEBUG(USERDIR, 'user is %s' % uname)
        try:
            info = pwd.getpwnam(uname)
        except KeyError:
            return #allow it to pass through

        newdocroot = info[5] + '/' + Configuration.userDirPath
        sessionDict['UserDir'] = 1
        sessionDict['UserDirDocRoot'] = Configuration.documentRoot
        sessionDict['UserDirCC'] = Configuration.compileCacheRoot

        cacheroot="%s/~%s/" % (Configuration.compileCacheRoot, uname)
        connection.uri = rest_of_path
        # this will clean itself up when the Configuration is trimmed
        Configuration.push({'documentRoot' : newdocroot,
                            'compileCacheRoot' : cacheroot,
                            'componentCacheRoot' : cacheroot})
        return
def __initConfig():
    import SkunkWeb.Configuration as C
    import os
    C.mergeDefaults(
        webdavDB=os.join(C.SkunkRoot, 'var/run/WEBDAVdb'),
        webdavFS=fs.WebdavFS(),
    )
def _processRequest(requestData, sessionDict):
    """
    request handling functioning for requestHandler's
    HandleRequest hook.
    """
    response=None
    
    # DEBUG(WEB, 'creating Connection')
    # DEBUG(WEB, 'requestData is %s' % str(requestData))
    connection=HTTPConnection(requestData)

    sessionDict[constants.CONNECTION]=connection
    sessionDict[constants.HOST]=connection.host
    sessionDict[constants.LOCATION]=connection.uri
    sessionDict[constants.SERVER_PORT]=int(connection.env['SERVER_PORT'])
    try:
        # DEBUG(WEB, 'executing HaveConnection hook')
        HaveConnection(Configuration.job, connection, sessionDict)
        # DEBUG(WEB, 'survived HaveConnection hook')

        # overlay of config information
        Configuration.trim()
        Configuration.scope(sessionDict)
        #Configuration.saveMash()

        # DEBUG(WEB, 'executing PreHandleConnection hook')
        PreHandleConnection(Configuration.job, connection, sessionDict)
                
    except PreemptiveResponse, pr:
        # DEBUG(WEB, 'got preemptive response')
        response=pr.responseData
Beispiel #9
0
def __initConfig():
    from AE import cfg
    from SkunkWeb import Configuration, confvars
    # set our defaults from AE defaults
    Configuration.mergeDefaults(
        documentRoot=confvars.DEFAULT_DOCROOT,
        compileCacheRoot=confvars.DEFAULT_CACHE,
        componentCacheRoot=confvars.DEFAULT_CACHE,
        failoverComponentCacheRoot="%s/failoverCache" %
        Configuration.SkunkRoot,
        mimeTypesFile=confvars.DEFAULT_MIME_TYPES_FILE_NAME,
        componentCommentLevel=0,
    )
    dd = {}
    for k, v in cfg.Configuration._d.items():
        if k not in [
                'documentRoot', 'compileCacheRoot', 'componentCacheRoot',
                'failoverComponentCacheRoot', 'mimeTypesFile',
                'componentCommentLevel'
        ]:
            dd[k] = v
    Configuration.mergeDefaults(dd)

    # set AE's config object to ours
    cfg.Configuration = Configuration
    __checkScopes(Configuration.scopeMatchers())
def __initConfig():
    from AE import cfg
    from SkunkWeb import Configuration, confvars
    # set our defaults from AE defaults
    Configuration.mergeDefaults(
        documentRoot = confvars.DEFAULT_DOCROOT,
        compileCacheRoot = confvars.DEFAULT_CACHE, 
        componentCacheRoot = confvars.DEFAULT_CACHE,
        failoverComponentCacheRoot = "%s/failoverCache" % Configuration.SkunkRoot,
        mimeTypesFile = confvars.DEFAULT_MIME_TYPES_FILE_NAME,
        componentCommentLevel = 0,
        )
    dd = {}
    for k, v in cfg.Configuration._d.items():
        if k not in ['documentRoot',
                     'compileCacheRoot',
                     'componentCacheRoot',
                     'failoverComponentCacheRoot',
                     'mimeTypesFile',
                     'componentCommentLevel']:
            dd[k]=v
    Configuration.mergeDefaults(dd)
            
    # set AE's config object to ours
    cfg.Configuration = Configuration
    __checkScopes(Configuration.scopeMatchers())
Beispiel #11
0
def _beginSession(sock, sessionDict):
    # capture the ip & port (or path, for a unix socket)
    # on which the request came, for scoping of configuration
    # data on their basis
    ip, port, unixpath = None, None, None
    try:
        addr = sock.getsockname()
        if type(addr) == types.TupleType:
            ip, port = addr
        else:
            unixpath = addr
    except:
        ERROR("failed to read addr off socket!")
        logException()
        raise

    if ip and port:
        sessionDict[constants.IP] = ip
        sessionDict[constants.PORT] = port
    else:
        sessionDict[constants.UNIXPATH] = unixpath

    # get configuration data for the job
    Configuration.scope(sessionDict)

    # job must be defined, or else die here
    if Configuration.job == None:
        message="No job specified for service on %s:%d, "\
                 "request cannot be processed!" % (ip, port)
        ERROR(message)
        raise SkunkCriticalError, message

    BeginSession(Configuration.job, sock, sessionDict)
def _beginSession(sock, sessionDict):
    # capture the ip & port (or path, for a unix socket)
    # on which the request came, for scoping of configuration
    # data on their basis
    ip, port, unixpath=None, None, None
    try:      
        addr=sock.getsockname()
        if type(addr)==types.TupleType:
            ip, port=addr
        else:
            unixpath=addr
    except:
        ERROR("failed to read addr off socket!")
        logException()
        raise

    if ip and port:
        sessionDict[constants.IP]=ip
        sessionDict[constants.PORT]=port
    else:
        sessionDict[constants.UNIXPATH]=unixpath
    
    # get configuration data for the job
    Configuration.scope(sessionDict)
    
    # job must be defined, or else die here
    if Configuration.job==None:
        message="No job specified for service on %s:%d, "\
                 "request cannot be processed!" % (ip, port)
        ERROR(message)
        raise SkunkCriticalError, message
    
    BeginSession(Configuration.job, sock, sessionDict)
Beispiel #13
0
def __initConfig():
    from SkunkWeb import Configuration
    Configuration.mergeDefaults(
        # session timeout, in seconds.
        SessionTimeout=30 * 60,

        # the key under which the session is kept
        SessionIDKey='sessionID',

        # the host, user, password, and database (for MySQLSessionStoreImpl)
        SessionHandler_MySQLHost='localhost',
        SessionHandler_MySQLUser='******',
        SessionHandler_MySQLPass='******',
        SessionHandler_MySQLDB='sessionStore',

        # table, id column, session value column, and timestamp column
        # (for MySQLSessionStoreImpl)
        SessionHandler_MySQLTable='Sessions',
        SessionHandler_MySQLIDColumn='id',
        SessionHandler_MySQLPickleColumn='pickle',
        SessionHandler_MySQLTimestampColumn='accessTime',

        # the same, for PostgreSQLSessionStoreImpl
        SessionHandler_PGHost='localhost',
        SessionHandler_PGUser='******',
        SessionHandler_PGPass='******',
        SessionHandler_PGDB='sessionStore',
        SessionHandler_PGTable='Sessions',
        SessionHandler_PGIDColumn='id',
        SessionHandler_PGPickleColumn='pickle',
        SessionHandler_PGTimestampColumn='accesstime',

        # directory where pickle files are stored (for FSSessionStore)
        SessionHandler_FSSessionDir=os.path.join(Configuration.SkunkRoot,
                                                 'var/run/skunksessions'),

        # reap interval (in seconds).  A negative value, or zero,
        # will turn off reaping.  it would be reasonable for at most
        # one server to reap any given session store.
        SessionReapInterval=300,
        SessionStore=None)
def __initConfig():
    from SkunkWeb import Configuration
    Configuration.mergeDefaults(
        # session timeout, in seconds. 
        SessionTimeout = 30*60,
        
        # the key under which the session is kept
        SessionIDKey='sessionID',
        
        # the host, user, password, and database (for MySQLSessionStoreImpl)
        SessionHandler_MySQLHost='localhost',
        SessionHandler_MySQLUser='******',
        SessionHandler_MySQLPass='******',
        SessionHandler_MySQLDB='sessionStore',
        
        # table, id column, session value column, and timestamp column
        # (for MySQLSessionStoreImpl)
        SessionHandler_MySQLTable='Sessions',
        SessionHandler_MySQLIDColumn='id',
        SessionHandler_MySQLPickleColumn='pickle',
        SessionHandler_MySQLTimestampColumn='accessTime',

        # the same, for PostgreSQLSessionStoreImpl
        SessionHandler_PGHost='localhost',
        SessionHandler_PGUser='******',
        SessionHandler_PGPass='******',
        SessionHandler_PGDB='sessionStore',
        SessionHandler_PGTable='Sessions',
        SessionHandler_PGIDColumn='id',
        SessionHandler_PGPickleColumn='pickle',
        SessionHandler_PGTimestampColumn='accesstime',
        
        # directory where pickle files are stored (for FSSessionStore)
        SessionHandler_FSSessionDir=os.path.join(Configuration.SkunkRoot, 'var/run/skunksessions'),
        
        # reap interval (in seconds).  A negative value, or zero,
        # will turn off reaping.  it would be reasonable for at most
        # one server to reap any given session store.
        SessionReapInterval=300,
        SessionStore=None
        )
def _cleanupConfig(requestData, sessionDict):
    """
    function for requestHandler's CleanupRequest hook
    """
    if sessionDict.has_key(constants.HOST):
        del sessionDict[constants.HOST]
    if sessionDict.has_key(constants.LOCATION):
        del sessionDict[constants.LOCATION]
    Configuration.trim()

    if sessionDict.has_key(constants.IP):
        Configuration.scope({constants.IP : sessionDict[constants.IP],
                             constants.PORT: sessionDict[constants.PORT]})
    elif sessionDict.has_key(constants.UNIXPATH):
        Configuration.scope({constants.UNIXPATH : sessionDict[constants.UNIXPATH]})
def _cleanupConfig(requestData, sessionDict):
    """
    function for requestHandler's CleanupRequest hook
    """
    if sessionDict.has_key(constants.HOST):
        del sessionDict[constants.HOST]
    if sessionDict.has_key(constants.LOCATION):
        del sessionDict[constants.LOCATION]
    if sessionDict.has_key(constants.SERVER_PORT):
        del sessionDict[constants.SERVER_PORT]
    Configuration.trim()

    if sessionDict.has_key(constants.IP):
        Configuration.scope({constants.IP : sessionDict[constants.IP],
                             constants.PORT: sessionDict[constants.PORT]})
    elif sessionDict.has_key(constants.UNIXPATH):
        Configuration.scope({constants.UNIXPATH : sessionDict[constants.UNIXPATH]})
Beispiel #17
0
            self.lbuf = ''


def redirectStdOutErr():
    if not sys.stderr.isatty():
        sys.stderr = Redirector(Logger.ERROR)
    if not sys.stdout.isatty():
        sys.stdout = Redirector(Logger.LOG)


########################################################################

Configuration.mergeDefaults(accessLog=confvars.DEFAULT_ACCESS_LOG,
                            errorLog=confvars.DEFAULT_ERROR_LOG,
                            regularLog=confvars.DEFAULT_REGULAR_LOG,
                            debugLog=confvars.DEFAULT_DEBUG_LOG,
                            stampEveryLine=1,
                            logDateFormat='%a, %d %b %Y %H:%M:%S GMT',
                            initialDebugServices=[])

Logger._logStamp = "[%d]initializing... %%s -- " % os.getpid()

# enable the logger to print the service name from the debug flag passed
# to debug statements.
Logger.getSourceFromKind = ServiceRegistry.getSourceFromKind
Logger.config = Configuration

Hooks.ServerStart.append(Logger.initLogStamp)
Hooks.ServerStart.append(redirectStdOutErr)
Hooks.ChildStart.append(Logger.initLogStamp)
#  
#  Copyright (C) 2001 Andrew T. Csillag <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#   
# $Id: userdir.py,v 1.7 2003/05/01 20:45:53 drew_csillag Exp $
########################################################################

import pwd
from SkunkWeb import Configuration

Configuration.mergeDefaults(userDir = 1,
                            userDirPath = 'public_html')

from SkunkWeb import ServiceRegistry
ServiceRegistry.registerService('userdir')
from SkunkWeb.LogObj import DEBUG
from SkunkWeb.ServiceRegistry import USERDIR    

def doUserDirPre(connection, sessionDict):
    """
    hook for web.protocol.PreHandleConnection
    """
    
    if not Configuration.userDir:
        return
    if connection.uri[:2] != '/~':
        return
    else:
#  Copyright (C) 2001 Andrew T. Csillag <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
########################################################################

from SkunkWeb import Configuration
import MySQL
from SkunkExcept import SkunkStandardError
from requestHandler.requestHandler import CleanupRequest

Configuration.mergeDefaults(
    MySQLConnectParams = {},
    MySQLRollback=0,
    MySQLTestFunc=None
    )

# add test function (used by MySQL connection cache to test
# connections before handing them out)
MySQL.connection_test=Configuration.MySQLTestFunc

for u, p in Configuration.MySQLConnectParams.items():
    MySQL.initUser(u, p)

# optional rollback
def rollback(*args):
    for v in MySQL._connections.values():
        try:
            v.rollback()
def SIGALRMHandler(*args):
    Configuration.trim()
    ERROR('Throwing timeout exception')
    signal.alarm(1) # in case they catch this exception
    raise DocumentTimeout, "timeout reached"
will affect all products, or by adding the product-name to the
Configuration.productPaths mapping.

This service will also contain a utility for creating products, creating
the MANIFEST file, byte-compiling the python modules, and creating the
archive file.
"""

import SkunkWeb.Configuration as Cfg
from loader import *
from manifest import *
import os

Cfg.mergeDefaults(
    productDirectory='products',
    products='*',
    defaultProductPath='products',
    productPaths={},
)

proddir = loader.product_directory()
if not os.path.isdir(proddir):
    try:
        os.makedirs(proddir)
    except:
        ERROR(("product service needs a product directory,"
               "currently configured as %s") % proddir)
        raise
del proddir

for p in loader.listProducts():
    p.load()
_config_attrs=tuple([("usertrackingCookie%s" % \
                      x.replace('-', '_').capitalize(), x) \
                     for x in _cookie_attrs])

Configuration.mergeDefaults(
    # whether usertracking is on
    usertrackingOn=0,
    # whether Configuration.usertrackingCookieExpires is an
    # absolute timestamp, or an interval to be added to the
    # current time (the latter is the default)
    usertrackingExpiresAbsolute=0,
    # function to generate unique ids; should take one argument,
    # the CONNECTION.  If None, a uuid will be generated.
    usertrackingGenUIDFunc=None,
    # function to verify a usertracking cookie;
    # by default, None
    usertrackingVerifyCookieFunc=None,
    # name of the cookie
    usertrackingCookieName="SKUNKTREK_ID",
    # values for cookie parameters
    usertrackingCookiePath=None,
    usertrackingCookieExpires=None,
    usertrackingCookieDomain=None,
    usertrackingCookieComment=None,
    usertrackingCookieVersion=None,
    usertrackingCookieMax_age=None)

def _verify_cookie(conn, cookiename):
    if conn.requestCookie.has_key(cookiename):
        v=conn.requestCookie[cookiename]
        f=Configuration.usertrackingVerifyCookieFunc
def _endSession(sessionDict):
    try:
        EndSession(Configuration.job, sessionDict)
    except:
        logException()
    Configuration.trim()
Beispiel #24
0
########################################################################
#  Copyright (C) 2004 Andrew T. Csillag <*****@*****.**>,
#                     Jacob Smullyan <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
########################################################################

from SkunkWeb import Configuration
import PsycopgCache

Configuration.mergeDefaults(PsycopgConnectParams = {})

for u, p in Configuration.PsycopgConnectParams.items():
    PsycopgCache.initUser (u, p)

def rollback(*args):
    for v in PsycopgCache._connections.values():
        v.rollback()

from requestHandler.requestHandler import CleanupRequest
CleanupRequest.addFunction(rollback)
Beispiel #25
0
    def marshalException(self, exc_text, sessionDict):
        '''
        should return response data appropriate for the current exception.
        '''
        res=RequestFailed(Configuration.job,
                          exc_text,
                          sessionDict)
        if res:
            return self._marshalData(res)
        else:
            return self._marshalData(exc_text)

    def _marshalData(self, data):
        return data

Configuration.mergeDefaults(SCGIListenPorts=['TCP:localhost:9999'])
if Configuration.SCGIListenPorts:
    requestHandler.requestHandler.addRequestHandler(
        SCGIProtocol(), Configuration.SCGIListenPorts)

########################################################################
# $Log: scgi.py,v $
# Revision 1.3  2003/05/01 20:45:53  drew_csillag
# Changed license text
#
# Revision 1.2  2002/06/18 20:09:38  drew_csillag
# fixed typo that caused problems on POSTs
#
# Revision 1.1  2002/06/17 19:29:52  drew_csillag
# added
#
import AE.Component
from web.protocol import Redirect
from SkunkWeb.LogObj import DEBUG
from SkunkWeb.ServiceRegistry import TEMPLATING
import SkunkWeb.Configuration as Config

# for img tag, try to import PIL (to get default image width and height)
try:
    import PIL.Image as Image
    import AE.Cache as Cache
    _havePIL=1
    import pil_preload
except:
    _havePIL=0

Config.mergeDefaults(tagsGenerateXHTML=1,
                     autosizeImages=1)
                     

def _genUrl ( path, query = {}, need_full = 0, noescape=None ):
    """
    Generate the URL given a URI. If need_full is 1, the generated URL 
    will contain the server part.
    """

    if noescape is None:
	path = urllib.quote(path)

    if query:
        path = path + skunklib.urlencode ( query )

    if need_full:
Beispiel #27
0
def _endSession(sessionDict):
    try:
        EndSession(Configuration.job, sessionDict)
    except:
        logException()
    Configuration.trim()
def Scope(*scopeMatchers):
    from SkunkWeb import Configuration
    Configuration.addScopeMatchers(*scopeMatchers)
Beispiel #29
0
def SIGALRMHandler(*args):
    Configuration.trim()
    ERROR('Throwing timeout exception')
    signal.alarm(1)  # in case they catch this exception
    raise DocumentTimeout, "timeout reached"
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
# $Id: __init__.py,v 1.5 2004/03/01 16:27:04 smulloni Exp $
# Time-stamp: <01/05/04 13:27:45 smulloni>
########################################################################

import SkunkWeb.ServiceRegistry
SkunkWeb.ServiceRegistry.registerService("httpd")

from SkunkWeb import Configuration, Hooks
from socket import getfqdn as _getfqdn
Configuration.mergeDefaults(lookupHTTPRemoteHost=0,
                            HTTPKeepAliveTimeout=0,
                            HTTPListenPorts=['TCP::8080'],
                            ServerName=_getfqdn())


class _hooker:
    def __init__(self, handler, adder, ports):
        self.adder = adder
        self.handler = handler
        self.ports = ports

    def __call__(self, *a, **kw):
        self.adder(self.handler, self.ports)


if Configuration.HTTPListenPorts:
    import requestHandler.requestHandler as rh
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#   
# $Id$
# Time-stamp: <01/05/04 13:27:45 smulloni>
########################################################################

import SkunkWeb.ServiceRegistry
SkunkWeb.ServiceRegistry.registerService("httpd")


from SkunkWeb import Configuration, Hooks
from socket import getfqdn as _getfqdn
Configuration.mergeDefaults(lookupHTTPRemoteHost=0,
                            HTTPKeepAliveTimeout=0,
                            HTTPListenPorts=['TCP::8080'],
                            ServerName=_getfqdn())

class _hooker:
    def __init__(self, handler, adder, ports):
        self.adder=adder
        self.handler=handler
        self.ports=ports

    def __call__(self, *a, **kw):
        self.adder(self.handler, self.ports)
    
if Configuration.HTTPListenPorts:
    import requestHandler.requestHandler as rh
    import protocol as prot
    httpProt=prot.HTTPProtocol()
from SkunkWeb import ServiceRegistry, Configuration, constants
ServiceRegistry.registerService('rewrite')
from SkunkWeb.LogObj import DEBUG, logException
from SkunkWeb.ServiceRegistry import REWRITE
import re
import sys
from requestHandler.protocol import PreemptiveResponse
from skunklib import normpath


def _fixPath(root, path):
    return normpath('%s/%s' % (root, path))


Configuration.mergeDefaults(rewriteBeforeScope=1,
                            rewriteRules=[],
                            rewriteApplyAll=1,
                            rewriteMatchToArgs=1)

_sre_pattern_type = type(re.compile('foo'))

_patdict = {}


def _getcompiled(regex):
    if type(regex) == _sre_pattern_type:
        _patdict.setdefault(regex.pattern, regex)
        return regex
    if not _patdict.has_key(regex):
        pat = re.compile(regex)
        _patdict[regex] = pat
        return pat
Beispiel #33
0
import AE.Error
import AE.Executables
from SkunkWeb import Configuration
import stat
import sys
from SkunkWeb.LogObj import ACCESS, ERROR, DEBUG
from web.protocol import Redirect
from SkunkWeb.ServiceRegistry import TEMPLATING
import vfs
from skunk.date.format import HTTPDate

Configuration.mergeDefaults(
    indexDocuments=['index.html'],
    hideMimeTypes=[
        "text/x-stml-component", "text/x-stml-python-component",
        "text/x-stml-data-component", "text/x-stml-python-data-component",
        "text/x-stml-include", "text/x-stml-python-include"
    ],
    interpretMimeTypes=["text/html", "application/x-python"],
    defaultIndexHtml=None,
    mimeHandlers={})


def _handleException(connObj):
    text = AE.Error.logException()
    ERROR(text)
    import cStringIO
    connObj.setStatus(500)
    if (hasattr(Configuration, 'errorTemplate')
            and Configuration.errorTemplate):
        connObj.write(
            AE.Component.callComponent(Configuration.errorTemplate, {
Beispiel #34
0
import SkunkWeb.Configuration as C
C.mergeDefaults(MvcOn=False)
def __initConfig():
    from SkunkWeb import Configuration
    Configuration.mergeDefaults(DocumentTimeout=30,
                                PostResponseTimeout=20,
                                job=None)
Beispiel #36
0
# Time-stamp: <02/10/30 09:27:03 smulloni>

# default values for Configuration variables go here.
import SkunkWeb.Configuration as C

# whether to disallow "guest" (anonymous) logins
C.mergeDefaults(HoptimeRequireValidUser=0) 

# make certain that the postgresql service is loaded
import postgresql

# initialize the db connection caching mechanism with a connectstring
import hopapi
hopapi.initDB(hopapi.SW_CONNECTSTRING)

# hopapi has a debug method that prints to stderr by default.
# replace it with SkunkWeb's debug method.
import SkunkWeb.ServiceRegistry as _SR
from SkunkWeb.LogObj import DEBUG as _d

def _munge_debug():
    _SR.registerService('hoptime.service', 'HOPTIME')
    HOPTIME=_SR.HOPTIME
    def _debug(message):
        _d(HOPTIME, str(message))
    hopapi.DEBUG=_debug

_munge_debug()
def SIGALRMHandler(*args):
    Configuration.trim()
    raise DocumentTimeout, "timeout reached"
def __initConnections():
    from protocol import SkunkWebRemoteProtocol
    Configuration.mergeDefaults(RemoteListenPorts=['TCP:localhost:9887'])
    if Configuration.RemoteListenPorts:
        requestHandler.requestHandler.addRequestHandler(
            SkunkWebRemoteProtocol(), Configuration.RemoteListenPorts)
Beispiel #39
0
import os
import datetime
import computils
from AE.Component import DT_INCLUDE
import SkunkWeb.Configuration as C

C.mergeDefaults(skinDir='/comp/skins',
                defaultSkin='default')

import threading
_local=threading.local()
_local.SLOTSTACK=[]

def getCurrentSlot():
    if _local.SLOTSTACK:
        return _local.SLOTSTACK[-1]

def push_slot(slot):
    _local.SLOTSTACK.append(slot)

def pop_slot():
    if _local.SLOTSTACK:
        _local.SLOTSTACK.pop()

class Slot(object):
    def __init__(self, name):
        self.name=name

class ComponentSlot(Slot):
    def __init__(self, name, compname, comptype=None, cache=computils.NO, **kw):
        Slot.__init__(self, name)
Beispiel #40
0
    def marshalException(self, exc_text, sessionDict):
        '''
        should return response data appropriate for the current exception.
        '''
        res = RequestFailed(Configuration.job, exc_text, sessionDict)
        if res:
            return self._marshalData(res)
        else:
            return self._marshalData(exc_text)

    def _marshalData(self, data):
        return data


Configuration.mergeDefaults(SCGIListenPorts=['TCP:localhost:9999'])
if Configuration.SCGIListenPorts:
    requestHandler.requestHandler.addRequestHandler(
        SCGIProtocol(), Configuration.SCGIListenPorts)

########################################################################
# $Log: scgi.py,v $
# Revision 1.3  2003/05/01 20:45:53  drew_csillag
# Changed license text
#
# Revision 1.2  2002/06/18 20:09:38  drew_csillag
# fixed typo that caused problems on POSTs
#
# Revision 1.1  2002/06/17 19:29:52  drew_csillag
# added
#
def Scope(*scopeMatchers):
    from SkunkWeb import Configuration
    Configuration.addScopeMatchers(*scopeMatchers)
class AddressValidationError( MailError ):
    """
    Error if addresses are most likely not deliverable
    """
    def __init__(self, message, bad, good=None):
        MailError.__init__(self, message)
        self.bad = bad
        self.good = good or []
	self.message = message


# Init some variables
Configuration.mergeDefaults(
    MailMethod = 'sendmail',
    MailHost = 'localhost',
    SendmailCommand = '/usr/lib/sendmail',
    FromAddress = "root@localhost",
    QmailInject = "/var/qmail/bin/qmail-inject",
    AddressCheckLevel = 1
    )
# AddressCheckLevel
# 0 - no checks are done
# 1 - simple format check
# 2 - full syntax check (not implemented yet)

valid_charsets = ['iso-8859-1', 'us-ascii']

# shows the mail method: 'sendmail' (default) or 'relay' or 'qmail'
_method = Configuration.MailMethod

# mailhost for relaying SMTP server (default localhost)
_mailhost = Configuration.MailHost
for the component cache.

To turn this on, define memcacheCacheBackend to be a list of ip
address of memcache servers.  If it is None, this will fall back to
the usual skunk cache.

"""
import cPickle

import memcache

import AE.Cache
from Logger import logException, ERROR
import SkunkWeb.Configuration as C

C.mergeDefaults(memcacheCacheBackend=None,
                memcachePathPrefix='component_')

_clients={}
def _get_memcache_client():
    global _clients
    servers=C.memcacheCacheBackend
    if not servers:
        return None
    servers.sort()
    servers=tuple(servers)
    try:
        return _clients[servers]
    except KeyError:
        client=memcache.Client(servers, False)
        _clients[servers]=client
        return client
Beispiel #44
0
# Time-stamp: <01/05/04 17:32:39 smulloni>
########################################################################

from SkunkWeb import Configuration, ServiceRegistry, Hooks
from SkunkWeb.LogObj import DEBUG, DEBUGIT, logException
import os
import select
import sys
import rfc822
import cStringIO

ServiceRegistry.registerService('extcgi')
EXTCGI=ServiceRegistry.EXTCGI

Configuration.mergeDefaults(CGIProgram = None,
                            CGIProgramArgs = (),
                            CGIProgramBase = '')

def _fix(dict): #fixup the environment variables
    nd = {}
    for k,v in dict.items():
        nd[str(k)] = str(v)
    pb = Configuration.CGIProgramBase
    if nd["SCRIPT_NAME"][:len(pb)] == pb:
        remnant = nd["SCRIPT_NAME"][len(pb):]
        if remnant:
            nd["PATH_INFO"] = '/' + remnant
        else:
            nd["PATH_INFO"] = ''
        
        if pb and pb[-1] == '/':
########################################################################
#  Copyright (C) 2001 Andrew T. Csillag <*****@*****.**>
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
########################################################################

from SkunkWeb import Configuration
import MySQL
from SkunkExcept import SkunkStandardError
from requestHandler.requestHandler import CleanupRequest

Configuration.mergeDefaults(MySQLConnectParams={},
                            MySQLRollback=0,
                            MySQLTestFunc=None)

# add test function (used by MySQL connection cache to test
# connections before handing them out)
MySQL.connection_test = Configuration.MySQLTestFunc

for u, p in Configuration.MySQLConnectParams.items():
    MySQL.initUser(u, p)


# optional rollback
def rollback(*args):
    for v in MySQL._connections.values():
        try:
            v.rollback()
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#

from SkunkWeb import Configuration, ServiceRegistry
from SkunkWeb.LogObj import DEBUG
from requestHandler.protocol import PreemptiveResponse
import AE.Cache
import os
import Authenticator
import sys
import base64

Configuration.mergeDefaults(basicAuthName=None, basicAuthFile=None)
ServiceRegistry.registerService("basicauth")
AUTH = ServiceRegistry.BASICAUTH


def getAuthorizationFromHeaders(conn, sessionDict):
    """
    pulls REMOTE_USER, REMOTE_PASSWORD, and AUTH_TYPE out of request headers.
    """
    DEBUG(AUTH, "looking for authorization headers")
    auth = conn.requestHeaders.get(
        'Authorization', conn.requestHeaders.get('Proxy-Authorization'))
    if auth:
        DEBUG(AUTH, "found authorization")
        conn.authType, ai = auth.split()
        ucp = base64.decodestring(ai)
import stat
import sys
from SkunkWeb.LogObj import ACCESS, ERROR, DEBUG
from web.protocol import Redirect
from SkunkWeb.ServiceRegistry import TEMPLATING
import vfs
import Date

Configuration.mergeDefaults(
    indexDocuments = ['index.html'],
    hideMimeTypes = [
        "text/x-stml-component",
        "text/x-stml-python-component",
        "text/x-stml-data-component",
        "text/x-stml-python-data-component",
        ],
    interpretMimeTypes = [
        "text/html",
        "application/x-python"
        ],
    defaultIndexHtml = None,
    mimeHandlers = {}
    )

def _handleException(connObj):
    text = AE.Error.logException()
    ERROR(text)
    import cStringIO
    connObj.setStatus(500)
    if (hasattr(Configuration, 'errorTemplate') and
        Configuration.errorTemplate):
import SkunkWeb.Configuration as Cfg
from SkunkWeb import Context
from web.protocol import RouteConnection
from SkunkWeb.constants import WEB_JOB

# the controller service is required
import controller

# make sure that the context object is installed
import context

from mvc.log import debug

__all__=['url_for', 'redirect_to']

Cfg.mergeDefaults(routes=[])

def _do_redirect(url):
    Context.Connection.redirect(url)

def routing_hook(connection, sessionDict):
    if not Cfg.MvcOn:
        return
    debug("in routing hook")
    # initialize routes request config
    rcfg=request_config()
    rcfg.redirect=_do_redirect
    rcfg.mapper=map=Mapper()
    rcfg.host=connection.host
    if connection.env.get('HTTPS', False):
        rcfg.protocol='HTTPS'
Beispiel #49
0
import AE.Component
from web.protocol import Redirect
from SkunkWeb.LogObj import DEBUG
from SkunkWeb.ServiceRegistry import TEMPLATING
import SkunkWeb.Configuration as Config

# for img tag, try to import PIL (to get default image width and height)
try:
    import PIL.Image as Image
    import AE.Cache as Cache
    _havePIL = 1
    import pil_preload
except:
    _havePIL = 0

Config.mergeDefaults(tagsGenerateXHTML=1, autosizeImages=1)


def _genUrl(path, query={}, need_full=0, noescape=None):
    """
    Generate the URL given a URI. If need_full is 1, the generated URL 
    will contain the server part.
    """

    if noescape is None:
        path = urllib.quote(path)

    if query:
        path = path + skunklib.urlencode(query)

    if need_full:
Beispiel #50
0
class AddressValidationError( MailError ):
    """
    Error if addresses are most likely not deliverable
    """
    def __init__(self, message, bad, good=None):
        MailError.__init__(self, message)
        self.bad = bad
        self.good = good or []
	self.message = message


# Init some variables
Configuration.mergeDefaults(
    MailMethod = 'sendmail',
    MailHost = 'localhost',
    SendmailCommand = '/usr/lib/sendmail',
    FromAddress = "root@localhost",
    QmailInject = "/var/qmail/bin/qmail-inject",
    AddressCheckLevel = 1
    )
# AddressCheckLevel
# 0 - no checks are done
# 1 - simple format check
# 2 - full syntax check (not implemented yet)

valid_charsets = ['iso-8859-1', 'us-ascii']

# shows the mail method: 'sendmail' (default) or 'relay' or 'qmail'
_method = Configuration.MailMethod

# mailhost for relaying SMTP server (default localhost)
_mailhost = Configuration.MailHost
########################################################################
#  Copyright (C) 2002 Andrew T. Csillag <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
########################################################################

from SkunkWeb import Configuration
import PyPgSQLcache

Configuration.mergeDefaults(
    PyPgSQLConnectParams = {},
    )

for u, p in Configuration.PyPgSQLConnectParams.items():
    PyPgSQLcache.initUser ( u, p )

def rollback(*args):
    for v in PyPgSQLcache._connections.values():
        v.rollback()

from requestHandler.requestHandler import CleanupRequest
CleanupRequest.addFunction(rollback)
########################################################################
#  
#  Copyright (C) 2003 Andrew T. Csillag <*****@*****.**>,
#                     Jacob Smullyan <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#   
########################################################################

# contributed by Brian Olsen.

from SkunkWeb import Configuration
import Firebird

Configuration.mergeDefaults(
    FirebirdConnectParams = {},
    )

for u, p in Configuration.FirebirdConnectParams.items():
    Firebird.initUser(u, p)

def rollback(*args):
    for v in Firebird._connections.values():
        v.rollback()

from requestHandler.requestHandler import CleanupRequest
CleanupRequest.addFunction(rollback)
def __initConnections():
    from protocol import SkunkWebRemoteProtocol

    Configuration.mergeDefaults(RemoteListenPorts=["TCP:localhost:9887"])
    if Configuration.RemoteListenPorts:
        requestHandler.requestHandler.addRequestHandler(SkunkWebRemoteProtocol(), Configuration.RemoteListenPorts)
# Time-stamp: <02/10/30 09:27:03 smulloni>
# $Id: service.py,v 1.2 2002/11/01 17:54:17 smulloni Exp $

# default values for Configuration variables go here.
import SkunkWeb.Configuration as C

# whether to disallow "guest" (anonymous) logins
C.mergeDefaults(HoptimeRequireValidUser=0) 

# make certain that the postgresql service is loaded
import postgresql

# initialize the db connection caching mechanism with a connectstring
import hopapi
hopapi.initDB(hopapi.SW_CONNECTSTRING)

# hopapi has a debug method that prints to stderr by default.
# replace it with SkunkWeb's debug method.
import SkunkWeb.ServiceRegistry as _SR
from SkunkWeb.LogObj import DEBUG as _d

def _munge_debug():
    _SR.registerService('hoptime.service', 'HOPTIME')
    HOPTIME=_SR.HOPTIME
    def _debug(message):
        _d(HOPTIME, str(message))
    hopapi.DEBUG=_debug

_munge_debug()
Beispiel #55
0
# Time-stamp: <03/04/15 00:23:55 smulloni>
# $Id: spreadcache_service.py,v 1.2 2003/05/01 20:45:53 drew_csillag Exp $

########################################################################
#  Copyright (C) 2003 Jacob Smullyan <*****@*****.**>
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
########################################################################

from SkunkWeb import Configuration
import spreadcache

Configuration.mergeDefaults(SpreadConnectParams={})

for alias, params in Configuration.SpreadConnectParams.items():
    spreadcache.initAlias(alias, **params)
Beispiel #56
0
        res = RequestFailed(Configuration.job, exc_text, sessionDict)
        if res:
            return self._marshalData(res)
        else:
            return self._marshalData(exc_text)

    def _marshalData(self, data):
        return "%10d%s" % (len(data), data)


def _serverStartHook(*args, **kw):
    requestHandler.requestHandler.addRequestHandler(
        AecgiProtocol(), Configuration.AecgiListenPorts)


Configuration.mergeDefaults(AecgiListenPorts=['TCP:localhost:9888'])
if Configuration.AecgiListenPorts:
    Hooks.ServerStart.append(_serverStartHook)

########################################################################
# $Log: aecgi.py,v $
# Revision 1.4  2003/05/01 20:45:53  drew_csillag
# Changed license text
#
# Revision 1.3  2002/07/19 16:21:02  smulloni
# removed spurious dependencies on aecgi from httpd and templating by
# moving the RequestFailed hook into requestHandler.
#
# Revision 1.2  2002/05/24 20:56:20  smulloni
# now add request handlers in ServerStart hook
#
Beispiel #57
0
def __initFlag():
    from SkunkWeb import ServiceRegistry
    ServiceRegistry.registerService('web', 'WEB')
    import SkunkWeb.Configuration as C
    C.mergeDefaults(mergeQueryStringWithPostData=1,
                    HttpLoggingOn=0)