예제 #1
0
파일: index.py 프로젝트: creshal/yakicms
def index (req, repo=None, version="0.0.0", OS="None"):
	if not repo:
		repolist = ""
		desc = "Download " + " ".join ([repo["name"] for repo in lib.get_config ("Repositories","Downloads")])
		for repo in lib.get_config ("Repositories","Downloads"):
			try:
				repolist += _snippet_for_repo (None, repo)
			except Exception as e:
				apache.log_error (str(e))
		return lib.respond (req, "<div class='news'>"+repolist+"<br/><br/></div>", "Downloads", "Downloads", desc, module_info ())
	else:
		repository = None
		for entry in lib.get_config ("Repositories","Downloads"):
			if entry["repo"] == repo:
				repository = entry
				break
		else:
			return lib.e404 (req, "Could not find a matching repository.", module_info())
		try:
			ver = _latest_ver (repo=repository)
		except Exception as e:
			apache.log_error (traceback.format_exc())
			return lib.e404 (req, "Repository corrupt or wrong configuration, please contact the administrator.", module_info())
		if version == ver:
			return lib.respond (req, "You're already running the lastest version of %s." % repository["name"], "Downloads", "Downloads", "Updater", module_info())
		else:
			return lib.respond (req, _snippet_for_repo (repo=repository),"Downloads", "Downloads", "Download %s" % repository["name"], module_info())
예제 #2
0
    def __init__(self,url):
        parseURL = urlparse.urlparse(unquote(url))
        try:
                self.arguments = urlparse.parse_qs(parseURL.query)
        except:
                # f**k python 2.5!!
                self.arguments = {}
                for arg in parseURL.query.split("&"):
                        from mod_python import apache
                        apache.log_error(arg,apache.APLOG_ERR)
                        try:
                                (key,value) = arg.split("=")
                                self.arguments[key] = value
                        except:
                                pass

        self.arguments["reaspect"] = "false"

        for i in self.arguments:
            if type(self.arguments[i]) == type ([]):
                self.arguments[i] = self.arguments[i][0]


        self.scheme = parseURL.scheme
        self.netloc = parseURL.netloc
        self.path = parseURL.path
        self.fragment = parseURL.fragment

        self.setArgument("exceptions","application/vnd.ogc.se_inimage")
예제 #3
0
파일: form.py 프로젝트: aashray/dist_crawl
def do_more_stuff(req, links_str):
    links_with_depth = links_str.split("|||")
    links = []
    for each in links_with_depth:
        if each != "":
            each_link_and_depth = each.split("||")
            apache.log_error(str(each_link_and_depth))
            links.append(each_link_and_depth)
    apache.log_error(links_str)
    #apache.log_error(str(len(links_str)));
    #apache.log_error(str(links))
    result = dist_crawl.start_processing([], links, 0)
    map_res = result[0]
    result.pop(0)
    map_to_arr = []
    for each in map_res:
        map_to_arr.append([each] + map_res[each])
    result.insert(0, map_to_arr)
    more_results = result[0]
    ret_html = ""
    for res in more_results:
        ret_html = ret_html + "<tr>"
        for col in res:
            ret_html = ret_html + "<td>" + str(col) + "</td>"
        ret_html = ret_html + "</tr>"

    return ret_html
예제 #4
0
파일: index.py 프로젝트: wujcheng/cobbler
def handler(req):
    """
    Right now, index serves everything.

    Hitting this URL means we've already cleared authn/authz
    but we still need to use the token for all remote requests.
    """

    my_user = __get_user(req)
    my_uri = req.uri
    sess = __get_session(req)

    if not sess.has_key('cobbler_token'):
        # using Kerberos instead of Python Auth handler?
        # We need to get our own token for use with authn_passthru
        # which should also be configured in /etc/cobbler/modules.conf
        # if another auth mode is configured in modules.conf this will
        # most certaintly fail.
        try:
            if not os.path.exists("/var/lib/cobbler/web.ss"):
                apache.log_error("cannot load /var/lib/cobbler/web.ss")
                return apache.HTTP_UNAUTHORIZED
            fd = open("/var/lib/cobbler/web.ss")
            data = fd.read()
            my_pw = data
            fd.close()
            token = xmlrpc_server.login(my_user, my_pw)
        except Exception, e:
            apache.log_error(str(e))
            return apache.HTTP_UNAUTHORIZED
        sess['cobbler_token'] = token
예제 #5
0
파일: index.py 프로젝트: 77720616/cobbler
def handler(req):

    """
    Right now, index serves everything.

    Hitting this URL means we've already cleared authn/authz
    but we still need to use the token for all remote requests.
    """

    my_user = __get_user(req)
    my_uri = req.uri
    sess  = __get_session(req)

    if not sess.has_key('cobbler_token'):
       # using Kerberos instead of Python Auth handler? 
       # We need to get our own token for use with authn_passthru
       # which should also be configured in /etc/cobbler/modules.conf
       # if another auth mode is configured in modules.conf this will
       # most certaintly fail.
       try:
           if not os.path.exists("/var/lib/cobbler/web.ss"):
               apache.log_error("cannot load /var/lib/cobbler/web.ss")
               return apache.HTTP_UNAUTHORIZED
           fd = open("/var/lib/cobbler/web.ss")
           data = fd.read()
           my_pw = data
           fd.close()
           token = xmlrpc_server.login(my_user,my_pw)
       except Exception, e:
           apache.log_error(str(e))
           return apache.HTTP_UNAUTHORIZED
       sess['cobbler_token'] = token
예제 #6
0
def _create_dispatcher():
    _LOGGER.info('Initializing Dispatcher')

    options = apache.main_server.get_options()

    handler_root = options.get(_PYOPT_HANDLER_ROOT, None)
    if not handler_root:
        raise Exception('PythonOption %s is not defined' % _PYOPT_HANDLER_ROOT,
                        apache.APLOG_ERR)

    handler_scan = options.get(_PYOPT_HANDLER_SCAN, handler_root)

    allow_handlers_outside_root = _parse_option(
        _PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT,
        options.get(_PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT),
        _PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT_DEFINITION)

    dispatcher = dispatch.Dispatcher(
        handler_root, handler_scan, allow_handlers_outside_root)

    for warning in dispatcher.source_warnings():
        apache.log_error(
            'mod_pywebsocket: Warning in source loading: %s' % warning,
            apache.APLOG_WARNING)

    return dispatcher
예제 #7
0
def handler(req):
    """HTTP request handler"""
    _options = req.get_options()
    _home = _options.get("TrackerHome")
    _lang = _options.get("TrackerLanguage")
    _timing = _options.get("TrackerTiming", "no")
    if _timing.lower() in ("no", "false"):
        _timing = ""
    _debug = _options.get("TrackerDebug", "no")
    _debug = _debug.lower() not in ("no", "false")
    if not (_home and os.path.isdir(_home)):
        apache.log_error(
            "PythonOption TrackerHome missing or invalid for %(uri)s"
            % {'uri': req.uri})
        return apache.HTTP_INTERNAL_SERVER_ERROR
    _tracker = roundup.instance.open(_home, not _debug)
    # create environment
    # Note: cookies are read from HTTP variables, so we need all HTTP vars
    req.add_common_vars()
    _env = dict(req.subprocess_env)
    # XXX classname must be the first item in PATH_INFO.  roundup.cgi does:
    #       path = string.split(os.environ.get('PATH_INFO', '/'), '/')
    #       os.environ['PATH_INFO'] = string.join(path[2:], '/')
    #   we just remove the first character ('/')
    _env["PATH_INFO"] = req.path_info[1:]
    if _timing:
        _env["CGI_SHOW_TIMING"] = _timing
    _form = cgi.FieldStorage(req, environ=_env)
    _client = _tracker.Client(_tracker, Request(req), _env, _form,
        translator=TranslationService.get_translation(_lang,
            tracker_home=_home))
    _client.main()
    return apache.OK
