# Path: cydra/web/wsgihelper.py
# class HTTPBasicAuthenticator(object):
# 
#     def __init__(self, cyd=None):
#         if cyd is None:
#             cyd = cydra.Cydra()
# 
#         self.cydra = self.compmgr = cyd
#         self.cache = SimpleCache()
# 
#     def __call__(self, environ):
#         # default to guest
#         environ['cydra_user'] = self.cydra.get_user(userid='*')
# 
#         # consult the REMOTE_USER variable. If this is set, apache or some other part
#         # already did the authetication. We will trust that judgement
#         userid = environ.get('REMOTE_USER', None)
#         logger.debug('Remote user: "%s"', str(userid))
# 
#         if userid is None:
#             # Nothing already set. Perform HTTP auth ourselves
#             author = environ.get('HTTP_AUTHORIZATION', None)
#             logger.debug("No remote user supplied, trying Authorization header")
# 
#             if author is None:
#                 logger.debug("No Authorization header supplied")
#                 return self.cydra.get_user(userid='*')
# 
#             if author.strip().lower()[:5] != 'basic':
#                 # atm only basic is supported
#                 logging.warning("User tried to use a different auth method (not basic): %s")
#                 return self.cydra.get_user(userid='*')
# 
#             userpw_base64 = author.strip()[5:].strip()
#             if userpw_base64 in self.cache:
#                 # login cached as successful, we can now set REMOTE_USER for further use
#                 user = self.cache.get(userpw_base64)
#                 logger.debug('Author header found in cache, user: %s (%s)', user.full_name, user.userid)
#                 environ['REMOTE_USER'] = user.userid
#                 environ['cydra_user'] = user
#                 return user
# 
#             userid, pw = userpw_base64.decode('base64').split(':', 1)
# 
#             # yes, you probably don't want to leak information about a password
#             # such as its length into the log. The length helps to debug issues with extra
#             # whitespace though
#             logger.debug('Got user "%s" with passwordlen %d. Agent: %s', userid, len(pw), environ.get('HTTP_USER_AGENT', 'None'))
# 
#             if is_urldecode_necessary(environ.get('HTTP_USER_AGENT', '')):
#                 logger.info('Client is broken w.r.t. url encoding: %s', environ.get('HTTP_USER_AGENT', 'None'))
#                 userid = urllib.unquote(userid)
#                 pw = urllib.unquote(pw)
# 
#             user = self.cydra.get_user(username=userid)
#             if user is None:
#                 logger.debug('Lookup for %s failed', userid)
#                 user = self.cydra.get_user(userid='*')
# 
#             logger.debug('User lookup gave %s (%s)', user.full_name, user.userid)
# 
#             if user.is_guest:
#                 logger.info('User %s resolved to guest', userid)
#                 return user
# 
#             elif user.check_password(pw):
#                 # login successful, we can now set REMOTE_USER for further use
#                 environ['REMOTE_USER'] = user.userid
#                 environ['cydra_user'] = user
# 
#                 # and cache
#                 logger.debug('Caching login data for %s (%s)', user.full_name, user.userid)
#                 self.cache.set(userpw_base64, user)
# 
#                 return user
#             else:
#                 logger.info('User %s (%s) supplied a wrong password', user.full_name, user.userid)
#                 return self.cydra.get_user(userid='*')
#         else:
#             logger.debug("Got REMOTE_USER=%s", userid)
# 
#             if userid in self.cache:
#                 user = self.cache.get(userid)
#                 environ['cydra_user'] = user
#             else:
#                 user = self.cydra.get_user(username=userid)
# 
#                 if user is None:
#                     logger.debug('Lookup for %s failed', userid)
#                     user = self.cydra.get_user(userid='*')
# 
#                 if not user.is_guest:
#                     self.cache.set(userid, user)
#                     environ['cydra_user'] = user
# 
#             return user


import os
import tornado.ioloop
import tornado.httpserver
import tornado.netutil
import tornado.web
import tornado.wsgi
import cydra
import cydraplugins.githttp
import logging
    import logging
    import logging.handlers
        import daemon, grp, pwd, lockfile
    import traceback, signal
from cydra.web.wsgihelper import HTTPBasicAuthenticator
from gittornado import RPCHandler, InfoRefsHandler, FileHandler
    from optparse import OptionParser
    parser.add_option('-f', '--force-https', action='store_true', dest='force_https', default=False)
    parser.add_option('-d', '--daemonize', action='store_true', dest='daemonize', default=False)
    parser.add_option('-i', '--pidfile', action='store', dest='pidfile', default=None)
    parser.add_option('-l', '--logfile', action='store', dest='logfile', default=None)
    parser.add_option('-u', '--user', action='store', dest='user', default=None)
    parser.add_option('-g', '--group', action='store', dest='group', default=None)
    (options, args) = parser.parse_args()

    # configure logging
    formatter = logging.Formatter('[%(asctime)s] %(levelname)s: <%(name)s@%(filename)s:%(lineno)d> %(message)s')

    if options.verbose:
        loglevel = logging.DEBUG
    else:
        loglevel = logging.ERROR

    if options.logfile:
        handler = logging.handlers.TimedRotatingFileHandler(options.logfile, when='midnight', backupCount=7, encoding='utf-8')
    else:
        handler = logging.StreamHandler()

    handler.setFormatter(formatter)
    logger = logging.getLogger()
    logger.addHandler(handler)
    logger.setLevel(loglevel)

    port = 8080
    if len(args) > 0:
        port = int(args[0])


