def describe(req): conditions = util.parse_qs(req.args) key = conditions["userkey"][0] pairs = server.Describe(key) def mkdescriptor(pair): prop, val = pair mkvallink = mkvallinker("", prop) formattedval = "|".join([mkvallink(v) for v in val.split(DB_DELIM)]) format = "<input name='%s' value='%s' type='checkbox'/>%s = %s<br><br>" return format % (prop, val, prop, formattedval) body = transform(pairs, "", mkdescriptor) format = ''' <table> <tr><td valign='top'>All descriptors for resource %s<p></td></tr> <tr height=1 bgcolor=#0000FF><td/></tr> <tr height=10><td/></tr> </table> <form action='showprops'> Find properties for resources matching checked descriptors: <input type='submit' value='Go'/> <p/> %s </form> <div style="float:right"><a class=filelink href='getfile?userkey=%s'><i>%s</i></a></div> ''' return makepage(format % (key, body, key, "Show Resource"))
def get_zip(req, db): req.content_type = "application/zip" args = util.parse_qs(req.args) txt = db.get_zip(args['package'][0], args['branch'][0], int(args['revision'][0])) req.write(txt) return apache.OK
def get_wrap(req, db): req.content_type = "text/plain" args = util.parse_qs(req.args) txt = db.get_wrap(args['package'][0], args['branch'][0], int(args['revision'][0])) req.write(txt) return apache.OK
def handler(req): # Get URL paramaters from apache web server as dictionary url = util.parse_qs(req.parsed_uri[apache.URI_QUERY]) # Each element in this dict is actually an array, just want the first qdict = {} for key in url: qdict[key] = url[key][0] # Build an aireq from the args, and call the proper AI aireq = AiRequest(qdict) if aireq.ai == 'lookahead': airesp = AiLookahead(aireq) elif aireq.ai == 'quality': airesp = AiQuality(aireq) elif aireq.ai == 'score': airesp = AiScore(aireq) elif aireq.ai == 'corner' or aireq.ai == 'ul': airesp = AiCorner(aireq) elif aireq.ai == 'left': airesp = AiLeft(aireq) else: airesp = AiRand(aireq) # Write the response back to the game req.content_type = 'text/text' req.send_http_header() req.write(airesp.dir + "\n" + airesp.msg + "\n") return apache.OK
def handler(req): '''this is sort of main(char args[]) in C -- req is the request object''' global debug #refer to the global instance session = Session.Session(req); try: if session.is_new(): session['user_name'] = req. session['type'] session['waypoint_info'] session['uid'], session['wordid'] req.content_type = "text/html"; query_string = util.parse_qs(req.parsed_uri[7]); req.write(str(query_string)); sensorName = query_string['sensorName'][0]; if debug: req.write("Sensor = " + sensorName); senseString = query_string['q'][0]; #dynamic calls implemented for the first time in history of SICSR! if (len(q.strip())) == 0: prepareandsendResponse('Error: You need to enter something!'); else: call = "responseDict = %s(req,'%s')" % (sensorName,senseString); exec(call); #call the right function and stores the response in responseList; req.write("You said %s and the response is %s" % senseString, responseList ); return apache.OK;
def GetPostValueTable(req): ls = req.headers_in.get('Content-Length') if ls: from mod_python import util post_qs = req.read(int(ls)) return util.parse_qs(post_qs, 1) else: return {}
def getConditions(req): if not req.args: return None, [] else: args = util.parse_qs(req.args) conditions = [(p, v) for (p, vs) in args.items() for v in vs if p != "prop"] prop = args.get("prop", [None])[0] return prop, conditions
def getfile(req): conditions = util.parse_qs(req.args) path = conditions["userkey"][0] root, ext = os.path.splitext(path) content = server.GetFile(path) if ext == ".gif": req.content_type = "image/gif" return content.data
def handler(req): req.log_error('handler') req.content_type = 'text/text' req.send_http_header() qs = req.parsed_uri[apache.URI_QUERY] pr = util.parse_qs(qs) board = pr['board'][0].split(",") score = pr['score'][0] move = ai(board, score) req.write(move) return apache.OK
def __init__(self, req, virtualBucket=False): self.req = req self.bucket = self.key = self.user = self.accesskey = self.signature = self.stringToSign = self.computedSig = None self.isUserAdmin = False self.subresources = {} self.__writeBuffer = '' self.virtualBucket = False #Query string digest if self.req.args: self.subresources = util.parse_qs(self.req.args, True) #URI digest basehost = Config.get('server', 'hostname') if self.req.hostname == basehost: uriDigestResults = self.uriDigest(req.uri) self.bucket = uriDigestResults.get('bucket') self.key = uriDigestResults.get('key') else: splitHost = self.req.hostname.split("." + basehost) if len(splitHost) == 2: uriDigestResults = self.uriDigest(splitHost[0] + '/' + req.uri) self.bucket = uriDigestResults.get('bucket') self.key = uriDigestResults.get('key') self.virtualBucket = True else: self.req.write("HOST: " + self.req.hostname + "\r\n") raise Exception, 'wrong hostname?' #custom header table self.customHeaderPrefix = Config.get('common', 'customHeaderPrefix').lower() self.customHeaderTable = {} for tag, val in self.req.headers_in.iteritems(): if tag.lower().startswith(self.customHeaderPrefix): self.customHeaderTable[tag.lower()[len(self.customHeaderPrefix):]] = val #authenticate -- must happen after custom header table is created self.accesskey, self.signature = self.__getAccessKeyAndSignature() if self.accesskey: self.stringToSign = self.__buildStringToSign() self.user, self.isUserAdmin, self.computedSig = getUser(self.signature, self.accesskey, self.stringToSign) #Check date #check customDateHeader then date header if 'signature' in self.subresources: self.req.headers_out['Signature'] = str(self.computedSig) self.write(str(self.computedSig) + "\r\n") self.write(str(self.stringToSign) + "\r\n") self.send()
def getstats(req, name, command): # we expect two commands: # sum # list # and two [optional] args - start and end start, end = None, None if req.args: qs = util.parse_qs(req.args) if qs.has_key('start'): start = qs['start'][0] if qs.has_key('end'): end = qs['end'][0] result = vsmon.report_sum(name, start, end) lj = 15 req.write('%s%s\n' % ('name:'.ljust(15), name)) for s in [('start', time.strftime('(%Y-%m-%d %H:%M:%S %Z)', time.localtime(result['start']))), ('end', time.strftime('(%Y-%m-%d %H:%M:%S %Z)', time.localtime(result['end']))), ('step', '(secs)'), ('steps', ''), ('ticks', '(cpu ticks)'), ('vm', '(mem tokens)'), ('rss', '(mem tokens)'), ('in', '(bytes)'), ('out', '(bytes)'), ('disk', '(disk tokens)')]: req.write('%s%s %s\n' % ((s[0]+':').ljust(lj), result[s[0]], s[1])) req.write('\n\n') req.write('1 mem token = 1 average KB over 1 minute interval\n') req.write('1 disk token = 1 average KB over 1 minute interval\n') return apache.OK
def getstats(req, name, command): # we expect two commands: # sum # list # and two [optional] args - start and end start, end = None, None if req.args: qs = util.parse_qs(req.args) if qs.has_key('start'): start = qs['start'][0] if qs.has_key('end'): end = qs['end'][0] result = vsmon.report_sum(name, start, end) lj = 15 req.write('%s%s\n' % ('name:'.ljust(15), name)) for s in [('start', time.strftime('(%Y-%m-%d %H:%M:%S %Z)', time.localtime(result['start']))), ('end', time.strftime('(%Y-%m-%d %H:%M:%S %Z)', time.localtime(result['end']))), ('step', '(secs)'), ('steps', ''), ('ticks', '(cpu ticks)'), ('vm', '(mem tokens)'), ('rss', '(mem tokens)'), ('in', '(bytes)'), ('out', '(bytes)'), ('disk', '(disk tokens)')]: req.write('%s%s %s\n' % ((s[0] + ':').ljust(lj), result[s[0]], s[1])) req.write('\n\n') req.write('1 mem token = 1 average KB over 1 minute interval\n') req.write('1 disk token = 1 average KB over 1 minute interval\n') return apache.OK
def graph(req, name, command): if not req.args: return error(req, 'Not sure what you mean') qargs = util.parse_qs(req.args) if not qargs.has_key('s'): return error(req, 'Where do I start?') start = '-'+qargs['s'][0] # exclude these vps's exclude = [] if qargs.has_key('exclude'): exclude = qargs['exclude'][0].split() # limit to only these vps's limit = [] if qargs.has_key('limit'): limit = qargs['limit'][0].split() width = 600 if qargs.has_key('w'): width = int(qargs['w'][0]) height = 400 if qargs.has_key('h'): height = int(qargs['h'][0]) # how many days back? secs = abs(int(start)) if secs < 60*60*24: # we're talking hours title = 'last %d hours' % (secs/(60*60)) else: title = 'last %d days' % (secs/(60*60*24)) if command in ['bwidth', 'mem']: # here we need to draw a nice little graph.... tfile, tpath = tempfile.mkstemp('.gif', 'oh') os.close(tfile) args = [tpath, '--start', start, '--title', title, '-w', str(width), '-h', str(height), '-c', 'SHADEB#FFFFFF', '-c', 'SHADEA#FFFFFF', '-l', '0'] if qargs.has_key('l'): args.append('-g') # no legend # list vservers vservers = vsutil.list_vservers() keys = vservers.keys() # assign colors colors = {} ci = 0 for vs in keys: colors[vs.replace('-', '')] = COLORS[ci] ci += 1 # process limit and exclude if limit: keys = [k for k in keys if k in limit] keys = [k for k in keys if k not in exclude] # we only have so many colors if len(keys) > len(COLORS): return error(req, 'Not enough colors for VPSs, exclude some:\n%s' % `keys`) keys.sort() for vs in keys: rrd = os.path.join(cfg.VAR_DB_OPENVPS, 'vsmon/%s.rrd' % vs) vs = vs.replace('-', '') # rrdtool does not like dashes if command == 'bwidth': args = args + [ 'DEF:%s_in=%s:vs_in:AVERAGE' % (vs, rrd), 'DEF:%s_out=%s:vs_out:AVERAGE' % (vs, rrd), 'CDEF:%s_inb=%s_in,-8,*' % (vs, vs), 'CDEF:%s_outb=%s_out,8,*' % (vs, vs) ] elif command == 'mem': args = args + [ 'DEF:%s_vm=%s:vs_vm:AVERAGE' % (vs, rrd), 'DEF:%s_rss=%s:vs_rss:AVERAGE' % (vs, rrd), 'CDEF:%s_vmb=%s_vm,1024,*' % (vs, vs), 'CDEF:%s_rssb=%s_rss,1024,*' % (vs, vs), 'CDEF:%s_rssbg=%s_rss,-1024,*' % (vs, vs), ] if command == 'bwidth': # incoming vs = keys[0].replace('-', '') args = args + [ 'AREA:%s_outb#%s:%s bps out' % (vs, colors[vs], vs.ljust(10)), 'GPRINT:%s_inb:MAX:Max IN\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_inb:AVERAGE:Avg IN\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_outb:MAX:Max OUT\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_outb:AVERAGE:Avg OUT\\: %%8.2lf%%s\\n' % (vs, ) ] for vs in keys[1:]: vs = vs.replace('-', '') args = args + [ 'STACK:%s_outb#%s:%s bps out' % (vs, colors[vs], vs.ljust(10)), 'GPRINT:%s_inb:MAX:Max IN\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_inb:AVERAGE:Avg IN\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_outb:MAX:Max OUT\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_outb:AVERAGE:Avg OUT\\: %%8.2lf%%s\\n' % (vs, ) ] # outgoing keys.reverse() vs = keys[0].replace('-', '') args = args + [ 'AREA:%s_inb#%s::' % (vs, colors[vs]), ] for vs in keys[1:]: vs = vs.replace('-', '') args = args + [ 'STACK:%s_inb#%s::' % (vs, colors[vs]), ] elif command == 'mem': # rss (displayed at bottom) vs = keys[0].replace('-', '') args = args + [ 'AREA:%s_rssbg#%s:%s RSS bytes' % (vs, colors[vs], vs.ljust(10)), 'GPRINT:%s_rssb:MAX:Max RSS\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_rssb:AVERAGE:Avg RSS\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_vmb:MAX:Max VM\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_vmb:AVERAGE:Avg VM\\: %%8.2lf%%s\\n' % (vs, ) ] for vs in keys[1:]: vs = vs.replace('-', '') args = args + [ 'STACK:%s_rssbg#%s:%s RSS bytes' % (vs, colors[vs], vs.ljust(10)), 'GPRINT:%s_rssb:MAX:Max RSS\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_rssb:AVERAGE:Avg RSS\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_vmb:MAX:Max VM\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_vmb:AVERAGE:Avg VM\\: %%8.2lf%%s\\n' % (vs, ) ] # vm keys.reverse() vs = keys[0].replace('-', '') args = args + [ 'AREA:%s_vmb#%s::' % (vs, colors[vs]), ] for vs in keys[1:]: vs = vs.replace('-', '') args = args + [ 'STACK:%s_vmb#%s::' % (vs, colors[vs]), ] RRD.graph(*args) req.content_type = 'image/gif' req.sendfile(tpath) os.unlink(tpath) return apache.OK else: return error(req, 'request not understood')
def graph(req, name, command): if not req.args: return error(req, 'Not sure what you mean') qargs = util.parse_qs(req.args) if not qargs.has_key('s'): return error(req, 'Where do I start?') start = '-' + qargs['s'][0] # exclude these vps's exclude = [] if qargs.has_key('exclude'): exclude = qargs['exclude'][0].split() # limit to only these vps's limit = [] if qargs.has_key('limit'): limit = qargs['limit'][0].split() width = 600 if qargs.has_key('w'): width = int(qargs['w'][0]) height = 400 if qargs.has_key('h'): height = int(qargs['h'][0]) # how many days back? secs = abs(int(start)) if secs < 60 * 60 * 24: # we're talking hours title = 'last %d hours' % (secs / (60 * 60)) else: title = 'last %d days' % (secs / (60 * 60 * 24)) if command in ['bwidth', 'mem']: # here we need to draw a nice little graph.... tfile, tpath = tempfile.mkstemp('.gif', 'oh') os.close(tfile) args = [ tpath, '--start', start, '--title', title, '-w', str(width), '-h', str(height), '-c', 'SHADEB#FFFFFF', '-c', 'SHADEA#FFFFFF', '-l', '0' ] if qargs.has_key('l'): args.append('-g') # no legend # list vservers vservers = vsutil.list_vservers() keys = vservers.keys() # assign colors colors = {} ci = 0 for vs in keys: colors[vs.replace('-', '')] = COLORS[ci] ci += 1 # process limit and exclude if limit: keys = [k for k in keys if k in limit] keys = [k for k in keys if k not in exclude] # we only have so many colors if len(keys) > len(COLORS): return error( req, 'Not enough colors for VPSs, exclude some:\n%s' % ` keys `) keys.sort() for vs in keys: rrd = os.path.join(cfg.VAR_DB_OPENVPS, 'vsmon/%s.rrd' % vs) vs = vs.replace('-', '') # rrdtool does not like dashes if command == 'bwidth': args = args + [ 'DEF:%s_in=%s:vs_in:AVERAGE' % (vs, rrd), 'DEF:%s_out=%s:vs_out:AVERAGE' % (vs, rrd), 'CDEF:%s_inb=%s_in,-8,*' % (vs, vs), 'CDEF:%s_outb=%s_out,8,*' % (vs, vs) ] elif command == 'mem': args = args + [ 'DEF:%s_vm=%s:vs_vm:AVERAGE' % (vs, rrd), 'DEF:%s_rss=%s:vs_rss:AVERAGE' % (vs, rrd), 'CDEF:%s_vmb=%s_vm,1024,*' % (vs, vs), 'CDEF:%s_rssb=%s_rss,1024,*' % (vs, vs), 'CDEF:%s_rssbg=%s_rss,-1024,*' % (vs, vs), ] if command == 'bwidth': # incoming vs = keys[0].replace('-', '') args = args + [ 'AREA:%s_outb#%s:%s bps out' % (vs, colors[vs], vs.ljust(10)), 'GPRINT:%s_inb:MAX:Max IN\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_inb:AVERAGE:Avg IN\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_outb:MAX:Max OUT\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_outb:AVERAGE:Avg OUT\\: %%8.2lf%%s\\n' % (vs, ) ] for vs in keys[1:]: vs = vs.replace('-', '') args = args + [ 'STACK:%s_outb#%s:%s bps out' % (vs, colors[vs], vs.ljust(10)), 'GPRINT:%s_inb:MAX:Max IN\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_inb:AVERAGE:Avg IN\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_outb:MAX:Max OUT\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_outb:AVERAGE:Avg OUT\\: %%8.2lf%%s\\n' % (vs, ) ] # outgoing keys.reverse() vs = keys[0].replace('-', '') args = args + [ 'AREA:%s_inb#%s::' % (vs, colors[vs]), ] for vs in keys[1:]: vs = vs.replace('-', '') args = args + [ 'STACK:%s_inb#%s::' % (vs, colors[vs]), ] elif command == 'mem': # rss (displayed at bottom) vs = keys[0].replace('-', '') args = args + [ 'AREA:%s_rssbg#%s:%s RSS bytes' % (vs, colors[vs], vs.ljust(10)), 'GPRINT:%s_rssb:MAX:Max RSS\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_rssb:AVERAGE:Avg RSS\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_vmb:MAX:Max VM\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_vmb:AVERAGE:Avg VM\\: %%8.2lf%%s\\n' % (vs, ) ] for vs in keys[1:]: vs = vs.replace('-', '') args = args + [ 'STACK:%s_rssbg#%s:%s RSS bytes' % (vs, colors[vs], vs.ljust(10)), 'GPRINT:%s_rssb:MAX:Max RSS\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_rssb:AVERAGE:Avg RSS\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_vmb:MAX:Max VM\\: %%8.2lf%%s' % (vs, ), 'GPRINT:%s_vmb:AVERAGE:Avg VM\\: %%8.2lf%%s\\n' % (vs, ) ] # vm keys.reverse() vs = keys[0].replace('-', '') args = args + [ 'AREA:%s_vmb#%s::' % (vs, colors[vs]), ] for vs in keys[1:]: vs = vs.replace('-', '') args = args + [ 'STACK:%s_vmb#%s::' % (vs, colors[vs]), ] RRD.graph(*args) req.content_type = 'image/gif' req.sendfile(tpath) os.unlink(tpath) return apache.OK else: return error(req, 'request not understood')
def authenhandler(req): if req.main is not None: #defer to the main request's auth if getattr(req.main,'user',False): req.user = req.main.user if hasattr(req.main,'groups'): req.groups = req.main.groups elif req.connection.notes.has_key('groups'): req.groups = req.connection.notes['groups'] return apache.OK else: return apache.HTTP_UNAUTHORIZED q=req.parsed_uri[apache.URI_QUERY] args={} if q is not None: args=util.parse_qs(q) apache_options = req.get_options() #at least in modpy 3.1 if there is a '//' after the domain, # it might not parse args correctly, and won't find LOGOUT_ARG if args.has_key(LOGOUT_ARG): if apache_options.get('AnonymousPassthrough',False): req.user=apache_options.get('AnonymousUser',DEFAULT_USER_ANONYMOUS) req.groups=apache_options.get('AnonymousGroups','') req.connection.notes['user']=req.user req.connection.notes['groups']=req.groups try: session = Session.Session(req, lock=0) session.user=req.user session.groups=req.groups session.save() except: pass return apache.OK else: req.user="" req.groups="" if req.connection.notes.has_key('user'): del req.connection.notes['user'] req.status=apache.HTTP_UNAUTHORIZED try: session = Session.Session(req, lock=0) session.invalidate() except: pass util.redirect(req,LOGOUT_URL) anonymous_switch = apache_options.get('AnonymousPassthrough',False) \ and args.has_key(TICKET_ARG) anon_user = apache_options.get('AnonymousUser',DEFAULT_USER_ANONYMOUS) if req.connection.notes.has_key('user'): #HACK:session only works per-request, and hangs when called by the same connection req.user = req.connection.notes['user'] req.groups = req.connection.notes['groups'] if not (anonymous_switch and req.user == anon_user): return apache.OK if args.has_key(ALT_AUTH_ARG): #this 'feature' may be handy if we want to try basic auth too #but it might not work (UNTESTED) return apache.DECLINED session = Session.Session(req, lock=0) if session.is_new(): #since Session.Session() sends a pysid cookie #we need to make sure that there's an entry in the db #or mod_python won't always save the session data once auth'd session.save() if session.has_key('user'): req.user=session['user'] req.groups=session['groups'] req.connection.notes['user']=req.user req.connection.notes['groups']=getattr(req,'groups','') if not (anonymous_switch and req.user == anon_user): return apache.OK if args.has_key(TICKET_ARG): ticket=args[TICKET_ARG][-1] validation=validate_wind_ticket(ticket) if validation[0]: req.user = validation[1] if not req.user: return apache.HTTP_EXPECTATION_FAILED req.groups = ','.join(validation[2]) session['user'] = req.user session['groups'] = req.groups req.connection.notes['user']= req.user req.connection.notes['groups']= req.groups session.save() return apache.OK if apache_options.get('AnonymousPassthrough',False): req.user=apache_options.get('AnonymousUser',DEFAULT_USER_ANONYMOUS) req.groups=apache_options.get('AnonymousGroups','') req.connection.notes['user']=req.user req.connection.notes['groups']=req.groups session.user=req.user session.groups=req.groups session.save() return apache.OK else: redirectWind(req) #should never get here apache.log_error('unexpected condition') return apache.HTTP_UNAUTHORIZED
def __init__(self, req, config, redirect=None): # contient la requete fournie par apache self.requete = req # contient les parametres issus du fichier de conf self.conf = config # chargement du typeMime par defaut if self.conf.has_option("Prefs","typeMime"): self.typeMime = self.conf.get("Prefs","typeMime") else: self.typeMime = "text/plain" # on extrait du fichier demande le repertoire dans lequel on # travaille (le lien vers la feuille de style XSLT sera en # fonction de ce repertoire self.repertoireTravail = sre.match("(/.*/)", req.filename).group(0) self.session = {} self.variables = {} # chemin absolu de la racine du site self.base = self.conf.get("Chemins", "cheminBase") # chemin_relatif est le chemin vers la racine du site # a partir du repertoire du fichier demande self.cheminRelatif = "./" + ("../" * (self.repertoireTravail.count("/") - self.base.count("/") - 1)) if redirect==None: #le fichier demande est forcement un .html #on lui ote donc ce ".html" final self.fichierDemande = self.requete.filename[0:len(self.requete.filename)-5] # on charge la session self.session = Session.Session(req) self.session.load() # on charge les variables de requete HTTP # post est prioritaire par rapport a get get_args = "" if req.args != None: get_args = req.args post_args = req.read() self.variables = util.parse_qs(get_args) self.variables.update(util.parse_qs(post_args)) else: # une redirection a ete demandee par le handler self.repertoireTravail = self.base + "/" self.fichierDemande = self.base + "/" + redirect # code de retour HTTP (initialisation par defaut) self.codeRetour = apache.OK # indique si les donnees sont envoyees au fur et a mesure # ou tout d'un bloc self.stream = False # liste des fichiers XML statique a charger self.fichiersXML = [] # liste des noeuds XML a agreger self.noeudsXML = [] # dictionnaire des requetes SQL self.requetesSQL = {} # dictionnaire des resultats aux requetes SQL correspondantes self.resultatsSQL = {} # fichier XSLT a utiliser self.fichierXSLT = None # paramettres XSLT a envoyer a la moulinette XSLT self.parametresXSLT = {"chemin_relatif": "'%s'" % (self.cheminRelatif)} # nom de la balise racine du DOM self.racineXML = u"page" # tampon des donnees a envoyer self._resultat = [] # module de base de donnees API-DB utilise self.bdd = None # connexion active a la base de donnees self.connexion = None
def login(req, vserver_name, message=''): if req.method == 'POST': # someone is trying to login fs = util.FieldStorage(req) userid = fs.getfirst('userid') passwd = fs.getfirst('passwd') uri = fs.getfirst('uri') vservers = vsutil.list_vservers() if ((vserver_name == userid and vservers.has_key(vserver_name) and vds.checkpw(vserver_name, userid, passwd)) or # root (userid == SUPER and vds.checkpw('/', userid, passwd)) or # superuser (userid == cfg.PANEL_SUPERUSER and crypto.check_passwd_md5(passwd, cfg.PANEL_SUPERUSER_PW))): # plant the cookie key = _read_priv_key() cookie = RSASignedCookie.RSASignedCookie( 'openvps-user', "%d:%s" % (time.time(), userid), key) cookie.path = '/' Cookie.add_cookie(req, cookie) if uri and not uri.endswith('login'): util.redirect(req, str(uri)) else: util.redirect(req, '/admin/%s/status' % vserver_name) else: message = 'invalid login or password' # if we got here, either it's not a POST or login failed # it's possible that some qargs were passed in qargs = {} if req.args: qargs = util.parse_qs(req.args) if qargs.has_key('m'): if not message: if qargs['m'][0] == '1': message = 'please log in' elif qargs['m'][0] == '2': message = 'session time-out, please log in again' if qargs.has_key('url'): url = qargs['url'][0] else: url = req.uri body_tmpl = _tmpl_path('login_body.html') body_vars = {'message': message, 'url': url} vars = { 'global_menu': '', 'body': psp.PSP(req, body_tmpl, vars=body_vars), 'name': '' } p = psp.PSP(req, _tmpl_path('main_frame.html'), vars=vars) p.run() return apache.OK
def disk(req, name, params): if params.startswith('graph'): if not req.args: return error(req, 'Not sure what you mean') qargs = util.parse_qs(req.args) if not qargs.has_key('s'): return error(req, 'Where do I start?') start = '-' + qargs['s'][0] width = 484 height = 70 nolegend = '' if qargs.has_key('l'): nolegend = '-g' # no legend # how many days back? secs = abs(int(start)) if secs < 60 * 60 * 24: # we're talking hours title = 'last %d hours' % (secs / (60 * 60)) else: title = 'last %d days' % (secs / (60 * 60 * 24)) rrd = os.path.join(cfg.VAR_DB_OPENVPS, 'vsmon/%s.rrd' % name) tfile, tpath = tempfile.mkstemp('.gif', 'oh') os.close(tfile) args = [ tpath, '--start', start, '--title', title, '-w', str(width), '-h', str(height), '-c', 'SHADEB#FFFFFF', '-c', 'SHADEA#FFFFFF', '-l', '0', 'DEF:d=%s:vs_disk_b_used:AVERAGE' % rrd, 'CDEF:db=d,1024,*', 'AREA:db#4eee94:bytes used' ] if qargs.has_key('l'): args.append('-g') # no legend RRD.graph(*args) req.content_type = 'image/gif' req.sendfile(tpath) os.unlink(tpath) return apache.OK else: location = 'stats:disk' body_tmpl = _tmpl_path('disk_body.html') rrd = os.path.join(cfg.VAR_DB_OPENVPS, 'vsmon/%s.rrd' % name) data = _load_rrd_data(rrd, ['vs_disk_b_used']) body_vars = {'data': data} vars = { 'global_menu': _global_menu(req, name, location), 'body': psp.PSP(req, body_tmpl, vars=body_vars), 'name': name } p = psp.PSP(req, _tmpl_path('main_frame.html'), vars=vars) p.run() return apache.OK
def login(req, vserver_name, message=''): if req.method == 'POST': # someone is trying to login fs = util.FieldStorage(req) userid = fs.getfirst('userid') passwd = fs.getfirst('passwd') uri = fs.getfirst('uri') vservers = vsutil.list_vservers() if ((vserver_name == userid and vservers.has_key(vserver_name) and vds.checkpw(vserver_name, userid, passwd)) or # root (userid == SUPER and vds.checkpw('/', userid, passwd)) or # superuser (userid == cfg.PANEL_SUPERUSER and crypto.check_passwd_md5(passwd, cfg.PANEL_SUPERUSER_PW))): # plant the cookie key = _read_priv_key() cookie = RSASignedCookie.RSASignedCookie('openvps-user', "%d:%s" % (time.time(), userid), key) cookie.path = '/' Cookie.add_cookie(req, cookie) if uri and not uri.endswith('login'): util.redirect(req, str(uri)) else: util.redirect(req, '/admin/%s/status' % vserver_name) else: message = 'invalid login or password' # if we got here, either it's not a POST or login failed # it's possible that some qargs were passed in qargs = {} if req.args: qargs = util.parse_qs(req.args) if qargs.has_key('m'): if not message: if qargs['m'][0] == '1': message = 'please log in' elif qargs['m'][0] == '2': message = 'session time-out, please log in again' if qargs.has_key('url'): url = qargs['url'][0] else: url = req.uri body_tmpl = _tmpl_path('login_body.html') body_vars = {'message':message, 'url':url} vars = {'global_menu': '', 'body':psp.PSP(req, body_tmpl, vars=body_vars), 'name':''} p = psp.PSP(req, _tmpl_path('main_frame.html'), vars=vars) p.run() return apache.OK
def login(req, url=None, realm='Administrator', token=None): uvm_login.setup_gettext() options = req.get_options() args = util.parse_qs(req.args or '') error_msg = None if req.form.has_key('username') or req.form.has_key('password'): error_msg = '%s' % cgi.escape(_('Error: Username and Password do not match')) connection = req.connection (addr, port) = connection.local_addr is_local = re.match('127\.', connection.remote_ip) if connection.remote_ip == '::1': is_local = True if port == 80 and not get_uvm_settings_item('system','httpAdministrationAllowed') and not is_local: write_error_page(req, "Permission denied") return if token != None and get_uvm_settings_item('system','cloudEnabled'): if _valid_token(req, token): sess = Session.Session(req, lock=0) sess.lock() sess.set_timeout(uvm_login.SESSION_TIMEOUT) uvm_login.save_session_user(sess, realm, "token") sess.save() sess.unlock() if url == None: return apache.OK else: url = re.sub('[^A-Za-z0-9-_/.#?=]','',url) # sanitize input if req.form.has_key('fragment') and req.form['fragment'] != '': url = url + req.form['fragment'] util.redirect(req, url) return if req.form.has_key('username') and req.form.has_key('password'): username = req.form['username'] password = req.form['password'] # debug # req.log_error("User:Pass = %s %s" % (username,password)) if _valid_login(req, realm, username, password): sess = Session.Session(req, lock=0) sess.lock() sess.set_timeout(uvm_login.SESSION_TIMEOUT) uvm_login.save_session_user(sess, realm, username) sess.save() sess.unlock() if url == None: return apache.OK else: url = re.sub('[^A-Za-z0-9-_/.#?=]','',url) # sanitize input if req.form.has_key('fragment') and req.form['fragment'] != '': url = url + req.form['fragment'] util.redirect(req, url) return company_name = uvm_login.get_company_name() title = _("Administrator Login") # some i18n company_names cause exception here, so wrap to handle this # revert to "Administrator Login" if exception occurs try: title = cgi.escape(_("%s Administrator Login") % company_name) except: pass host = cgi.escape(req.hostname) _write_login_form(req, title, host, error_msg)
def disk(req, name, params): if params.startswith('graph'): if not req.args: return error(req, 'Not sure what you mean') qargs = util.parse_qs(req.args) if not qargs.has_key('s'): return error(req, 'Where do I start?') start = '-'+qargs['s'][0] width = 484 height = 70 nolegend = '' if qargs.has_key('l'): nolegend = '-g' # no legend # how many days back? secs = abs(int(start)) if secs < 60*60*24: # we're talking hours title = 'last %d hours' % (secs/(60*60)) else: title = 'last %d days' % (secs/(60*60*24)) rrd = os.path.join(cfg.VAR_DB_OPENVPS, 'vsmon/%s.rrd' % name) tfile, tpath = tempfile.mkstemp('.gif', 'oh') os.close(tfile) args = [tpath, '--start', start, '--title', title, '-w', str(width), '-h', str(height), '-c', 'SHADEB#FFFFFF', '-c', 'SHADEA#FFFFFF', '-l', '0', 'DEF:d=%s:vs_disk_b_used:AVERAGE' % rrd, 'CDEF:db=d,1024,*', 'AREA:db#4eee94:bytes used'] if qargs.has_key('l'): args.append('-g') # no legend RRD.graph(*args) req.content_type = 'image/gif' req.sendfile(tpath) os.unlink(tpath) return apache.OK else: location = 'stats:disk' body_tmpl = _tmpl_path('disk_body.html') rrd = os.path.join(cfg.VAR_DB_OPENVPS, 'vsmon/%s.rrd' % name) data = _load_rrd_data(rrd, ['vs_disk_b_used']) body_vars = {'data':data} vars = {'global_menu': _global_menu(req, name, location), 'body':psp.PSP(req, body_tmpl, vars=body_vars), 'name':name} p = psp.PSP(req, _tmpl_path('main_frame.html'), vars=vars) p.run() return apache.OK
def showvals(req): prop = "" offset = 0 limit = PAGESIZE if not req.args: conditions = [] else: args = util.parse_qs(req.args) prop = args.get("prop")[0] # throws key error if 'prop' not found sorted = args.get("sorted", [""])[0] offset = args.get("offset", [0])[0] limit = args.get("limit", [PAGESIZE])[0] arglst = [(p, v) for (p, vs) in args.items() for v in vs] conditions = [ (p, v) for (p, v) in arglst if p != "offset" and p != "limit" and p != "sorted" and p != "prop" ] realprop = unencode(prop) #query strings have a list of values for each keyword pairs = [(unencode(p), unencode(v)) for p, v in conditions] path = getSimplePath(req) result = server.PathValues(path, pairs, realprop, offset, limit, sorted) qs = '&'.join(['%s=%s' % (p, v) for p, v in conditions]) # returns a fuction for formatting values as links to ValidValue queries mklink = mkvallinker(qs, prop) def mkmultivallink(val): return ", ".join([mklink(v) for v in val.split(DB_DELIM)]) + "<br><br>\n" resultbody = transform(result, "", mkmultivallink) context = Context(conditions) format = ''' <table> <tr><td valign='top'>Values %s through %s of <b>%s</b>, for resources where <i>(%s)</i></td></tr> %s <tr><td>%s</td></tr> </table> ''' if not sorted and len(result) == PAGESIZE: navigation = '<tr><td>These results are just a sample. <a href="%s">Show all</a></td></tr><p>' navigation = navigation % ( "showvals?%s&sorted=true&prop=%s&offset=0&limit=%s" % (qs, prop, PAGESIZE), ) navigation += '<tr height=1 bgcolor=#0000FF><td/></tr>' elif not sorted and len(result) < PAGESIZE: navigation = '<tr height=1 bgcolor=#0000FF><td/></tr>' elif sorted: poff = max(0, int(offset) - PAGESIZE) noff = int(offset) + PAGESIZE backlink = '<a href="showvals?%s&sorted=true&prop=%s&offset=%s&limit=%s">%s - %s</a>' backlink = backlink % (qs, prop, poff, PAGESIZE, poff, poff + PAGESIZE - 1) fwrdlink = '<a href="showvals?%s&sorted=true&prop=%s&offset=%s&limit=%s">next %s</a>' fwrdlink = fwrdlink % (qs, prop, noff, PAGESIZE, PAGESIZE) if int(offset) == 0: backlink = '' if len(result) < PAGESIZE: fwrdlink = '' navigation = '<tr><td>%s %s</td></tr><p>' % ( backlink, fwrdlink) navigation += '<tr height=1 bgcolor=#0000FF><td/></tr>' else: navigation = '<tr height=1 bgcolor=#0000FF><td/></tr>' #body = html.grid(6, [mklink(r) for r in result]) tup = (offset, int(offset) + len(result), prop, context, navigation, resultbody) displaypath = getPath(req) return makeresultpage(format % tup, displaypath)
def login(req, url=None, realm='Administrator', token=None): uvm_login.setup_gettext() options = req.get_options() args = util.parse_qs(req.args or '') error_msg = None if req.form.has_key('username') or req.form.has_key('password'): error_msg = '%s' % cgi.escape( _('Error: Username and Password do not match')) connection = req.connection (addr, port) = connection.local_addr is_local = re.match('127\.', connection.remote_ip) if connection.remote_ip == '::1': is_local = True if port == 80 and not get_uvm_settings_item( 'system', 'httpAdministrationAllowed') and not is_local: write_error_page(req, "Permission denied") return if token != None and get_uvm_settings_item('system', 'cloudEnabled'): if _valid_token(req, token): sess = Session.Session(req, lock=0) sess.lock() sess.set_timeout(uvm_login.SESSION_TIMEOUT) uvm_login.save_session_user(sess, realm, "token") sess.save() sess.unlock() if url == None: return apache.OK else: url = re.sub('[^A-Za-z0-9-_/.#?=]', '', url) # sanitize input if req.form.has_key('fragment') and req.form['fragment'] != '': url = url + req.form['fragment'] util.redirect(req, url) return if req.form.has_key('username') and req.form.has_key('password'): username = req.form['username'] password = req.form['password'] # debug # req.log_error("User:Pass = %s %s" % (username,password)) if _valid_login(req, realm, username, password): sess = Session.Session(req, lock=0) sess.lock() sess.set_timeout(uvm_login.SESSION_TIMEOUT) uvm_login.save_session_user(sess, realm, username) sess.save() sess.unlock() if url == None: return apache.OK else: url = re.sub('[^A-Za-z0-9-_/.#?=]', '', url) # sanitize input if req.form.has_key('fragment') and req.form['fragment'] != '': url = url + req.form['fragment'] util.redirect(req, url) return company_name = uvm_login.get_company_name() title = _("Administrator Login") # some i18n company_names cause exception here, so wrap to handle this # revert to "Administrator Login" if exception occurs try: title = cgi.escape(_("%s Administrator Login") % company_name) except: pass host = cgi.escape(req.hostname) _write_login_form(req, title, host, error_msg)
def login(req, url=None, realm='Administrator'): uvmlogin.setup_gettext() options = req.get_options() args = util.parse_qs(req.args or '') strAuthLoginAdmin = '/auth/login?url=/setup/welcome.do&realm=Administrator' apache.log_error( 'rjt: These are really just informational messages, ' ' so i could acquaint myself with various http variables but did not want to spend time figuring out' ' how to set DEBUG so that APLOG_DEBUG or APLOG_INFO actually log something.', apache.APLOG_WARNING, req.server) apache.log_error( 'rjt: Some of the login pages are directly accessible, so safeguards are bypassed. ' 'This is real easy to test. Put the following string into your browser:', apache.APLOG_CRIT, req.server) strTestURL = 'http://' + req.hostname + strAuthLoginAdmin apache.log_error('rjt: ' + strTestURL, apache.APLOG_CRIT, req.server) apache.log_error( 'rjt: The following code provides a fix by redirecting to SSL when only http:.', apache.APLOG_WARNING, req.server) apache.log_error('rjt: req.server.port = %s' % (str(req.server.port)), apache.APLOG_WARNING, req.server) apache.log_error('rjt: req.interpreter = %s' % (str(req.interpreter)), apache.APLOG_WARNING, req.server) apache.log_error( 'rjt: apache.interpreter = %s' % (str(apache.interpreter)), apache.APLOG_WARNING, req.server) apache.log_error( 'rjt: http://modpython.org/live/current/doc-html/pythonapi.html#connection-object-mp-conn', apache.APLOG_WARNING, req.server) apache.log_error('rjt: req.server.names = %s' % (str(req.server.names)), apache.APLOG_WARNING, req.server) apache.log_error( 'rjt: req.server.wild_names = %s' % (str(req.server.wild_names)), apache.APLOG_WARNING, req.server) apache.log_error( 'rjt: req.server.server_hostname = %s' % (str(req.server.server_hostname)), apache.APLOG_WARNING, req.server) apache.log_error('rjt: req.hostname = %s' % (str(req.hostname)), apache.APLOG_WARNING, req.server) apache.log_error( 'rjt: req.server.is_virtual = %s' % (str(req.server.is_virtual)), apache.APLOG_WARNING, req.server) apache.log_error('rjt: req.is_https() = %s' % (str(req.is_https())), apache.APLOG_WARNING, req.server) login_url = cgi.escape(req.unparsed_uri) apache.log_error('rjt: login_url = %s' % (str(login_url)), apache.APLOG_WARNING, req.server) apache.log_error('rjt: req.unparsed_uri = %s' % (str(req.unparsed_uri)), apache.APLOG_WARNING, req.server) if 80 == req.server.port or not req.is_https(): apache.log_error('rjt: WHY EVER ASK FOR CREDENTIALS WITHOUT SSL?', apache.APLOG_ALERT, req.server) strURI = req.unparsed_uri (strAuthLogin) = strAuthLoginAdmin.rpartition( '&') #DUMP THE REALM FOR THOSE THAT ARE NOT ADMINS. strRedirect = 'https://' + req.hostname + strAuthLogin[ 0] #req.unparsed_uri apache.log_error('rjt: Attempting redirect to %s' % (str(strRedirect)), apache.APLOG_ALERT, req.server) util.redirect(req, location=strRedirect, permanent=True, text=" No passwords in the clear! ") elif req.is_https(): apache.log_error( 'rjt: req.is_https() = %s GREAT! PASSWORDS ARE NOW PROTECTED. YES.' % (str(req.is_https())), apache.APLOG_WARNING, req.server) if req.form.has_key('username') or req.form.has_key('password'): is_error = True else: is_error = False if req.form.has_key('username') and req.form.has_key('password'): username = req.form['username'] password = req.form['password'] # debug # assert False, ("User:Pass = %s %s" % (username,password)) if _valid_login(req, realm, username, password): sess = Session.Session(req) sess.set_timeout(uvmlogin.SESSION_TIMEOUT) uvmlogin.save_session_user(sess, realm, username) sess.save() sess.unlock() if url == None: return apache.OK else: util.redirect(req, url, text="Login Successfull") company_name = uvmlogin.get_company_name() title = _("Administrator Login") # some i18n company_names cause exception here, so wrap to handle this # revert to "Administrator Login" if exception occurs try: title = cgi.escape(_("%s Administrator Login") % company_name) except: pass host = cgi.escape(req.hostname) _write_login_form(req, title, host, is_error)