예제 #8
0
def handler(req):
    #req.content_type = 'text/plain'
    #req.write("Hello World!")

    if req.method == 'POST':
        kwargs = parse_qs(req.read())
    elif req.method == 'GET':
        kwargs = parse_qs(req.args)

    #oldid = os.getuid()
    #os.setuid(501)

    try:
        method = str(kwargs['mode'][0])
        methodKWargs = kwargs.remove('mode')
        methodKWargs['req'] = req

        myFilemanager.__dict__['method'](**methodKWargs)

        return apache.OK

    except KeyError:
        return apache.HTTP_BAD_REQUEST

    except Exception, (errno, strerror):
        apache.log_error(strerror, apache.APLOG_CRIT)
        return apache.HTTP_INTERNAL_SERVER_ERROR
예제 #9
0
파일: form.py 프로젝트: aashray/dist_crawl
def do_more_stuff(req, links_str):
	links_with_depth = links_str.split("|||");
	links = []
	for each in links_with_depth:
		if each != "":
			each_link_and_depth = each.split("||")
			apache.log_error(str(each_link_and_depth))
			links.append(each_link_and_depth);
	apache.log_error(links_str);
	#apache.log_error(str(len(links_str)));
	#apache.log_error(str(links))
	result = dist_crawl.start_processing([], links, 0);
	map_res = result[0]
	result.pop(0);
	map_to_arr = []
	for each in map_res:
		map_to_arr.append([each] + map_res[each])
	result.insert(0, map_to_arr);
	more_results = result[0]
	ret_html = ""
	for res in more_results:
		ret_html = ret_html + "<tr>"
		for col in res:
			ret_html = ret_html + "<td>" + str(col) + "</td>"
		ret_html = ret_html + "</tr>"

	return ret_html
def handler(req): 
    #req.content_type = 'text/plain' 
    #req.write("Hello World!") 

    if req.method == 'POST':
        kwargs = parse_qs(req.read())
    elif req.method == 'GET': 
        kwargs = parse_qs(req.args)
    
    #oldid = os.getuid()
    #os.setuid(501)

    try:
        method=str(kwargs['mode'][0])
        methodKWargs=kwargs.remove('mode')
        methodKWargs['req']=req
        
        myFilemanager.__dict__['method'](**methodKWargs)
        
        return apache.OK 


    except KeyError:
        return apache.HTTP_BAD_REQUEST   

    except Exception, (errno, strerror):
        apache.log_error(strerror, apache.APLOG_CRIT)
        return apache.HTTP_INTERNAL_SERVER_ERROR
예제 #11
0
def getDicts(params):
    result = []
    dictSums = getDictSums()
    for param in params:
        name = param[k_NAME]
        lang = param[k_LANG]
        md5sum = param[k_MD5SUM]
        index = param[k_INDEX]
        if not name.endswith(k_suffix): name += k_suffix
        path = lang + "/" + name
        if not path in dictSums:
            sums = md5Checksums(dictSums, path)
            if sums:
                dictSums[path] = sums
                s_shelf[k_SUMS] = dictSums
        if path in dictSums:
            if not md5sum in dictSums[path]:
                cur = {
                    k_URL: k_urlbase + "/and_wordlists/" + path,
                    k_INDEX: index,
                    k_ISUM: dictSums[path][1]
                }
                result.append(cur)
        else:
            apache.log_error(path + " not known")

    closeShelf()
    if 0 == len(result): result = None
    return result
예제 #12
0
def getUpdates(req, params):
    result = {k_SUCCESS: True}
    appResult = None
    apache.log_error("getUpdates: got params: %s" % params)
    asJson = json.loads(params)
    if k_APP in asJson:
        name = None
        if k_NAME in asJson: name = asJson[k_NAME]
        appResult = getApp(asJson[k_APP], name)
        if appResult:
            result[k_APP] = appResult
    if k_DICTS in asJson:
        dictsResult = getDicts(asJson[k_DICTS])
        if dictsResult:
            result[k_DICTS] = dictsResult

    # Let's not upgrade strings at the same time as we're upgrading the app
    # if appResult:
    #     apache.log_error( 'skipping xlation upgrade because app being updated' )
    # elif k_XLATEINFO in asJson and k_NAME in asJson and k_STRINGSHASH in asJson:
    #     xlateResult = getXlate( asJson[k_XLATEINFO], asJson[k_NAME], asJson[k_STRINGSHASH] )
    #     if xlateResult:
    #         apache.log_error( xlateResult )
    #         result[k_XLATEINFO] = xlateResult;

    result = json.dumps(result)
    # apache.log_error( result )
    return result
def getClasses(req,buld=None,room=None):
	req.content_type="application/json"
	req.send_http_header()
	if buld is None or room is None:
		return "classypengins = null;"
	buld = re.sub("^[0 ]+","",buld)
	room = re.sub("^[0 ]+","",room)
	conn = sqlite3.connect(path+'/rota.db')
	c = conn.cursor()
	c.execute('''SELECT session, start, stop FROM class WHERE building=? AND room=? AND start > ? AND start < ?''',(
		buld,
		room,
		datetime.date.today() + offset,
		datetime.date.today() + offset + datetime.timedelta(days=1)
		))
	res = c.fetchall()
	sessions = []
	for r in res:
		apache.log_error(repr(r),apache.APLOG_DEBUG)
		c.execute('''SELECT offering FROM classCourse WHERE session=?''', (r[0],))
		offer = c.fetchall()
		c.execute('''SELECT course FROM courses WHERE offering=?''',
			(offer[0][0],))
		classname = c.fetchall()
		sessiondict={}
		sessiondict['class']=classname[0][0]
		sessiondict['start']=r[1]
		sessiondict['finish']=r[2]
		sessions.append(sessiondict)
	return simplejson.dumps(sessions)
예제 #14
0
def handler(req):
    reload(sys) #set default encoding from ascii to utf-8
    sys.setdefaultencoding('utf-8')

    apache.log_error(req.args)

    params = {}
    for pair in req.args.split('&'):
        key, value = pair.split('=')
        params[key] = value
    if params['service'] == 'get_sen':
        req.content_type = "text/plain; charset=utf-8"
        uid = params['uid']
        sen = getSen(uid)
        req.write(sen)
        return apache.OK
    elif params['service'] == 'put_sen':
        wav = req.read()
        uid = params['uid']
        sid = params['sid']
        result = putSen(uid, sid, wav)
        req.content_type = "text/plain; charset=utf-8"
        req.write(result)
        return apache.OK
    elif params['service'] == 'login':
        user_name = unquote(params['user_name']).decode('utf-8')
        result = login(user_name)
        req.content_type = "text/plain; charset=utf-8"
        req.write(result)
        return apache.OK