# Path: cydra/web/wsgihelper.py
# class HTTPBasicAuthenticator(object):
# 
#     def __init__(self, cyd=None):
#         if cyd is None:
#             cyd = cydra.Cydra()
# 
#         self.cydra = self.compmgr = cyd
#         self.cache = SimpleCache()
# 
#     def __call__(self, environ):
#         # default to guest
#         environ['cydra_user'] = self.cydra.get_user(userid='*')
# 
#         # consult the REMOTE_USER variable. If this is set, apache or some other part
#         # already did the authetication. We will trust that judgement
#         userid = environ.get('REMOTE_USER', None)
#         logger.debug('Remote user: "%s"', str(userid))
# 
#         if userid is None:
#             # Nothing already set. Perform HTTP auth ourselves
#             author = environ.get('HTTP_AUTHORIZATION', None)
#             logger.debug("No remote user supplied, trying Authorization header")
# 
#             if author is None:
#                 logger.debug("No Authorization header supplied")
#                 return self.cydra.get_user(userid='*')
# 
#             if author.strip().lower()[:5] != 'basic':
#                 # atm only basic is supported
#                 logging.warning("User tried to use a different auth method (not basic): %s")
#                 return self.cydra.get_user(userid='*')
# 
#             userpw_base64 = author.strip()[5:].strip()
#             if userpw_base64 in self.cache:
#                 # login cached as successful, we can now set REMOTE_USER for further use
#                 user = self.cache.get(userpw_base64)
#                 logger.debug('Author header found in cache, user: %s (%s)', user.full_name, user.userid)
#                 environ['REMOTE_USER'] = user.userid
#                 environ['cydra_user'] = user
#                 return user
# 
#             userid, pw = userpw_base64.decode('base64').split(':', 1)
# 
#             # yes, you probably don't want to leak information about a password
#             # such as its length into the log. The length helps to debug issues with extra
#             # whitespace though
#             logger.debug('Got user "%s" with passwordlen %d. Agent: %s', userid, len(pw), environ.get('HTTP_USER_AGENT', 'None'))
# 
#             if is_urldecode_necessary(environ.get('HTTP_USER_AGENT', '')):
#                 logger.info('Client is broken w.r.t. url encoding: %s', environ.get('HTTP_USER_AGENT', 'None'))
#                 userid = urllib.unquote(userid)
#                 pw = urllib.unquote(pw)
# 
#             user = self.cydra.get_user(username=userid)
#             if user is None:
#                 logger.debug('Lookup for %s failed', userid)
#                 user = self.cydra.get_user(userid='*')
# 
#             logger.debug('User lookup gave %s (%s)', user.full_name, user.userid)
# 
#             if user.is_guest:
#                 logger.info('User %s resolved to guest', userid)
#                 return user
# 
#             elif user.check_password(pw):
#                 # login successful, we can now set REMOTE_USER for further use
#                 environ['REMOTE_USER'] = user.userid
#                 environ['cydra_user'] = user
# 
#                 # and cache
#                 logger.debug('Caching login data for %s (%s)', user.full_name, user.userid)
#                 self.cache.set(userpw_base64, user)
# 
#                 return user
#             else:
#                 logger.info('User %s (%s) supplied a wrong password', user.full_name, user.userid)
#                 return self.cydra.get_user(userid='*')
#         else:
#             logger.debug("Got REMOTE_USER=%s", userid)
# 
#             if userid in self.cache:
#                 user = self.cache.get(userid)
#                 environ['cydra_user'] = user
#             else:
#                 user = self.cydra.get_user(username=userid)
# 
#                 if user is None:
#                     logger.debug('Lookup for %s failed', userid)
#                     user = self.cydra.get_user(userid='*')
# 
#                 if not user.is_guest:
#                     self.cache.set(userid, user)
#                     environ['cydra_user'] = user
# 
#             return user


# Path: plugins/githttp/cydraplugins/githttp/gittornado_integration.py
import os
import tornado.ioloop
import tornado.httpserver
import tornado.netutil
import tornado.web
import tornado.wsgi
import cydra
import cydraplugins.githttp
import logging
    import logging
    import logging.handlers
        import daemon, grp, pwd, lockfile
    import traceback, signal
from cydra.web.wsgihelper import HTTPBasicAuthenticator
from gittornado import RPCHandler, InfoRefsHandler, FileHandler
    from optparse import OptionParser

    parser.add_option('-f', '--force-https', action='store_true', dest='force_https', default=False)
    parser.add_option('-d', '--daemonize', action='store_true', dest='daemonize', default=False)
    parser.add_option('-i', '--pidfile', action='store', dest='pidfile', default=None)
    parser.add_option('-l', '--logfile', action='store', dest='logfile', default=None)
    parser.add_option('-u', '--user', action='store', dest='user', default=None)
    parser.add_option('-g', '--group', action='store', dest='group', default=None)
    (options, args) = parser.parse_args()

    # configure logging
    formatter = logging.Formatter('[%(asctime)s] %(levelname)s: <%(name)s@%(filename)s:%(lineno)d> %(message)s')

    if options.verbose:
        loglevel = logging.DEBUG
    else:
        loglevel = logging.ERROR

    if options.logfile:
        handler = logging.handlers.TimedRotatingFileHandler(options.logfile, when='midnight', backupCount=7, encoding='utf-8')
    else:
        handler = logging.StreamHandler()

    handler.setFormatter(formatter)
    logger = logging.getLogger()
    logger.addHandler(handler)
    logger.setLevel(loglevel)

    port = 8080
    if len(args) > 0:
        port = int(args[0])


    cyd = cydra.Cydra()