예제 #15
0
def _create_dispatcher():
    _LOGGER.info('Initializing Dispatcher')

    options = apache.main_server.get_options()

    handler_root = options.get(_PYOPT_HANDLER_ROOT, None)
    if not handler_root:
        raise Exception('PythonOption %s is not defined' % _PYOPT_HANDLER_ROOT,
                        apache.APLOG_ERR)

    handler_scan = options.get(_PYOPT_HANDLER_SCAN, handler_root)

    allow_handlers_outside_root = _parse_option(
        _PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT,
        options.get(_PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT),
        _PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT_DEFINITION)

    dispatcher = dispatch.Dispatcher(
        handler_root, handler_scan, allow_handlers_outside_root)

    for warning in dispatcher.source_warnings():
        apache.log_error(
            'mod_pywebsocket: Warning in source loading: %s' % warning,
            apache.APLOG_WARNING)

    return dispatcher
예제 #16
0
def handler(req):
    reload(sys) #set default encoding from ascii to utf-8
    sys.setdefaultencoding('utf-8')

    apache.log_error(req.args)

    params = {}
    for pair in req.args.split('&'):
        key, value = pair.split('=')
        params[key] = value
    ssid = params['ssid']
    password = params['passwd']
    req.content_type = "text/plain; charset=utf-8"
    req.write('开始连接wifi咯!')

    scripts_path = get_scripts_path()
    if scripts_path == '':
        apache.log_error('scripts_path resolv failed!')
    catkin_ws = scripts_path.split('src')[0]
    sys.path.append(catkin_ws+'devel/lib/python2.7/dist-packages')
    sys.path.append('/opt/ros/hydro/lib/python2.7/dist-packages')
    os.environ['ROS_MASTER_URI'] = 'http://localhost:11311'
    import rospy
    from qbo_config_manager.srv import *
    rospy.wait_for_service('/config_connect_user_wifi')
    proc = rospy.ServiceProxy('/config_connect_user_wifi', ConnectWifi)
    result = proc(ssid, 'p'+password)  #ROS 把'123456'理解成数字,而不是字符串,所以要在前面加字母占位符

    return apache.OK
예제 #17
0
def headerparserhandler(req):
    options = req.get_options()

    realm = None
    if options.has_key('Realm'):
        realm = options['Realm']
    else:
        apache.log_error('no realm specified')
        return apache.DECLINED

    # if the token is in the URL, extract it and send it to the login page
    token = None
    if req.args != None:
        try:
            dict = util.FieldStorage(req)
            if dict.has_key('token'):
                token = dict['token']
        except:
            pass

    sess = Session.Session(req, lock=0)
    sess.lock()
    sess.set_timeout(SESSION_TIMEOUT)

    username = session_user(sess, realm)

    if None == username and realm == 'Reports':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard' and not is_wizard_complete():
        username = '******'
        save_session_user(sess, realm, username)

    if None == username and is_local_process_uid_authorized(req):
        username = '******'
        log_login(req, username, True, True, None)
        save_session_user(sess, realm, username)

    #if sess.has_key('apache_realms'):
    #    apache.log_error('DEBUG apache_realms: %s' % sess['apache_realms'])
    #    if sess['apache_realms'].has_key(realm):
    #        apache.log_error('DEBUG apache_realms[%s]: %s' % (realm, sess['apache_realms'][realm]))
    #else:
    #    apache.log_error('DEBUG apache_realms: %s' % None)

    sess.save()
    sess.unlock()

    if username != None:
        pw = base64.encodestring('%s' % username).strip()
        req.headers_in['Authorization'] = "BASIC % s" % pw
        req.notes['authorized'] = 'true'
        return apache.OK

    apache.log_error('Auth failure [Username not specified]. Redirecting to auth page. (realm: %s)' % realm)
    login_redirect(req, realm, token)
예제 #18
0
def headerparserhandler(req):
    options = req.get_options()

    realm = None
    if options.has_key('Realm'):
        realm = options['Realm']
    else:
        apache.log_error('no realm specified')
        return apache.DECLINED

    # if the token is in the URL, extract it and send it to the login page
    token = None
    if req.args != None:
        try:
            dict = util.FieldStorage(req)
            if dict.has_key('token'):
                token = dict['token']
        except:
            pass

    sess = Session.Session(req, lock=0)
    sess.lock()
    sess.set_timeout(SESSION_TIMEOUT)

    username = session_user(sess, realm)

    if None == username and realm == 'Reports':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard' and not wizard_password_required():
        username = '******'
        save_session_user(sess, realm, username)

    if None == username and is_local_process_uid_authorized(req):
        username = '******'
        log_login(req, username, True, True, None)
        save_session_user(sess, realm, username)

    #if sess.has_key('apache_realms'):
    #    apache.log_error('DEBUG apache_realms: %s' % sess['apache_realms'])
    #    if sess['apache_realms'].has_key(realm):
    #        apache.log_error('DEBUG apache_realms[%s]: %s' % (realm, sess['apache_realms'][realm]))
    #else:
    #    apache.log_error('DEBUG apache_realms: %s' % None)

    sess.save()
    sess.unlock()

    if username != None:
        pw = base64.encodestring('%s' % username).strip()
        req.headers_in['Authorization'] = "BASIC % s" % pw
        req.notes['authorized'] = 'true'
        return apache.OK

    apache.log_error('Auth failure [Username not specified]. Redirecting to auth page. (realm: %s)' % realm)
    login_redirect(req, realm, token)
예제 #19
0
 def log(self, msg):
     if self.logger.error_log is self.__error_log:
         try:
             self.__apache_request.log_error(msg)
         except AttributeError:
             apache.log_error(msg)
     else:
         Publisher.log(self, msg)
예제 #20
0
 def log(self, msg):
     if self.error_log is self.__error_log:
         try:
             self.__apache_request.log_error(msg)
         except AttributeError:
             apache.log_error(msg)
     else:
         Publisher.log(self, msg)
예제 #21
0
def phase_status_8(req):
    apache.log_error("phase_status_8")
    apache.log_error("phases = %s" % req.phases)
    if req.phases != [1, 2, 5, 6, 7]:
        req.write("test failed")
    else:
        req.write("test ok")
    return apache.OK
예제 #22
0
def phase_status_8(req):
    apache.log_error("phase_status_8")
    apache.log_error("phases = %s" % req.phases)
    if req.phases != [1, 2, 5, 6, 7]:
        req.write("test failed")
    else:
        req.write("test ok")
    return apache.OK
예제 #23
0
파일: _cpmodpy.py 프로젝트: Pluckyduck/eve
 def _log(msg, level):
     newlevel = apache.APLOG_ERR
     if logging.DEBUG >= level:
         newlevel = apache.APLOG_DEBUG
     elif logging.INFO >= level:
         newlevel = apache.APLOG_INFO
     elif logging.WARNING >= level:
         newlevel = apache.APLOG_WARNING
     apache.log_error(msg, newlevel, req.server)
예제 #24
0
 def _log(msg, level):
     newlevel = apache.APLOG_ERR
     if logging.DEBUG >= level:
         newlevel = apache.APLOG_DEBUG
     elif logging.INFO >= level:
         newlevel = apache.APLOG_INFO
     elif logging.WARNING >= level:
         newlevel = apache.APLOG_WARNING
     apache.log_error(msg, newlevel, req.server)
예제 #25
0
 def emit(self, record):
     level = self.apache_level(record)
     """
     Set MODPYTHON mp_server object so that vhost logs to its own error_log.
     """
     try:
         server = record.__dict__['server']
         apache.log_error(record.getMessage(), level, server)
     except KeyError:
         apache.log_error(record.getMessage(), level)
예제 #26
0
def _create_dispatcher():
    _HANDLER_ROOT = apache.main_server.get_options().get(
            _PYOPT_HANDLER_ROOT, None)
    if not _HANDLER_ROOT:
        raise Exception('PythonOption %s is not defined' % _PYOPT_HANDLER_ROOT,
                        apache.APLOG_ERR)
    dispatcher = dispatch.Dispatcher(_HANDLER_ROOT)
    for warning in dispatcher.source_warnings():
        apache.log_error('mod_pywebsocket: %s' % warning, apache.APLOG_WARNING)
    return dispatcher
예제 #27
0
def send_login_event(client_addr, login, local, succeeded, reason):
    # localadmin is used for local machine API calls
    # these are not logged
    if login == "localadmin":
        return
    try:
        uvmContext = uvm.Uvm().getUvmContext()
        uvmContext.adminManager().logAdminLoginEvent( str(login), local, str(client_addr), succeeded, reason )
    except Exception, e:
        apache.log_error('error: %s' % repr(e))
예제 #28
0
def send_login_event(client_addr, login, local, succeeded, reason):
    # localadmin is used for local machine API calls
    # these are not logged
    if login == "localadmin":
        return
    try:
        uvmContext = uvm.Uvm().getUvmContext()
        uvmContext.adminManager().logAdminLoginEvent( str(login), local, str(client_addr), succeeded, reason )
    except Exception, e:
        apache.log_error('error: %s' % repr(e))
예제 #29
0
def handler(req):
    """HTTP request handler"""
    _options = req.get_options()
    _home = _options.get("TrackerHome")
    _lang = _options.get("TrackerLanguage")
    _timing = _options.get("TrackerTiming", "no")
    if _timing.lower() in ("no", "false"):
        _timing = ""
    _debug = _options.get("TrackerDebug", "no")
    _debug = _debug.lower() not in ("no", "false")

    # We do not need to take a lock here (the fast path) because reads
    # from dictionaries are atomic.
    if not _debug and _home in __tracker_cache:
        _tracker = __tracker_cache[_home]
    else:
        if not (_home and os.path.isdir(_home)):
            apache.log_error(
                "PythonOption TrackerHome missing or invalid for %(uri)s" %
                {'uri': req.uri})
            return apache.HTTP_INTERNAL_SERVER_ERROR
        if _debug:
            _tracker = roundup.instance.open(_home, optimize=0)
        else:
            __tracker_cache_lock.acquire()
            try:
                # The tracker may have been added while we were acquiring
                # the lock.
                if _home in __tracker_cache:
                    _tracker = __tracker_cache[home]
                else:
                    _tracker = roundup.instance.open(_home, optimize=1)
                    __tracker_cache[_home] = _tracker
            finally:
                __tracker_cache_lock.release()
    # create environment
    # Note: cookies are read from HTTP variables, so we need all HTTP vars
    req.add_common_vars()
    _env = dict(req.subprocess_env)
    # XXX classname must be the first item in PATH_INFO.  roundup.cgi does:
    #       path = os.environ.get('PATH_INFO', '/').split('/')
    #       os.environ['PATH_INFO'] = '/'.join(path[2:])
    #   we just remove the first character ('/')
    _env["PATH_INFO"] = req.path_info[1:]
    if _timing:
        _env["CGI_SHOW_TIMING"] = _timing
    _form = cgi.FieldStorage(req, environ=_env)
    _client = _tracker.Client(_tracker,
                              Request(req),
                              _env,
                              _form,
                              translator=TranslationService.get_translation(
                                  _lang, tracker_home=_home))
    _client.main()
    return apache.OK
예제 #30
0
파일: uvmlogin.py 프로젝트: rjt/untangle
def setup_gettext():
    lang = get_uvm_language()
    try:
        trans = gettext.translation('untangle-apache2-config',
                                    languages=[lang],
                                    fallback=True)
        trans.install()
    except Exception, e:
        apache.log_error('could not install language: %s lang. %s' % (lang, e))
        import __builtin__
        __builtin__.__dict__['_'] = unicode
예제 #31
0
def getXlate(params, name, stringsHash):
    result = []
    path = xwconfig.k_REPOPATH
    apache.log_error('creating repo with path ' + path)
    repo = mygit.GitRepo(path)
    apache.log_error("getXlate: %s, hash=%s" %
                     (json.dumps(params), stringsHash))
    # apache.log_error( 'status: ' + repo.status() )

    # reduce org.eehouse.anroid.xxx to xxx, then turn it into a
    # variant and get the contents of the R.java file
    splits = name.split('.')
    name = splits[-1]
    variant = variantFor(name)
    rPath = '%s/archive/R.java' % variant
    rDotJava = repo.cat(rPath, stringsHash)

    # Figure out the newest hash possible for translated strings.xml
    # files.  If our R.java's the newest, that's HEAD.  Otherwise it's
    # the revision BEFORE the revision that changed R.java

    head = repo.getHeadRev()
    apache.log_error('head = %s' % head)
    rjavarevs = repo.getRevsBetween(head, stringsHash, rPath)
    if rjavarevs:
        assert (1 >= len(rjavarevs))
        assert (stringsHash == rjavarevs[-1])
        if 1 == len(rjavarevs):
            firstPossible = head
        else:
            firstPossible = rjavarevs[-2] + '^'
            # get actual number for rev^
            firstPossible = repo.getRevsBetween(firstPossible,
                                                firstPossible)[0]
        apache.log_error('firstPossible: %s' % firstPossible)

        for entry in params:
            curVers = entry[k_XLATEVERS]
            if not curVers == firstPossible:
                locale = entry[k_LOCALE]

                data = mk_for_download.getXlationFor( repo, rDotJava, locale, \
                                                          firstPossible )
                if data:
                    result.append({
                        k_LOCALE: locale,
                        k_OLD: curVers,
                        k_NEW: firstPossible,
                        k_PAIRS: data,
                    })

    if 0 == len(result): result = None
    apache.log_error("getXlate=>%s" % (json.dumps(result)))
    return result
예제 #32
0
파일: uvmlogin.py 프로젝트: rjt/untangle
def setup_gettext():
    lang = get_uvm_language()
    try:
        trans = gettext.translation('untangle-apache2-config',
                                    languages=[lang],
                                    fallback=True)
        trans.install()
    except Exception, e:
        apache.log_error('could not install language: %s lang. %s' % (lang, e))
        import __builtin__
        __builtin__.__dict__['_'] = unicode
예제 #33
0
def login(user_name):
    db_conn = getDbConn()
    c = db_conn.cursor()
    apache.log_error("user_name = %s!"%user_name, apache.APLOG_WARNING)
    c.execute('select user_id from userDB where user_name = "%s" limit 1;'%user_name)
    rec = c.fetchall()
    if len(rec) == 0:
        apache.log_error("user_name not found!", apache.APLOG_WARNING)
	return '0'
    else:
        return str(rec[0][0]) #record 0 field 0, then convert from int to str
예제 #34
0
def _create_dispatcher():
    _HANDLER_ROOT = apache.main_server.get_options().get(
        _PYOPT_HANDLER_ROOT, None)
    if not _HANDLER_ROOT:
        raise Exception('PythonOption %s is not defined' % _PYOPT_HANDLER_ROOT,
                        apache.APLOG_ERR)
    _HANDLER_SCAN = apache.main_server.get_options().get(
        _PYOPT_HANDLER_SCAN, _HANDLER_ROOT)
    dispatcher = dispatch.Dispatcher(_HANDLER_ROOT, _HANDLER_SCAN)
    for warning in dispatcher.source_warnings():
        apache.log_error('mod_pywebsocket: %s' % warning, apache.APLOG_WARNING)
    return dispatcher
예제 #35
0
def is_local_process_uid_authorized(req):
    (remote_ip, remote_port) = req.connection.remote_addr

    if remote_ip != "127.0.0.1":
        return False

    # This determines the PID of the connecting process
    # and determines if it is from a process who is owned by root
    # or a user in uvm_login group. If so, auto-authenticate it.
    uids = get_uvmlogin_uids()

    q = remote_ip.split(".")
    q.reverse()
    n = reduce(lambda a, b: long(a) * 256 + long(b), q)
    hexaddr = "%08X" % n
    hexport = "%04X" % remote_port

    # We have to attempt to read /proc/net/tcp several times.
    # There is some race condition in the kernel and sometimes the socket we are looking for will not show up on the first read
    # This loop hack appears to "fix" the issue as it always shows up on the second read if the first fails.
    #
    # Also sometimes /proc/net/tcp reports the incorrect UID.
    # As a result, we must also try again if the UID is not authorized
    uid = None
    for count in range(0, 5):
        # if count > 0:
        #     apache.log_error('Failed to find/authorize UID [%s, %s:%s], attempting again... (try: %i)' % ( str(uid), str(remote_ip), str(remote_port), (count+1) ) )
        try:
            infile = open('/proc/net/tcp', 'r')
            for l in infile.readlines():
                a = l.split()
                if len(a) <= 2:
                    continue

                p = a[1].split(':')
                if len(p) != 2:
                    continue

                if p[0] == hexaddr and p[1] == hexport:
                    try:
                        uid = int(a[7])

                        # Found the UID
                        # if its in the list of enabled UIDs
                        if uid in uids:
                            return True
                    except:
                        apache.log_error('Bad UID: %s' % a[7])

        except Exception, e:
            apache.log_error('Exception reading /proc/net/tcp: %s' %
                             traceback.format_exc(e))
        finally:
 def _log(msg, level):
     newlevel = apache.APLOG_ERR
     if logging.DEBUG >= level:
         newlevel = apache.APLOG_DEBUG
     elif logging.INFO >= level:
         newlevel = apache.APLOG_INFO
     elif logging.WARNING >= level:
         newlevel = apache.APLOG_WARNING
     # On Windows, req.server is required or the msg will vanish. See
     # http://www.modpython.org/pipermail/mod_python/2003-October/014291.html.
     # Also, "When server is not specified...LogLevel does not apply..."
     apache.log_error(msg, newlevel, req.server)
예제 #37
0
파일: apache.py 프로젝트: AnishShah/roundup
def handler(req):
    """HTTP request handler"""
    _options = req.get_options()
    _home = _options.get("TrackerHome")
    _lang = _options.get("TrackerLanguage")
    _timing = _options.get("TrackerTiming", "no")
    if _timing.lower() in ("no", "false"):
        _timing = ""
    _debug = _options.get("TrackerDebug", "no")
    _debug = _debug.lower() not in ("no", "false")

    # We do not need to take a lock here (the fast path) because reads
    # from dictionaries are atomic.
    if not _debug and _home in __tracker_cache:
        _tracker = __tracker_cache[_home]
    else:
        if not (_home and os.path.isdir(_home)):
            apache.log_error(
                "PythonOption TrackerHome missing or invalid for %(uri)s"
                % {'uri': req.uri})
            return apache.HTTP_INTERNAL_SERVER_ERROR
        if _debug:
            _tracker = roundup.instance.open(_home, optimize=0)
        else:
            __tracker_cache_lock.acquire()
            try:
                # The tracker may have been added while we were acquiring
                # the lock.
                if _home in __tracker_cache:
                    _tracker = __tracker_cache[home]
                else:
                    _tracker = roundup.instance.open(_home, optimize=1)
                    __tracker_cache[_home] = _tracker
            finally:
                __tracker_cache_lock.release()
    # create environment
    # Note: cookies are read from HTTP variables, so we need all HTTP vars
    req.add_common_vars()
    _env = dict(req.subprocess_env)
    # XXX classname must be the first item in PATH_INFO.  roundup.cgi does:
    #       path = string.split(os.environ.get('PATH_INFO', '/'), '/')
    #       os.environ['PATH_INFO'] = string.join(path[2:], '/')
    #   we just remove the first character ('/')
    _env["PATH_INFO"] = req.path_info[1:]
    if _timing:
        _env["CGI_SHOW_TIMING"] = _timing
    _form = cgi.FieldStorage(req, environ=_env)
    _client = _tracker.Client(_tracker, Request(req), _env, _form,
        translator=TranslationService.get_translation(_lang,
            tracker_home=_home))
    _client.main()
    return apache.OK
예제 #38
0
	def test(self, req):
		req.content_type = "text/plain"
	
		apache.log_error("request!", apache.APLOG_NOTICE)
		req.write("\nParsed URI:\n-------------\n")
		req.write(dump.dump(req.parsed_uri))
		req.write("\nModPython Options:\n-------------\n")
		req.write(dump.dump(req.get_options()))
		req.write("\nModPython Config:\n-------------\n")
		req.write(dump.dump(req.get_config()))
		
		req.write("\nOS Env:\n-------------\n")
		req.write(dump.dump(os.environ))
	
		req.write("\nProcess Env:\n-------------\n")
		req.add_common_vars()
		req.write(dump.dump(req.subprocess_env))
		
		req.write("\n")
		req.write("server_root=" + apache.server_root() + "\n")
		req.write("document_root=" + req.document_root() + "\n")
		req.write("loglevel=" + dump.dump(req.server.loglevel))
		req.write("is_virtual=" + dump.dump(req.server.is_virtual))
		req.write("phase=" + dump.dump(req.phase))
		req.write("handler=" + dump.dump(req.handler))
		req.write("uri=" + dump.dump(req.uri))
		req.write("filename=" + dump.dump(req.filename))
		req.write("py interpreter=" + dump.dump(req.interpreter))
		
		req.write("\n")
		req.write("__file__=" + __file__ + "\n")
		req.write("dir=" + os.path.dirname(__file__) + "\n")
		
		req.write("\n")
		if apache.mpm_query(apache.AP_MPMQ_IS_THREADED):
			req.write("mpm is threaded\n")
		else:
			req.write("mpm is NOT threaded\n")
		if apache.mpm_query(apache.AP_MPMQ_IS_FORKED):
			req.write("mpm is forked\n")
		else:
			req.write("mpm is NOT forked\n")
		
		req.write("\n")
		req.write("sys.path: %s\n" % sys.path)
		req.write("\n")
		req.write("POST form data:\n")    
		req.write("content length: " + dump.dump(req.clength))
		req.write(dump.dump(req.read()))
		#req.write(dump.dump(apache.config_tree()))
		
		return apache.OK
예제 #39
0
파일: uvmlogin.py 프로젝트: rjt/untangle
def get_uvmlogin_uids():
    s = sets.Set([0])

    try:
        for username in grp.getgrnam('uvmlogin')[3]:
            try:
                s.add(pwd.getpwnam(username)[2])
            except:
                apache.log_error('bad user %s' % username)
    except:
        apache.log_error('could not get group info')

    return s
예제 #40
0
def handler(req):
    opts = req.get_options()
    try:
        factory = opts['quixote-publisher-factory']
    except KeyError:
        apache.log_error('quixote-publisher-factory setting required')
        return apache.HTTP_INTERNAL_SERVER_ERROR
    pub = name2publisher.get(factory)
    if pub is None:
        factory_fcn = import_object(factory)
        pub = factory_fcn()
        name2publisher[factory] = pub
    return run(pub, req)
예제 #41
0
def handler(req):
    opts = req.get_options()
    try:
        factory = opts['quixote-publisher-factory']
    except KeyError:
        apache.log_error('quixote-publisher-factory setting required')
        return apache.HTTP_INTERNAL_SERVER_ERROR
    pub = name2publisher.get(factory)
    if pub is None:
        factory_fcn = import_object(factory)
        pub = factory_fcn()
        name2publisher[factory] = pub
    return run(pub, req)
예제 #42
0
파일: uvmlogin.py 프로젝트: rjt/untangle
def get_uvmlogin_uids():
    s = sets.Set([0])

    try:
        for username in grp.getgrnam('uvmlogin')[3]:
            try:
                s.add(pwd.getpwnam(username)[2])
            except:
                apache.log_error('bad user %s' % username)
    except:
        apache.log_error('could not get group info')

    return s
예제 #43
0
def getSen(uid):
    db_file = os.path.join(BASE_DIR, DB_NAME)
    db_conn = getDbConn()
    c = db_conn.cursor()
    apache.log_error("get_sen uid = %s!"%uid, apache.APLOG_WARNING)
    c.execute('select sen_id,sen_txt from senDB where sen_id not in (select sen_id from recDB where user_id = %s) limit 1;' % uid)
    rec = c.fetchall()
    if len(rec) == 0:
        result = 'sen_id=0'
    else:
        sen_id, sen_txt = rec[0]
        apache.log_error("f**k txt = %s!"%sen_txt.decode('utf-8'), apache.APLOG_WARNING)
        result = u'sen_id=%s&sen_txt=%s'%(sen_id, sen_txt.decode('utf-8'))
    return result
예제 #44
0
파일: uvmlogin.py 프로젝트: rjt/untangle
def headerparserhandler(req):
    options = req.get_options()

    if options.has_key('Realm'):
        realm = options['Realm']
    else:
        apache.log_error('no realm specified')
        return apache.DECLINED

    sess = Session.Session(req, lock=0)
    sess.set_timeout(SESSION_TIMEOUT)

    sess.lock()

    username = session_user(sess, realm)

    if None == username and realm == 'Reports':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard' and not is_wizard_complete(
    ):
        username = '******'
        save_session_user(sess, realm, username)

    if None == username and is_local_process_uid_authorized(req):
        username = '******'
        log_login(req, username, True, True, None)
        save_session_user(sess, realm, username)

    sess.save()
    sess.unlock()

    if None != username:
        pw = base64.encodestring('%s' % username).strip()
        req.headers_in['Authorization'] = "BASIC % s" % pw
        req.notes['authorized'] = 'true'
        return apache.OK
    else:
        # we only do this as to not present a login screen when access
        # is restricted. a tomcat valve enforces this setting.
        if options.get('UseRemoteAccessSettings', 'no') == 'yes':
            http_enabled = get_uvm_settings_item('system',
                                                 'httpAdministrationAllowed')
            connection = req.connection

            (addr, port) = connection.local_addr
            apache.log_error('rjt: addr=%s  port=%s' % (str(addr), str(port)))
            apache.log_error('rjt: connection.remote_ip = %s' %
                             (str(connection.remote_ip)))
            if not re.match('127\.|\:\:1', connection.remote_ip):
                if port == 80 and not http_enabled:
                    return apache.HTTP_FORBIDDEN

        apache.log_error(
            'Auth failure [Username not specified]. Redirecting to auth page. (realm: %s)'
            % realm)
        login_redirect(req, realm)
예제 #45
0
def putSen(uid, sid, wav):
    db_file = os.path.join(BASE_DIR, DB_NAME)
    db_conn = getDbConn()
    c = db_conn.cursor()
    apache.log_error("put_sen uid = %s!"%uid, apache.APLOG_WARNING)
    c.execute('select fin from recDB where user_id = %s and sen_id = %s limit 1;'%(uid, sid))
    rec = c.fetchall()
    if len(rec) == 0:
        apache.log_error("not found record!", apache.APLOG_WARNING)
        c.execute('insert into recDB (user_id, sen_id, fin) values (%s, %s, "Y");'%(uid, sid))
        db_conn.commit()
    else:
        fin = rec[0]
        if fin == 'Y':
            apache.log_error("record exist already!", apache.APLOG_ERR)
            return '录音已存在'
        else:
            c.execute('update recDB set FIN = "Y" where user_id = %s and sen_id = %s;'%(uid, sid))
            db_conn.commit()
    wav_dir = os.path.join(BASE_DIR, 'voices/%s/'%uid)
    try:
        os.mkdir(wav_dir)
    except:
        pass
    on = os.path.join(wav_dir, '%s_%s.wav'%(formatId(uid), formatId(sid)))
    #on = os.path.join(wav_dir, '%s.wav'%uid)
    try:
        of = open(on, 'w')
        of.write(wav)
        of.close()
    except:
        apache.log_error(str(on), apache.APLOG_WARNING)
        
    return '上传成功!'
예제 #46
0
파일: index.py 프로젝트: wujcheng/cobbler
def authenhandler(req):
    """
    Validates that username/password are a valid combination, but does
    not check access levels.
    """

    my_pw = req.get_basic_auth_pw()
    my_user = req.user
    my_uri = req.uri

    try:
        token = xmlrpc_server.login(my_user, my_pw)
    except Exception, e:
        apache.log_error(str(e))
        return apache.HTTP_UNAUTHORIZED
예제 #47
0
파일: index.py 프로젝트: 77720616/cobbler
def authenhandler(req):

    """
    Validates that username/password are a valid combination, but does
    not check access levels.
    """

    my_pw = req.get_basic_auth_pw()
    my_user = req.user
    my_uri = req.uri

    try:
        token = xmlrpc_server.login(my_user,my_pw)
    except Exception, e:
        apache.log_error(str(e))
        return apache.HTTP_UNAUTHORIZED
예제 #48
0
    def handleException(self, req):
        import traceback

        apache.log_error('WebKit mod_python: Error while responding to request\n')
        apache.log_error('Python exception:\n')
        traceback.print_exc(file=sys.stderr)

        output = traceback.format_exception(*sys.exc_info())
        output = ''.join(output)
        output = output.replace('&', '&amp;'
            ).replace('<', '&lt;').replace('>', '&gt;')
        req.write('''
<html><body>
<p><pre>ERROR

%s</pre>
</body></html>\n''' % output)
예제 #49
0
    def handleException(self, req):
        import traceback

        apache.log_error('WebKit mod_python: Error while responding to request\n')
        apache.log_error('Python exception:\n')
        traceback.print_exc(file=sys.stderr)

        output = traceback.format_exception(*sys.exc_info())
        output = ''.join(output)
        output = output.replace('&', '&amp;'
            ).replace('<', '&lt;').replace('>', '&gt;')
        req.write('''
<html><body>
<p><pre>ERROR

%s</pre>
</body></html>\n''' % output)
예제 #50
0
def log_failed_login(request, username=None):
    '''
    This is not a decorator, but it is called from the log_failed_logins
    decorator. If you're doing some custom kind of authentication, you
    may call this on login failure.
    '''
    if username is None:
        username = request.POST.get('username', '/unset/')
    # For apache2 with mod-wsgi, we get this in the global
    # (non-site-specific) error.log:
    # [Sun Feb 27 16:12:29 2011] [error] THE_MESSAGE
    # The ILLEGAL_RE makes sure no improper characters get mixed in into
    # the message which would make it harder to parse.
    xff = ILLEGAL_RE.sub('', request.META.get('HTTP_X_FORWARDED_FOR', ''))
    if xff:
        xff = ', X-Forwarded-For: %s' % (xff,)
    msg = (
        u'[django] Failed login for %(username)s '
        u'from %(address)s port %(port)s (Host: %(host)s%(xff)s)\n'
    ) % {
        'username': ILLEGAL_RE.sub('?', username) or '/unset/',
        'address': request.META.get('REMOTE_ADDR', '/unset/'),
        'port': request.META.get('REMOTE_PORT', '/unset/'),
        'host': ILLEGAL_RE.sub('?', request.META.get('HTTP_HOST', '/unset/')),
        'xff': xff,
    }

    # Always use syslog. You should be checking auth.log
    # anyway for failed ssh logins. fail2ban has issues
    # with the uwsgi log which does not set timestamps on
    # every message.
    syslog.openlog(logoption=(syslog.LOG_PID | syslog.LOG_NDELAY),
                   facility=syslog.LOG_AUTH)
    syslog.syslog(syslog.LOG_WARNING, msg.encode('utf-8')[0:-1])  # strip LF

    # These log messages are here for further debugging and
    # backwards compatibility.
    if request.META.get('SERVER_SOFTWARE') == 'mod_python':
        from mod_python import apache
        apache.log_error(msg.encode('utf-8')[0:-1])  # strip LF
    elif sys.argv[1:2] != ['test']:  # no output during test runs
        # We could check for 'uwsgi.version' in request.META
        # and add strftime('%c'), but that log confuses
        # fail2ban so we won't bother.
        sys.stderr.write(msg.encode('utf-8'))
        sys.stderr.flush()  # mod_python needs this, others might too
예제 #51
0
def dictVersion(req, name, lang, md5sum):
    result = {k_SUCCESS: True}
    if not name.endswith(k_suffix): name += k_suffix
    dictSums = getDictSums()
    path = lang + "/" + name
    if not path in dictSums:
        sums = md5Checksums(dictSums, path)
        if sums:
            dictSums[path] = sums
            s_shelf[k_SUMS] = dictSums
    if path in dictSums:
        if not md5sum in dictSums[path]:
            result[k_URL] = k_urlbase + "/and_wordlists/" + path
    else:
        apache.log_error(path + " not known")
    closeShelf()
    return json.dumps(result)
예제 #52
0
파일: uvmlogin.py 프로젝트: rjt/untangle
def headerparserhandler(req):
    options = req.get_options()

    if options.has_key('Realm'):
        realm = options['Realm']
    else:
        apache.log_error('no realm specified')
        return apache.DECLINED

    sess = Session.Session(req, lock=0)
    sess.set_timeout(SESSION_TIMEOUT)

    sess.lock()

    username = session_user(sess, realm)

    if None == username and realm == 'Reports':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard' and not is_wizard_complete():
        username = '******'
        save_session_user(sess, realm, username)

    if None == username and is_local_process_uid_authorized(req):
        username = '******'
        log_login(req, username, True, True, None)
        save_session_user(sess, realm, username)

    sess.save()
    sess.unlock()

    if None != username:
        pw = base64.encodestring('%s' % username).strip()
        req.headers_in['Authorization'] = "BASIC % s" % pw
        req.notes['authorized'] = 'true'
        return apache.OK
    else:
        # we only do this as to not present a login screen when access
        # is restricted. a tomcat valve enforces this setting.
        if options.get('UseRemoteAccessSettings', 'no') == 'yes':
            http_enabled = get_uvm_settings_item('system','httpAdministrationAllowed')
            connection = req.connection

            (addr, port) = connection.local_addr
            apache.log_error('rjt: addr=%s  port=%s' % (str(addr), str(port)))
            apache.log_error('rjt: connection.remote_ip = %s' % (str(connection.remote_ip)))
            if not re.match('127\.|\:\:1', connection.remote_ip):
                if port == 80 and not http_enabled:
                    return apache.HTTP_FORBIDDEN

        apache.log_error('Auth failure [Username not specified]. Redirecting to auth page. (realm: %s)' % realm)
        login_redirect(req, realm)
예제 #53
0
def is_local_process_uid_authorized(req):
    (remote_ip, remote_port) = req.connection.remote_addr

    if remote_ip != "127.0.0.1":
        return False

    # This determines the PID of the connecting process
    # and determines if it is from a process who is owned by root
    # or a user in uvm_login group. If so, auto-authenticate it.
    uids = get_uvmlogin_uids()

    q = remote_ip.split(".")
    q.reverse()
    n = reduce(lambda a, b: long(a) * 256 + long(b), q)
    hexaddr = "%08X" % n
    hexport = "%04X" % remote_port

    # We have to attempt to read /proc/net/tcp several times.
    # This file is not immediately updated synchronously, so we must read it a few times until we find the socket in an established state
    uid = None
    for count in range(0,5):
        try:
            infile = open("/proc/net/tcp", "r")
            # for l in infile.read(500000).splitlines():
            for l in infile.readlines():
                a = l.split()
                if len(a) <= 8:
                    continue

                p = a[1].split(':')
                if len(p) != 2:
                    continue

                if p[0] == hexaddr and p[1] == hexport:
                    try:
                        uid = int(a[7])
                        state = a[3]

                        # If socket state == established
                        if state == "01":
                            # If userid is in list of authorized userids
                            if uid in uids:
                                apache.log_error('UID %s authorized as localadmin on via %s:%s' % (str(uid), str(remote_ip), str(remote_port)))
                                # apache.log_error('%s' % (l))
                                return True
                            else:
                                apache.log_error('UID %s NOT authorized on via %s:%s' % (str(uid), str(remote_ip), str(remote_port)))
                                # apache.log_error('%s' % (l))
                                return False
                    except Exception,e:
                        apache.log_error('Bad line in /proc/net/tcp: %s: %s' % (line, traceback.format_exc(e)))

        except Exception,e:
            apache.log_error('Exception reading /proc/net/tcp: %s' % traceback.format_exc(e))
        finally:
예제 #54
0
def is_local_process_uid_authorized(req):
    (remote_ip, remote_port) = req.connection.remote_addr

    if remote_ip != "127.0.0.1":
        return False

    # This determines the PID of the connecting process
    # and determines if it is from a process who is owned by root
    # or a user in uvm_login group. If so, auto-authenticate it.
    uids = get_uvmlogin_uids()

    q = remote_ip.split(".")
    q.reverse()
    n = reduce(lambda a, b: long(a) * 256 + long(b), q)
    hexaddr = "%08X" % n
    hexport = "%04X" % remote_port

    # We have to attempt to read /proc/net/tcp several times.
    # This file is not immediately updated synchronously, so we must read it a few times until we find the socket in an established state
    uid = None
    for count in range(0,5):
        try:
            infile = open('/proc/net/tcp', 'r')
            # for l in infile.read(500000).splitlines():
            for l in infile.readlines():
                a = l.split()
                if len(a) <= 8:
                    continue

                p = a[1].split(':')
                if len(p) != 2:
                    continue

                if p[0] == hexaddr and p[1] == hexport:
                    try:
                        uid = int(a[7])
                        state = a[3]
                        
                        # If socket state == established
                        if state == "01":
                            # If userid is in list of authorized userids
                            if uid in uids:
                                apache.log_error('UID %s authorized as localadmin on via %s:%s' % (str(uid), str(remote_ip), str(remote_port)))
                                # apache.log_error('%s' % (l))
                                return True
                            else:
                                apache.log_error('UID %s NOT authorized on via %s:%s' % (str(uid), str(remote_ip), str(remote_port)))
                                # apache.log_error('%s' % (l))
                                return False
                    except Exception,e:
                        apache.log_error('Bad line in /proc/net/tcp: %s: %s' % (line, traceback.format_exc(e)))

        except Exception,e:
            apache.log_error('Exception reading /proc/net/tcp: %s' % traceback.format_exc(e))
        finally:
예제 #55
0
def curVersion(req, name, avers=41, gvers=None, installer=None):
    global k_versions
    result = {k_SUCCESS: True}
    if apacheAvailable:
        apache.log_error('IP address of requester is %s' %
                         req.get_remote_host(apache.REMOTE_NAME))

    apache.log_error("name: %s; avers: %s; installer: %s; gvers: %s" %
                     (name, avers, installer, gvers))
    if name in k_versions:
        versions = k_versions[name]
        if versions[k_AVERS] > int(avers):
            apache.log_error(avers + " is old")
            result[k_URL] = k_urlbase + '/' + versions[k_URL]
        else:
            apache.log_error(name + " is up-to-date")
    else:
        apache.log_error('Error: bad name ' + name)
    return json.dumps(result)
예제 #56
0
def index(req, repo=None, version="0.0.0", OS="None"):
    if not repo:
        repolist = ""
        desc = "Download " + " ".join([
            repo["name"]
            for repo in lib.get_config("Repositories", "Downloads")
        ])
        for repo in lib.get_config("Repositories", "Downloads"):
            try:
                repolist += _snippet_for_repo(None, repo)
            except Exception as e:
                apache.log_error(str(e))
        return lib.respond(
            req, "<div class='news'>" + repolist + "<br/><br/></div>",
            "Downloads", "Downloads", desc, module_info())
    else:
        repository = None
        for entry in lib.get_config("Repositories", "Downloads"):
            if entry["repo"] == repo:
                repository = entry
                break
        else:
            return lib.e404(req, "Could not find a matching repository.",
                            module_info())
        try:
            ver = _latest_ver(repo=repository)
        except Exception as e:
            apache.log_error(traceback.format_exc())
            return lib.e404(
                req,
                "Repository corrupt or wrong configuration, please contact the administrator.",
                module_info())
        if version == ver:
            return lib.respond(
                req, "You're already running the lastest version of %s." %
                repository["name"], "Downloads", "Downloads", "Updater",
                module_info())
        else:
            return lib.respond(req, _snippet_for_repo(repo=repository),
                               "Downloads",
                               "Downloads", "Download %s" % repository["name"],
                               module_info())
예제 #57
0
def md5Checksums(sums, filePath):
    if not filePath.endswith(k_suffix): filePath += k_suffix
    if filePath in sums:
        result = sums[filePath]
    else:
        # logging.debug( "opening %s" % (k_filebase + "and_wordlists/" + filePath))
        try:
            file = open(k_filebase + "and_wordlists/" + filePath, 'rb')
            md5 = hashlib.md5()
            while True:
                buffer = file.read(128)
                if not buffer: break
                md5.update(buffer)

            sums[filePath] = [md5.hexdigest(), getInternalSum(filePath)]
            apache.log_error("figured sum for %s: %s" %
                             (filePath, sums[filePath]))
            result = sums[filePath]
        except:
            # apache.log_error( "Unexpected error: " + sys.exc_info()[0] )
            result = None
    return result
예제 #58
0
파일: uvmlogin.py 프로젝트: rjt/untangle
def is_local_process_uid_authorized(req):
    (remote_ip, remote_port) = req.connection.remote_addr

    if remote_ip != "127.0.0.1": 
        apache.log_error('rjt: IPv6 has ::1 but this IS NOT CHECKED', apache.APLOG_EMERG, req.server)
        return False

    # This determines the PID of the connecting process
    # and determines if it is from a process who is owned by root
    # or a user in uvmlogin group. If so, auto-authenticate it.
    uids = get_uvmlogin_uids()

    q = remote_ip.split(".")
    q.reverse()
    n = reduce(lambda a, b: long(a) * 256 + long(b), q)
    hexaddr = "%08X" % n
    hexport = "%04X" % remote_port

    # We have to attempt to read /proc/net/tcp several times.
    # There is some race condition in the kernel and sometimes the socket we are looking for will not show up on the first read
    # This loop hack appears to "fix" the issue as it always shows up on the second read if the first fails.
    #
    # Also sometimes /proc/net/tcp reports the incorrect UID. 
    # As a result, we must also try again if the UID is not authorized
    uid = None
    for count in range(0,5):
        # if count > 0:
        #     apache.log_error('Failed to find/authorize UID [%s, %s:%s], attempting again... (try: %i)' % ( str(uid), str(remote_ip), str(remote_port), (count+1) ) )
        try:
            infile = open('/proc/net/tcp', 'r')
            for l in infile.readlines():
                a = l.split()
                if len(a) <= 2:
                    continue

                p = a[1].split(':')
                if len(p) != 2:
                    continue

                if p[0] == hexaddr and p[1] == hexport:
                    try:
                        uid = int(a[7])
                        
                        # Found the UID
                        # if its in the list of enabled UIDs
                        if uid in uids:
                            return True
                    except:
                        apache.log_error('Bad UID: %s' % a[7])

        except Exception,e:
            apache.log_error('Exception reading /proc/net/tcp: %s' % traceback.format_exc(e))
        finally: