rem
stringlengths
1
322k
add
stringlengths
0
2.05M
context
stringlengths
4
228k
meta
stringlengths
156
215
debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`))
self._debug(NIGHTMARE, "matched rule %s on tag %s" % (`rule.title`, `tag`))
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" # give'em a chance to replace more than one attribute if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item continue else: break else: debug(NIGHTMARE, "HtmlFilter: put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.javascript: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.javascript: self.buf2data()
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
debug(NIGHTMARE, "HtmlFilter: put on buffer")
self._debug(NIGHTMARE, "put on buffer")
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" # give'em a chance to replace more than one attribute if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item continue else: break else: debug(NIGHTMARE, "HtmlFilter: put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.javascript: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.javascript: self.buf2data()
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
elif self.javascript:
elif self.js_filter:
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" # give'em a chance to replace more than one attribute if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item continue else: break else: debug(NIGHTMARE, "HtmlFilter: put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.javascript: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.javascript: self.buf2data()
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
if not self.rulestack and not self.javascript:
if not self.rulestack and not self.js_filter:
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" # give'em a chance to replace more than one attribute if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item continue else: break else: debug(NIGHTMARE, "HtmlFilter: put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.javascript: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.javascript: self.buf2data()
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
if self.javascript and tag=='script': self.jsEndElement(item) else: self.buf.append(item)
if self.js_filter and tag=='script': return self.jsEndElement(item) self.buf.append(item)
def endElement (self, tag): """We know the following: if a rule matches, it must be the one on the top of the stack. So we look only at the top rule.
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
self.jsEnv.attachListener(self)
self.js_env.attachListener(self)
def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" val = resolve_html_entities(attrs[name]) if not val: return self.jsEnv.attachListener(self) try: self.jsEnv.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.jsEnv.detachListener(self) res = self.popup_counter self.popup_counter = 0 return res
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
self.jsEnv.executeScriptAsFunction(val, 0.0)
self.js_env.executeScriptAsFunction(val, 0.0)
def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" val = resolve_html_entities(attrs[name]) if not val: return self.jsEnv.attachListener(self) try: self.jsEnv.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.jsEnv.detachListener(self) res = self.popup_counter self.popup_counter = 0 return res
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
self.jsEnv.detachListener(self)
self.js_env.detachListener(self)
def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" val = resolve_html_entities(attrs[name]) if not val: return self.jsEnv.attachListener(self) try: self.jsEnv.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.jsEnv.detachListener(self) res = self.popup_counter self.popup_counter = 0 return res
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
debug(HURT_ME_PLENTY, "JS: jsForm", `name`, `action`, `target`) self.jsEnv.addForm(name, action, target)
self._debug(HURT_ME_PLENTY, "jsForm", `name`, `action`, `target`) self.js_env.addForm(name, action, target)
def jsForm (self, name, action, target): """when hitting a (named) form, notify the JS engine about that""" if not name: return debug(HURT_ME_PLENTY, "JS: jsForm", `name`, `action`, `target`) self.jsEnv.addForm(name, action, target)
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
if not self.script: print >> sys.stderr, "empty JS src", url
if not self.js_script: print >> sys.stderr, "HtmlFilter[%d]: empty JS src"%self.level, url
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.script: print >> sys.stderr, "empty JS src", url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) self.buf.append([DATA, "<!--\n%s\n//-->"%self.script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.state = 'parse' self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`) else: debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
self.buf.append([DATA, "<!--\n%s\n//-->"%self.script])
if self.js_script.find("<!--")==-1: script = "<!--\n%s\n//-->"%self.js_script else: script = self.js_script self.buf.append([DATA, script])
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.script: print >> sys.stderr, "empty JS src", url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) self.buf.append([DATA, "<!--\n%s\n//-->"%self.script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.state = 'parse' self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`) else: debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`)
self.js_script = '' self._debug(NIGHTMARE, "switching back to parse with") self._debugbuf()
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.script: print >> sys.stderr, "empty JS src", url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) self.buf.append([DATA, "<!--\n%s\n//-->"%self.script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.state = 'parse' self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`) else: debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
self._debug(HURT_ME_PLENTY, "JS read", len(data), "<=", url) self.js_script += data
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.script: print >> sys.stderr, "empty JS src", url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) self.buf.append([DATA, "<!--\n%s\n//-->"%self.script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.state = 'parse' self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`) else: debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
debug(HURT_ME_PLENTY, "JS: jsScriptSrc", url, ver)
self._debug(HURT_ME_PLENTY, "JS jsScriptSrc", url, ver)
def jsScriptSrc (self, url, language): """Start a background download for <script src=""> tags""" assert self.state=='parse' ver = 0.0 if language: mo = re.search(r'(?i)javascript(?P<num>\d\.\d)', language) if mo: ver = float(mo.group('num')) url = urlparse.urljoin(self.url, url) debug(HURT_ME_PLENTY, "JS: jsScriptSrc", url, ver) self.state = 'wait' client = HttpProxyClient(self.jsScriptData, (url, ver)) ClientServerMatchmaker(client, "GET %s HTTP/1.1" % url, #request {}, #headers '', #content {'nofilter': None}, 'identity', # compress ) self.waited = "True"
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
def jsScript (self, script, ver): """execute given script with javascript version ver return True if the script generates any output, else False""" self.output_counter = 0 self.jsEnv.attachListener(self) self.jsfilter = HtmlFilter(self.rules, self.url, comments=self.comments, javascript=self.javascript) self.jsEnv.executeScript(script, ver) self.jsEnv.detachListener(self) if self.output_counter: self.jsfilter.flush() self.outbuf.write(self.jsfilter.flushbuf()) self.buf[-2:-2] = self.jsfilter.buf self.rulestack += self.jsfilter.rulestack self.jsfilter = None return self.popup_counter + self.output_counter def processData (self, data):
def jsScript (self, script, ver, item): """execute given script with javascript version ver""" self._debug(NIGHTMARE, "JS: jsScript", ver, `script`) assert self.state == 'parse' assert len(self.buf) >= 2 self.js_output = 0 self.js_env.attachListener(self) self.js_html = HtmlFilter(self.rules, self.url, comments=self.comments, javascript=self.js_filter, level=self.level+1) self.js_env.executeScript(script, ver) self.js_env.detachListener(self) self.jsEndScript(item) def jsEndScript (self, item): self._debug(NIGHTMARE, "JS: endScript") assert len(self.buf) >= 2 if self.js_output: try: self.js_html.feed('') self.js_html.flush() except FilterException: self.state = 'wait' self.waited = "True" make_timer(0.1, lambda : HtmlFilter.jsEndScript(self, item)) return self.js_html._debugbuf() assert not self.js_html.inbuf.getvalue() assert not self.js_html.waitbuf assert len(self.buf) >= 2 self.buf[-2:-2] = [[DATA, self.js_html.outbuf.getvalue()]]+self.js_html.buf self.js_html = None if (self.js_popup + self.js_output) > 0: del self.buf[-1] del self.buf[-1] else: self.buf.append(item) self._debug(NIGHTMARE, "JS: switching back to parse with") self._debugbuf() self.state = 'parse' def jsProcessData (self, data): """process data produced by document.write() JavaScript""" self._debug(NIGHTMARE, "JS: document.write", `data`) self.js_output += 1
def jsScript (self, script, ver): """execute given script with javascript version ver return True if the script generates any output, else False""" #debug(NIGHTMARE, "JS: jsScript", ver, `script`) self.output_counter = 0 self.jsEnv.attachListener(self) self.jsfilter = HtmlFilter(self.rules, self.url, comments=self.comments, javascript=self.javascript) self.jsEnv.executeScript(script, ver) self.jsEnv.detachListener(self) if self.output_counter: self.jsfilter.flush() self.outbuf.write(self.jsfilter.flushbuf()) self.buf[-2:-2] = self.jsfilter.buf self.rulestack += self.jsfilter.rulestack self.jsfilter = None return self.popup_counter + self.output_counter
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
self.output_counter += 1 self.jsfilter.feed(data) def processPopup (self): self.popup_counter += 1
self.js_html.feed(data) def jsProcessPopup (self): """process javascript popup""" self._debug(NIGHTMARE, "JS: popup") self.js_popup += 1
def processData (self, data): # parse recursively self.output_counter += 1 self.jsfilter.feed(data)
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
"""parse generated html for scripts return True if the script generates any output, else False"""
"""parse generated html for scripts"""
def jsEndElement (self, item): """parse generated html for scripts return True if the script generates any output, else False""" if len(self.buf)<2: return #assert len(self.buf)>=2 if self.buf[-1][0]!=DATA: # no data means we had <script></script> return if not (self.buf[-2][0]==STARTTAG and \ self.buf[-2][1]=='script'): # there was a <script src="..."> already return # get script data script = self.buf[-1][1].strip() # remove html comments if script.startswith("<!--"): i = script.find('\n') if i==-1: script = script[4:] else: script = script[(i+1):] if script.endswith("-->"): script = script[:-3] if not script: # again, ignore an empty script del self.buf[-1] del self.buf[-1] return if self.jsScript(script, 0.0): del self.buf[-1] del self.buf[-1] return self.buf.append(item)
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
if self.buf[-1][0]!=DATA: return if not (self.buf[-2][0]==STARTTAG and \ self.buf[-2][1]=='script'):
if self.js_src: del self.buf[-1] if self.buf[-3][0]==STARTTAG and self.buf[-3][1]=='script': del self.buf[-1] if len(self.buf)<2 or self.buf[-1][0]==DATA or \ self.buf[-2][0]!=STARTTAG or self.buf[-2][1]!='script':
def jsEndElement (self, item): """parse generated html for scripts return True if the script generates any output, else False""" if len(self.buf)<2: return #assert len(self.buf)>=2 if self.buf[-1][0]!=DATA: # no data means we had <script></script> return if not (self.buf[-2][0]==STARTTAG and \ self.buf[-2][1]=='script'): # there was a <script src="..."> already return # get script data script = self.buf[-1][1].strip() # remove html comments if script.startswith("<!--"): i = script.find('\n') if i==-1: script = script[4:] else: script = script[(i+1):] if script.endswith("-->"): script = script[:-3] if not script: # again, ignore an empty script del self.buf[-1] del self.buf[-1] return if self.jsScript(script, 0.0): del self.buf[-1] del self.buf[-1] return self.buf.append(item)
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
return if self.jsScript(script, 0.0): del self.buf[-1] del self.buf[-1] return self.buf.append(item)
else: self.jsScript(script, 0.0, item)
def jsEndElement (self, item): """parse generated html for scripts return True if the script generates any output, else False""" if len(self.buf)<2: return #assert len(self.buf)>=2 if self.buf[-1][0]!=DATA: # no data means we had <script></script> return if not (self.buf[-2][0]==STARTTAG and \ self.buf[-2][1]=='script'): # there was a <script src="..."> already return # get script data script = self.buf[-1][1].strip() # remove html comments if script.startswith("<!--"): i = script.find('\n') if i==-1: script = script[4:] else: script = script[(i+1):] if script.endswith("-->"): script = script[:-3] if not script: # again, ignore an empty script del self.buf[-1] del self.buf[-1] return if self.jsScript(script, 0.0): del self.buf[-1] del self.buf[-1] return self.buf.append(item)
475def66113a258d59f287a283585f27e07dd77a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/475def66113a258d59f287a283585f27e07dd77a/Rewriter.py
values[category.name] = {}
def _reset_values (): for category in categories: values[category.name] = {} if category.iterable: for value in category.values: values[category.name][value] = False else: values[category.name] = None rating_modified.clear()
e57320a5f66cd1bb8ce168580daf9cf533104b48 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e57320a5f66cd1bb8ce168580daf9cf533104b48/rating_html.py
values[category.name][value] = False
values[category.name][value] = value=='none'
def _reset_values (): for category in categories: values[category.name] = {} if category.iterable: for value in category.values: values[category.name][value] = False else: values[category.name] = None rating_modified.clear()
e57320a5f66cd1bb8ce168580daf9cf533104b48 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e57320a5f66cd1bb8ce168580daf9cf533104b48/rating_html.py
values[category.name] = None
values[category.name] = ""
def _reset_values (): for category in categories: values[category.name] = {} if category.iterable: for value in category.values: values[category.name][value] = False else: values[category.name] = None rating_modified.clear()
e57320a5f66cd1bb8ce168580daf9cf533104b48 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e57320a5f66cd1bb8ce168580daf9cf533104b48/rating_html.py
for key, value in _get_prefix_vals(form, 'category_'): category = _get_category(key)
for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname)
def _form_ratings (form): """Check category value validity""" for key, value in _get_prefix_vals(form, 'category_'): category = _get_category(key) if category is None: # unknown category error['categoryvalue'] = True return False if not category.is_valid_value(value): error['categoryvalue'] = True return False values[key] = value return True
e57320a5f66cd1bb8ce168580daf9cf533104b48 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e57320a5f66cd1bb8ce168580daf9cf533104b48/rating_html.py
if not category.is_valid_value(value):
if not category.valid_value(value):
def _form_ratings (form): """Check category value validity""" for key, value in _get_prefix_vals(form, 'category_'): category = _get_category(key) if category is None: # unknown category error['categoryvalue'] = True return False if not category.is_valid_value(value): error['categoryvalue'] = True return False values[key] = value return True
e57320a5f66cd1bb8ce168580daf9cf533104b48 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e57320a5f66cd1bb8ce168580daf9cf533104b48/rating_html.py
values[key] = value
if category.iterable: values[catname]['none'] = False values[catname][value] = True else: values[catname] = value
def _form_ratings (form): """Check category value validity""" for key, value in _get_prefix_vals(form, 'category_'): category = _get_category(key) if category is None: # unknown category error['categoryvalue'] = True return False if not category.is_valid_value(value): error['categoryvalue'] = True return False values[key] = value return True
e57320a5f66cd1bb8ce168580daf9cf533104b48 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e57320a5f66cd1bb8ce168580daf9cf533104b48/rating_html.py
logfile = os.path.join(confdir, "logging.conf")
logfile = os.path.join(wc.ConfigDir, "logging.conf")
def do_install (): """ Install shortcuts and NT service. """ fix_configdata() import wc # initialize logging logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name) install_shortcuts() install_certificates() install_service() stop_service() install_adminpassword() start_service() open_browser_config()
5cfafa3fdea9afcf37190b42d066b9e5573323f0 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/5cfafa3fdea9afcf37190b42d066b9e5573323f0/install-webcleaner.py
logfile = os.path.join(confdir, "logging.conf")
logfile = os.path.join(wc.ConfigDir, "logging.conf")
def do_remove (): """ Stop and remove the installed NT service. """ import wc # initialize logging logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name) stop_service() remove_service() remove_certificates() remove_tempfiles() purge_tempfiles() # make sure empty directories are removed remove_empty_directories(wc.ConfigDir)
5cfafa3fdea9afcf37190b42d066b9e5573323f0 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/5cfafa3fdea9afcf37190b42d066b9e5573323f0/install-webcleaner.py
exception(GUI, "Wrong path %r", url)
wc.log.exception(GUI, "Wrong path %r", url)
def __init__ (self, client, url, form, protocol, clientheaders, status=200, msg=wc.i18n._('Ok'), localcontext=None, auth=''): """load a web configuration template and return response""" wc.log.debug(wc.LOG_GUI, "WebConfig %s %s", url, form) self.client = client # we pretend to be the server self.connected = True headers = wc.proxy.Headers.WcMessage() headers['Server'] = 'Proxy\r' if auth: if status==407: headers['Proxy-Authenticate'] = "%s\r"%auth elif status==401: headers['WWW-Authenticate'] = "%s\r"%auth else: error(GUI, "Authentication with wrong status %d", status) if status in [301,302]: headers['Location'] = clientheaders['Location'] gm = mimetypes.guess_type(url, None) if gm[0] is not None: ctype = gm[0] else: # note: index.html is appended to directories ctype = 'text/html' if ctype=='text/html': ctype += "; charset=iso-8859-1" headers['Content-Type'] = "%s\r"%ctype try: lang = wc.i18n.get_headers_lang(clientheaders) # get the template filename path, dirs, lang = get_template_url(url, lang) if path.endswith('.html'): fp = file(path) # get TAL context context, newstatus = \ get_context(dirs, form, localcontext, lang) if newstatus==401 and status!=newstatus: client.error(401, wc.i18n._("Authentication Required"), auth=wc.proxy.auth.get_challenges()) return # get translator translator = gettext.translation(wc.Name, wc.LocaleDir, [lang], fallback=True) #wc.log.debug(wc.LOG_GUI, "Using translator %s", translator.info()) # expand template data = expand_template(fp, context, translator=translator) else: fp = file(path, 'rb') data = fp.read() fp.close() except IOError: exception(GUI, "Wrong path %r", url) # XXX this can actually lead to a maximum recursion # error when client.error caused the exception client.error(404, wc.i18n._("Not Found")) return except StandardError: # catch standard exceptions and report internal error exception(GUI, "Template error") client.error(500, wc.i18n._("Internal Error")) return # not catched builtin exceptions are: # SystemExit, StopIteration and all warnings
040418fb71088d27d487307bd693e3fb4cdf048b /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/040418fb71088d27d487307bd693e3fb4cdf048b/__init__.py
exception(GUI, "Template error")
wc.log.exception(GUI, "Template error")
def __init__ (self, client, url, form, protocol, clientheaders, status=200, msg=wc.i18n._('Ok'), localcontext=None, auth=''): """load a web configuration template and return response""" wc.log.debug(wc.LOG_GUI, "WebConfig %s %s", url, form) self.client = client # we pretend to be the server self.connected = True headers = wc.proxy.Headers.WcMessage() headers['Server'] = 'Proxy\r' if auth: if status==407: headers['Proxy-Authenticate'] = "%s\r"%auth elif status==401: headers['WWW-Authenticate'] = "%s\r"%auth else: error(GUI, "Authentication with wrong status %d", status) if status in [301,302]: headers['Location'] = clientheaders['Location'] gm = mimetypes.guess_type(url, None) if gm[0] is not None: ctype = gm[0] else: # note: index.html is appended to directories ctype = 'text/html' if ctype=='text/html': ctype += "; charset=iso-8859-1" headers['Content-Type'] = "%s\r"%ctype try: lang = wc.i18n.get_headers_lang(clientheaders) # get the template filename path, dirs, lang = get_template_url(url, lang) if path.endswith('.html'): fp = file(path) # get TAL context context, newstatus = \ get_context(dirs, form, localcontext, lang) if newstatus==401 and status!=newstatus: client.error(401, wc.i18n._("Authentication Required"), auth=wc.proxy.auth.get_challenges()) return # get translator translator = gettext.translation(wc.Name, wc.LocaleDir, [lang], fallback=True) #wc.log.debug(wc.LOG_GUI, "Using translator %s", translator.info()) # expand template data = expand_template(fp, context, translator=translator) else: fp = file(path, 'rb') data = fp.read() fp.close() except IOError: exception(GUI, "Wrong path %r", url) # XXX this can actually lead to a maximum recursion # error when client.error caused the exception client.error(404, wc.i18n._("Not Found")) return except StandardError: # catch standard exceptions and report internal error exception(GUI, "Template error") client.error(500, wc.i18n._("Internal Error")) return # not catched builtin exceptions are: # SystemExit, StopIteration and all warnings
040418fb71088d27d487307bd693e3fb4cdf048b /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/040418fb71088d27d487307bd693e3fb4cdf048b/__init__.py
if ro.match(self.headers.getheader('content-type')):
if ro.match(self.headers.getheader('content-type') or ""):
def process_headers (self): # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.match(r'^((?:[^\r\n]+\r?\n)*\r?\n)', self.recv_buffer) if not m: return
dae5223b4ecf5e1694df38fdc3b545cc2abc239d /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/dae5223b4ecf5e1694df38fdc3b545cc2abc239d/HttpServer.py
getattr(self, fun)(htmlfilter)
getattr(self, fun)()
def scan_end_tag (self, tag): fun = "%s_end"%tag if hasattr(self, fun): getattr(self, fun)(htmlfilter)
5c152a455e9df787a50e15e9795d92473345321e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/5c152a455e9df787a50e15e9795d92473345321e/HtmlSecurity.py
def object_end (self, htmlfilter):
def object_end (self):
def object_end (self, htmlfilter): if self.in_winhelp: self.in_winhelp = False
5c152a455e9df787a50e15e9795d92473345321e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/5c152a455e9df787a50e15e9795d92473345321e/HtmlSecurity.py
mime = mime_types[0]
def server_set_content_headers (headers, mime_types, url): """add missing content-type headers""" origmime = headers.get('Content-Type', None) if not origmime: wc.log.warn(wc.LOG_PROXY, _("Missing content type in %r"), url) if not mime_types: return matching_mimes = [m for m in mime_types if origmime.startswith(m)] if len(matching_mimes) > 0: return # we have a mime type override if origmime: wc.log.warn(wc.LOG_PROXY, _("Change content type of %r from %r to %r"), url, origmime, mime) else: wc.log.warn(wc.LOG_PROXY, _("Set content type of %r to %r"), url, mime) headers['Content-Type'] = "%s\r" % mime
e45a48522bb6ccd0159406b412e8f56420e39c09 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e45a48522bb6ccd0159406b412e8f56420e39c09/Headers.py
def addLocals (self, localVarList): # Pop the current locals onto the stack self.localStack.append (self.locals) self.locals = copy.copy (self.locals) for name,value in localVarList: if (isinstance (value, ContextVariable)): self.locals [name] = value else: self.locals [name] = ContextVariable (value)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def popLocals (self): self.locals = self.localStack.pop()
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
self.log.debug ("Evaluating %s" % expr)
self.log.debug ("Evaluating %s ...", expr)
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
return self.evaluatePath (expr[5:].lstrip ())
res = self.evaluatePath (expr[5:].lstrip ())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
return self.evaluateExists (expr[7:].lstrip())
res = self.evaluateExists (expr[7:].lstrip())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
return self.evaluateNoCall (expr[7:].lstrip())
res = self.evaluateNoCall (expr[7:].lstrip())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
return self.evaluateNot (expr[4:].lstrip())
res = self.evaluateNot (expr[4:].lstrip())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
return self.evaluateString (expr[7:].lstrip())
res = self.evaluateString (expr[7:].lstrip())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
return self.evaluatePython (expr[7:].lstrip())
res = self.evaluatePython (expr[7:].lstrip())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
return self.evaluatePath (expr)
res = self.evaluatePath (expr) self.log.debug("... result %s", str(res)) return res
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluatePython (self, expr): if (not self.allowPythonPath): self.log.warn ("Parameter allowPythonPath is false. NOT Evaluating python expression %s" % expr) return self.false self.log.debug ("Evaluating python expression %s" % expr) globals={} for name, value in self.globals.items(): globals [name] = value.rawValue() globals ['path'] = self.pythonPathFuncs.path globals ['string'] = self.pythonPathFuncs.string globals ['exists'] = self.pythonPathFuncs.exists globals ['nocall'] = self.pythonPathFuncs.nocall locals={} for name, value in self.locals.items(): locals [name] = value.rawValue() try: result = eval(expr, globals, locals) except Exception, e: # An exception occured evaluating the template, return the exception as text self.log.warn ("Exception occured evaluting python path, exception: " + str (e)) return ContextVariable ("Exception: %s" % str (e)) return ContextVariable(result)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluatePython (self, expr): if (not self.allowPythonPath): self.log.warn ("Parameter allowPythonPath is false. NOT Evaluating python expression %s" % expr) return self.false self.log.debug ("Evaluating python expression %s" % expr) globals={} for name, value in self.globals.items(): globals [name] = value.rawValue() globals ['path'] = self.pythonPathFuncs.path globals ['string'] = self.pythonPathFuncs.string globals ['exists'] = self.pythonPathFuncs.exists globals ['nocall'] = self.pythonPathFuncs.nocall locals={} for name, value in self.locals.items(): locals [name] = value.rawValue() try: result = eval(expr, globals, locals) except Exception, e: # An exception occured evaluating the template, return the exception as text self.log.warn ("Exception occured evaluting python path, exception: " + str (e)) return ContextVariable ("Exception: %s" % str (e)) return ContextVariable(result)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluatePython (self, expr): if (not self.allowPythonPath): self.log.warn ("Parameter allowPythonPath is false. NOT Evaluating python expression %s" % expr) return self.false self.log.debug ("Evaluating python expression %s" % expr) globals={} for name, value in self.globals.items(): globals [name] = value.rawValue() globals ['path'] = self.pythonPathFuncs.path globals ['string'] = self.pythonPathFuncs.string globals ['exists'] = self.pythonPathFuncs.exists globals ['nocall'] = self.pythonPathFuncs.nocall locals={} for name, value in self.locals.items(): locals [name] = value.rawValue() try: result = eval(expr, globals, locals) except Exception, e: # An exception occured evaluating the template, return the exception as text self.log.warn ("Exception occured evaluting python path, exception: " + str (e)) return ContextVariable ("Exception: %s" % str (e)) return ContextVariable(result)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluatePython (self, expr): if (not self.allowPythonPath): self.log.warn ("Parameter allowPythonPath is false. NOT Evaluating python expression %s" % expr) return self.false self.log.debug ("Evaluating python expression %s" % expr) globals={} for name, value in self.globals.items(): globals [name] = value.rawValue() globals ['path'] = self.pythonPathFuncs.path globals ['string'] = self.pythonPathFuncs.string globals ['exists'] = self.pythonPathFuncs.exists globals ['nocall'] = self.pythonPathFuncs.nocall locals={} for name, value in self.locals.items(): locals [name] = value.rawValue() try: result = eval(expr, globals, locals) except Exception, e: # An exception occured evaluating the template, return the exception as text self.log.warn ("Exception occured evaluting python path, exception: " + str (e)) return ContextVariable ("Exception: %s" % str (e)) return ContextVariable(result)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluatePath (self, expr): self.log.debug ("Evaluating path expression %s" % expr) allPaths = expr.split ('|') if (len (allPaths) > 1): for path in allPaths: # Evaluate this path pathResult = self.evaluate (path.strip ()) if (pathResult is not None): return pathResult return None else: # A single path - so let's evaluate it return self.traversePath (allPaths[0])
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluateExists (self, expr): self.log.debug ("Evaluating %s to see if it exists" % expr) allPaths = expr.split ('|') if (len (allPaths) > 1): # The first path is for us # Return true if this first bit evaluates, otherwise test the rest result = self.traversePath (allPaths[0]) if (result is not None): return self.true for path in allPaths[1:]: # Evaluate this path pathResult = self.evaluate (path.strip ()) if (pathResult is not None): return self.true return None else: # A single path - so let's evaluate it result = self.traversePath (allPaths[0]) if (result is None): return None return self.true
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluateNot (self, expr): self.log.debug ("Evaluating NOT value of %s" % expr) # Evaluate what I was passed pathResult = self.evaluate (expr) if (pathResult is None): # None of these paths exist! return self.true if (pathResult.isTrue()): return self.false return self.true
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluateNot (self, expr): self.log.debug ("Evaluating NOT value of %s" % expr) # Evaluate what I was passed pathResult = self.evaluate (expr) if (pathResult is None): # None of these paths exist! return self.true if (pathResult.isTrue()): return self.false return self.true
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def evaluateString (self, expr): self.log.debug ("Evaluating String %s" % expr) result = "" skipCount = 0 for position in xrange (0,len (expr)): if (skipCount > 0): skipCount -= 1 else: if (expr[position] == '$'): try: if (expr[position + 1] == '$'): # Escaped $ sign result += '$' skipCount = 1 elif (expr[position + 1] == '{'): # Looking for a path! endPos = expr.find ('}', position + 1) if (endPos > 0): path = expr[position + 2:endPos] # Evaluate the path pathResult = self.evaluate (path) if (pathResult is not None and not pathResult.isNothing()): resultVal = pathResult.value() if (type (resultVal) == type (u"")): result += resultVal elif (type (resultVal) == type ("")): result += resultVal else: result += str(resultVal) skipCount = endPos - position else: # It's a variable endPos = expr.find (' ', position + 1) if (endPos == -1): endPos = len (expr) path = expr [position + 1:endPos] # Evaluate the variable pathResult = self.traversePath (path) if (pathResult is not None and not pathResult.isNothing()): resultVal = pathResult.value() if (type (resultVal) == type (u"")): result += resultVal elif (type (resultVal) == type ("")): result += resultVal else: result += str(resultVal) skipCount = endPos - position - 1 except Exception: # Trailing $ sign - just suppress it self.log.warn ("Trailing $ detected") pass else: result += expr[position] return ContextVariable(result)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def traversePath (self, expr, canCall=1): self.log.debug ("Traversing path %s" % expr) # Check for and correct for trailing/leading quotes if (expr[0] == '"' or expr[0] == "'"): expr = expr [1:] if (expr[-1] == '"' or expr[-1] == "'"): expr = expr [0:-1] pathList = expr.split ('/') path = pathList[0] if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if self.locals.has_key(path): val = self.locals[path] elif self.globals.has_key(path): val = self.globals[path] else: # If we can't find it then return None return None index = 1 for path in pathList[1:]: #self.log.debug ("Looking for path element %s" % path) if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if (canCall): try: temp = val.value((index,pathList)) except ContextVariable, e: return e else: temp = NoCallVariable (val).value() if (hasattr (temp, path)): val = getattr (temp, path) if (not isinstance (val, ContextVariable)): val = ContextVariable (val) else: try: val = temp[path] if (not isinstance (val, ContextVariable)): val = ContextVariable (val) except: #self.log.debug ("Not found.") return None index = index + 1 #self.log.debug ("Found value %s" % str (val)) if (not canCall): return NoCallVariable (val) return val
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
val = self.globals[path]
val = self.globals[path]
def traversePath (self, expr, canCall=1): self.log.debug ("Traversing path %s" % expr) # Check for and correct for trailing/leading quotes if (expr[0] == '"' or expr[0] == "'"): expr = expr [1:] if (expr[-1] == '"' or expr[-1] == "'"): expr = expr [0:-1] pathList = expr.split ('/') path = pathList[0] if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if self.locals.has_key(path): val = self.locals[path] elif self.globals.has_key(path): val = self.globals[path] else: # If we can't find it then return None return None index = 1 for path in pathList[1:]: #self.log.debug ("Looking for path element %s" % path) if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if (canCall): try: temp = val.value((index,pathList)) except ContextVariable, e: return e else: temp = NoCallVariable (val).value() if (hasattr (temp, path)): val = getattr (temp, path) if (not isinstance (val, ContextVariable)): val = ContextVariable (val) else: try: val = temp[path] if (not isinstance (val, ContextVariable)): val = ContextVariable (val) except: #self.log.debug ("Not found.") return None index = index + 1 #self.log.debug ("Found value %s" % str (val)) if (not canCall): return NoCallVariable (val) return val
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def traversePath (self, expr, canCall=1): self.log.debug ("Traversing path %s" % expr) # Check for and correct for trailing/leading quotes if (expr[0] == '"' or expr[0] == "'"): expr = expr [1:] if (expr[-1] == '"' or expr[-1] == "'"): expr = expr [0:-1] pathList = expr.split ('/') path = pathList[0] if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if self.locals.has_key(path): val = self.locals[path] elif self.globals.has_key(path): val = self.globals[path] else: # If we can't find it then return None return None index = 1 for path in pathList[1:]: #self.log.debug ("Looking for path element %s" % path) if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if (canCall): try: temp = val.value((index,pathList)) except ContextVariable, e: return e else: temp = NoCallVariable (val).value() if (hasattr (temp, path)): val = getattr (temp, path) if (not isinstance (val, ContextVariable)): val = ContextVariable (val) else: try: val = temp[path] if (not isinstance (val, ContextVariable)): val = ContextVariable (val) except: #self.log.debug ("Not found.") return None index = index + 1 #self.log.debug ("Found value %s" % str (val)) if (not canCall): return NoCallVariable (val) return val
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
return None
return None
def traversePath (self, expr, canCall=1): self.log.debug ("Traversing path %s" % expr) # Check for and correct for trailing/leading quotes if (expr[0] == '"' or expr[0] == "'"): expr = expr [1:] if (expr[-1] == '"' or expr[-1] == "'"): expr = expr [0:-1] pathList = expr.split ('/') path = pathList[0] if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if self.locals.has_key(path): val = self.locals[path] elif self.globals.has_key(path): val = self.globals[path] else: # If we can't find it then return None return None index = 1 for path in pathList[1:]: #self.log.debug ("Looking for path element %s" % path) if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if (canCall): try: temp = val.value((index,pathList)) except ContextVariable, e: return e else: temp = NoCallVariable (val).value() if (hasattr (temp, path)): val = getattr (temp, path) if (not isinstance (val, ContextVariable)): val = ContextVariable (val) else: try: val = temp[path] if (not isinstance (val, ContextVariable)): val = ContextVariable (val) except: #self.log.debug ("Not found.") return None index = index + 1 #self.log.debug ("Found value %s" % str (val)) if (not canCall): return NoCallVariable (val) return val
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def traversePath (self, expr, canCall=1): self.log.debug ("Traversing path %s" % expr) # Check for and correct for trailing/leading quotes if (expr[0] == '"' or expr[0] == "'"): expr = expr [1:] if (expr[-1] == '"' or expr[-1] == "'"): expr = expr [0:-1] pathList = expr.split ('/') path = pathList[0] if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if self.locals.has_key(path): val = self.locals[path] elif self.globals.has_key(path): val = self.globals[path] else: # If we can't find it then return None return None index = 1 for path in pathList[1:]: #self.log.debug ("Looking for path element %s" % path) if path.startswith ('?'): path = path[1:] if self.locals.has_key(path): path = self.locals[path].value() elif self.globals.has_key(path): path = self.globals[path].value() #self.log.debug ("Dereferenced to %s" % path) if (canCall): try: temp = val.value((index,pathList)) except ContextVariable, e: return e else: temp = NoCallVariable (val).value() if (hasattr (temp, path)): val = getattr (temp, path) if (not isinstance (val, ContextVariable)): val = ContextVariable (val) else: try: val = temp[path] if (not isinstance (val, ContextVariable)): val = ContextVariable (val) except: #self.log.debug ("Not found.") return None index = index + 1 #self.log.debug ("Found value %s" % str (val)) if (not canCall): return NoCallVariable (val) return val
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def __str__ (self): return "Globals: " + str (self.globals) + "Locals: " + str (self.locals)
0edb6e3f2306e15c10eb82adbad02c9b014afe28 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/0edb6e3f2306e15c10eb82adbad02c9b014afe28/simpleTALES.py
def finish(self, data, **attrs): names = data.keys() for name in names: for expr in self.delete: if expr.search(name): del data[name] for key,val in self.add.items(): data[key] = val debug(HURT_ME_PLENTY, "Headers\n", data) return data
def filter(self, data, **attrs): headers = data.keys()[:] for header in headers: for name in self.delete: if header.find(name) != -1: del data[header] for key,val in self.add.items(): data[key] = val debug(HURT_ME_PLENTY, "Headers\n", data) return data
5ed249964d1d63b0574c3a0ae3ceeb43885e80c2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/5ed249964d1d63b0574c3a0ae3ceeb43885e80c2/Header.py
if attrs: self.data += " " for key,val in attrs.items(): self.data += "%s=\"%s\"" % (key, cgi.escape(val, True))
for key,val in attrs.items(): self.data += " %s=\"%s\"" % (key, cgi.escape(val, True))
def unknown_starttag (self, tag, attributes): attrs = {} for key,val in attributes: attrs[key] = val msgid = attrs.get('i18n:translate', None) if msgid == '': if self.tag: raise Exception, "nested i18n:translate is unsupported" self.tag = tag self.data = "" elif msgid is not None: if self.tag: raise Exception, "nested i18n:translate is unsupported" if msgid.startswith("string:"): self.translations.add(msgid[7:].replace(';;', ';')) else: print >>sys.stderr, "tag <%s> has unsupported dynamic msgid %s" % (tag, `msgid`) elif self.tag: # nested tag to translate self.data += "<%s"%tag if attrs: self.data += " " for key,val in attrs.items(): self.data += "%s=\"%s\"" % (key, cgi.escape(val, True)) self.data += ">" argument = attrs.get('i18n:attributes', None) if argument is not None: for name, msgid in get_attribute_list(argument): self.translations.add(msgid)
7e46f756ae6d7bfb045c5cf8af8cca77002bb7d8 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/7e46f756ae6d7bfb045c5cf8af8cca77002bb7d8/pygettext.py
def process_read (self): if not self.callback: self.close() # Assume that the entire answer comes in one packet if self.tcp: if len(self.recv_buffer) < 2: return header = self.recv_buffer[:2] (l,) = struct.unpack("!H", header) if len(self.recv_buffer) < 2+l: return self.read(2) # header wire = self.read(l) try: self.socket.shutdown(1) except socket.error: pass else: wire = self.read(1024) response = wc.dns.message.from_wire( wire, keyring=self.query.keyring, request_mac=self.query.mac) wc.log.debug(wc.LOG_DNS, "got DNS response %s", response) if not self.query.is_response(response): wc.log.warn(wc.LOG_DNS, '%s was no response to %s', response, self.query) # Oops, this doesn't answer the right question. This can # happen because we're using UDP, and UDP replies might end # up in the wrong place: open conn A, send question to A, # timeout, send question to A, receive answer, close our # object, then open a new conn B, send question to B, # but get the OLD answer to A as a reply. This doesn't happen # with TCP but then TCP is slower.
d86a40bc356cc1b19fb23705808bd92842646052 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/d86a40bc356cc1b19fb23705808bd92842646052/dns_lookups.py
def process_read (self): if not self.callback: self.close() # Assume that the entire answer comes in one packet if self.tcp: if len(self.recv_buffer) < 2: return header = self.recv_buffer[:2] (l,) = struct.unpack("!H", header) if len(self.recv_buffer) < 2+l: return self.read(2) # header wire = self.read(l) try: self.socket.shutdown(1) except socket.error: pass else: wire = self.read(1024) response = wc.dns.message.from_wire( wire, keyring=self.query.keyring, request_mac=self.query.mac) wc.log.debug(wc.LOG_DNS, "got DNS response %s", response) if not self.query.is_response(response): wc.log.warn(wc.LOG_DNS, '%s was no response to %s', response, self.query) # Oops, this doesn't answer the right question. This can # happen because we're using UDP, and UDP replies might end # up in the wrong place: open conn A, send question to A, # timeout, send question to A, receive answer, close our # object, then open a new conn B, send question to B, # but get the OLD answer to A as a reply. This doesn't happen # with TCP but then TCP is slower.
d86a40bc356cc1b19fb23705808bd92842646052 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/d86a40bc356cc1b19fb23705808bd92842646052/dns_lookups.py
tc, self.nameserver, self.hostname)
response, self.nameserver, self.hostname)
def process_read (self): if not self.callback: self.close() # Assume that the entire answer comes in one packet if self.tcp: if len(self.recv_buffer) < 2: return header = self.recv_buffer[:2] (l,) = struct.unpack("!H", header) if len(self.recv_buffer) < 2+l: return self.read(2) # header wire = self.read(l) try: self.socket.shutdown(1) except socket.error: pass else: wire = self.read(1024) response = wc.dns.message.from_wire( wire, keyring=self.query.keyring, request_mac=self.query.mac) wc.log.debug(wc.LOG_DNS, "got DNS response %s", response) if not self.query.is_response(response): wc.log.warn(wc.LOG_DNS, '%s was no response to %s', response, self.query) # Oops, this doesn't answer the right question. This can # happen because we're using UDP, and UDP replies might end # up in the wrong place: open conn A, send question to A, # timeout, send question to A, receive answer, close our # object, then open a new conn B, send question to B, # but get the OLD answer to A as a reply. This doesn't happen # with TCP but then TCP is slower.
d86a40bc356cc1b19fb23705808bd92842646052 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/d86a40bc356cc1b19fb23705808bd92842646052/dns_lookups.py
if self.hostname[-4:] in ('.com','.net') and \ '64.94.110.11' in ip_addrs: callback(self.hostname, DnsResponse('error', 'not found')) else: callback(self.hostname, DnsResponse('found', ip_addrs))
callback(self.hostname, DnsResponse('found', ip_addrs))
def process_read (self): if not self.callback: self.close() # Assume that the entire answer comes in one packet if self.tcp: if len(self.recv_buffer) < 2: return header = self.recv_buffer[:2] (l,) = struct.unpack("!H", header) if len(self.recv_buffer) < 2+l: return self.read(2) # header wire = self.read(l) try: self.socket.shutdown(1) except socket.error: pass else: wire = self.read(1024) response = wc.dns.message.from_wire( wire, keyring=self.query.keyring, request_mac=self.query.mac) wc.log.debug(wc.LOG_DNS, "got DNS response %s", response) if not self.query.is_response(response): wc.log.warn(wc.LOG_DNS, '%s was no response to %s', response, self.query) # Oops, this doesn't answer the right question. This can # happen because we're using UDP, and UDP replies might end # up in the wrong place: open conn A, send question to A, # timeout, send question to A, receive answer, close our # object, then open a new conn B, send question to B, # but get the OLD answer to A as a reply. This doesn't happen # with TCP but then TCP is slower.
d86a40bc356cc1b19fb23705808bd92842646052 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/d86a40bc356cc1b19fb23705808bd92842646052/dns_lookups.py
def __init__ (self): """initalize filter delete/add lists""" super(Header, self).__init__() self.delete = {
def get_attrs (self, url, headers): """configure header rules to add/delete""" d = super(Header, self).get_attrs(url, headers) delete = {
def __init__ (self): """initalize filter delete/add lists""" super(Header, self).__init__() self.delete = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], } self.add = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], }
18604fdaeeb7314f0449113bd9f4de858be52d05 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/18604fdaeeb7314f0449113bd9f4de858be52d05/Header.py
self.add = {
add = {
def __init__ (self): """initalize filter delete/add lists""" super(Header, self).__init__() self.delete = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], } self.add = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], }
18604fdaeeb7314f0449113bd9f4de858be52d05 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/18604fdaeeb7314f0449113bd9f4de858be52d05/Header.py
def addrule (self, rule): """add given rule to filter, filling header delete/add lists""" super(Header, self).addrule(rule) if not rule.name: return if not rule.value: matcher = re.compile(rule.name, re.I).match if rule.filterstage in ('both', 'request'): self.delete[wc.filter.FILTER_REQUEST_HEADER].append(matcher) if rule.filterstage in ('both', 'response'): self.delete[wc.filter.FILTER_RESPONSE_HEADER].append(matcher) else: name = str(rule.name) val = str(rule.value) if rule.filterstage in ('both', 'request'): self.add[wc.filter.FILTER_REQUEST_HEADER].append((name, val)) if rule.filterstage in ('both', 'response'): self.add[wc.filter.FILTER_RESPONSE_HEADER].append((name, val))
for rule in self.rules: if not rule.appliesTo(url) or not rule.name: continue if not rule.value: matcher = re.compile(rule.name, re.I).match if rule.filterstage in ('both', 'request'): delete[wc.filter.FILTER_REQUEST_HEADER].append(matcher) if rule.filterstage in ('both', 'response'): delete[wc.filter.FILTER_RESPONSE_HEADER].append(matcher) else: name = str(rule.name) val = str(rule.value) if rule.filterstage in ('both', 'request'): add[wc.filter.FILTER_REQUEST_HEADER].append((name, val)) if rule.filterstage in ('both', 'response'): add[wc.filter.FILTER_RESPONSE_HEADER].append((name, val)) d['header_add'] = add d['header_delete'] = delete return d
def __init__ (self): """initalize filter delete/add lists""" super(Header, self).__init__() self.delete = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], } self.add = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], }
18604fdaeeb7314f0449113bd9f4de858be52d05 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/18604fdaeeb7314f0449113bd9f4de858be52d05/Header.py
warn(PROXY, 'read buffer full')
warn(PROXY, '%s read buffer full', str(self))
def handle_read (self): if not self.connected: # It's been closed (presumably recently) return
d561d4434dfd8778f12ecf8ab54dd36be8fa04d1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/d561d4434dfd8778f12ecf8ab54dd36be8fa04d1/Connection.py
return len(self.send_buffer)
return self.send_buffer
def writable (self): return len(self.send_buffer)
d561d4434dfd8778f12ecf8ab54dd36be8fa04d1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/d561d4434dfd8778f12ecf8ab54dd36be8fa04d1/Connection.py
config['allowedhostset'] = ip.hosts2map(config['allowedhosts'])
config['allowedhostset'] = _hosts2map(config['allowedhosts'])
def _form_addallowed (host): if host not in config['allowedhosts']: config['allowedhosts'].append(host) config['allowedhostset'] = ip.hosts2map(config['allowedhosts']) info['addallowed'] = True config.write_proxyconf()
13800fb83183cbc0fc21b18f7f924e8927138afe /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/13800fb83183cbc0fc21b18f7f924e8927138afe/config_html.py
config['allowedhostset'] = ip.hosts2map(config['allowedhosts'])
config['allowedhostset'] = _hosts2map(config['allowedhosts'])
def _form_delallowed (form): removed = 0 for host in _getlist(form, 'allowedhosts'): if host in config['allowedhosts']: config['allowedhosts'].remove(host) removed += 1 if removed > 0: config['allowedhostset'] = ip.hosts2map(config['allowedhosts']) config.write_proxyconf() info['delallowed'] = True
13800fb83183cbc0fc21b18f7f924e8927138afe /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/13800fb83183cbc0fc21b18f7f924e8927138afe/config_html.py
def _main (fname): import hotshot.stats stats = hotshot.stats.load(fname) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(25)
import sys import os import wc _profile = "webcleaner.prof" def _main (filename): """ Print profiling data and exit. """ if not wc.HasPstats: print >>sys.stderr, "The `pstats' Python module is not installed." sys.exit(1) if not os.path.isfile(filename): print >>sys.stderr, "Could not find regular file %r." % filename sys.exit(1) import pstats stats = pstats.Stats(filename) stats.strip_dirs().sort_stats("cumulative").print_stats(100) sys.exit(0)
def _main (fname): import hotshot.stats stats = hotshot.stats.load(fname) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(25)
7e51c8f454cbc27245221ea53715d07788aa0ae3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/7e51c8f454cbc27245221ea53715d07788aa0ae3/showprof.py
import sys
def _main (fname): import hotshot.stats stats = hotshot.stats.load(fname) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(25)
7e51c8f454cbc27245221ea53715d07788aa0ae3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/7e51c8f454cbc27245221ea53715d07788aa0ae3/showprof.py
_main("filter.prof")
_main(_profile)
def _main (fname): import hotshot.stats stats = hotshot.stats.load(fname) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(25)
7e51c8f454cbc27245221ea53715d07788aa0ae3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/7e51c8f454cbc27245221ea53715d07788aa0ae3/showprof.py
scripts = ['webcleanerconf', 'wcheaders'],
scripts = ['webcleanerconf', 'wcheaders']
def create_batch_file(self, directory, data, filename): filename = os.path.join(directory, filename) # write the batch file util.execute(write_file, (filename, data), "creating %s" % filename, self.verbose>=1, self.dry_run)
e8a8c51de822e2e35b9f24ca6e64373676a9ffbd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e8a8c51de822e2e35b9f24ca6e64373676a9ffbd/setup.py
scripts = ['webcleaner', 'webcleanerconf', 'wcheaders'],
scripts = ['webcleaner', 'webcleanerconf', 'wcheaders']
def create_batch_file(self, directory, data, filename): filename = os.path.join(directory, filename) # write the batch file util.execute(write_file, (filename, data), "creating %s" % filename, self.verbose>=1, self.dry_run)
e8a8c51de822e2e35b9f24ca6e64373676a9ffbd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/e8a8c51de822e2e35b9f24ca6e64373676a9ffbd/setup.py
def is_valid_bitmask (mask): """Return True if given mask is a valid network bitmask""" return 1 <= mask <= 32
def is_valid_cidrmask (mask): """check if given mask is a valid network bitmask in CIDR notation""" return 0 <= mask <= 32
def is_valid_bitmask (mask): """Return True if given mask is a valid network bitmask""" return 1 <= mask <= 32
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
def suffix2mask (n): "return a mask of n bits as a long integer" return (1L << (32 - n)) - 1 def mask2suffix (mask): """return suff for given bit mask""" return 32 - int(math.log(mask+1, 2)) def dq2mask (ip):
def cidr2mask (n): "return a mask where the n left-most of 32 bits are set" return ((1L << n) - 1) << (32-n) def netmask2mask (ip):
def suffix2mask (n): "return a mask of n bits as a long integer" return (1L << (32 - n)) - 1
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
n = dq2num(ip) return -((-n+1) | n)
return dq2num(ip)
def dq2mask (ip): "return a mask of bits as a long integer" n = dq2num(ip) return -((-n+1) | n)
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
n = dq2num(ip) net = n - (n & mask) return (net, mask) def dq_in_net (n, net, mask): """return True iff numerical ip n is in given net with mask. (net,mask) must be returned previously by ip2net""" m = n - (n & mask) return m == net
return dq2num(ip) & mask def dq_in_net (n, mask): """return True iff numerical ip n is in given network""" return (n & mask) == mask
def dq2net (ip, mask): "return a tuple (network ip, network mask) for given ip and mask" n = dq2num(ip) net = n - (n & mask) return (net, mask)
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
for net, mask in nets: if dq_in_net(n, net, mask):
for net in nets: if dq_in_net(n, net):
def host_in_set (ip, hosts, nets): """return True if given ip is in host or network list""" if ip in hosts: return True if is_valid_ipv4(ip): n = dq2num(ip) for net, mask in nets: if dq_in_net(n, net, mask): return True return False
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
if _host_bitmask_re.match(host):
if _host_cidrmask_re.match(host):
def hosts2map (hosts): """return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = sets.Set() nets = [] for host in hosts: if _host_bitmask_re.match(host): host, mask = host.split("/") mask = int(mask) if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask) continue if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue nets.append(dq2net(host, suffix2mask(mask))) elif _host_netmask_re.match(host): host, mask = host.split("/") if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue if not is_valid_ipv4(mask): wc.log.error(wc.LOG_NET, "mask %r is not a valid ip network mask", mask) continue nets.append(dq2net(host, dq2mask(mask))) elif is_valid_ip(host): hostset.add(expand_ip(host)[0]) else: try: hostset |= resolve_host(host) except socket.gaierror: wc.log.error(wc.LOG_NET, "invalid host %r", host) return (hostset, nets)
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask)
if not is_valid_cidrmask(mask): wc.log.error(wc.LOG_NET, "CIDR mask %d is not a valid network mask", mask)
def hosts2map (hosts): """return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = sets.Set() nets = [] for host in hosts: if _host_bitmask_re.match(host): host, mask = host.split("/") mask = int(mask) if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask) continue if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue nets.append(dq2net(host, suffix2mask(mask))) elif _host_netmask_re.match(host): host, mask = host.split("/") if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue if not is_valid_ipv4(mask): wc.log.error(wc.LOG_NET, "mask %r is not a valid ip network mask", mask) continue nets.append(dq2net(host, dq2mask(mask))) elif is_valid_ip(host): hostset.add(expand_ip(host)[0]) else: try: hostset |= resolve_host(host) except socket.gaierror: wc.log.error(wc.LOG_NET, "invalid host %r", host) return (hostset, nets)
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
nets.append(dq2net(host, suffix2mask(mask)))
nets.append(dq2net(host, cidr2mask(mask)))
def hosts2map (hosts): """return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = sets.Set() nets = [] for host in hosts: if _host_bitmask_re.match(host): host, mask = host.split("/") mask = int(mask) if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask) continue if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue nets.append(dq2net(host, suffix2mask(mask))) elif _host_netmask_re.match(host): host, mask = host.split("/") if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue if not is_valid_ipv4(mask): wc.log.error(wc.LOG_NET, "mask %r is not a valid ip network mask", mask) continue nets.append(dq2net(host, dq2mask(mask))) elif is_valid_ip(host): hostset.add(expand_ip(host)[0]) else: try: hostset |= resolve_host(host) except socket.gaierror: wc.log.error(wc.LOG_NET, "invalid host %r", host) return (hostset, nets)
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
nets.append(dq2net(host, dq2mask(mask)))
nets.append(dq2net(host, netmask2mask(mask)))
def hosts2map (hosts): """return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = sets.Set() nets = [] for host in hosts: if _host_bitmask_re.match(host): host, mask = host.split("/") mask = int(mask) if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask) continue if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue nets.append(dq2net(host, suffix2mask(mask))) elif _host_netmask_re.match(host): host, mask = host.split("/") if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue if not is_valid_ipv4(mask): wc.log.error(wc.LOG_NET, "mask %r is not a valid ip network mask", mask) continue nets.append(dq2net(host, dq2mask(mask))) elif is_valid_ip(host): hostset.add(expand_ip(host)[0]) else: try: hostset |= resolve_host(host) except socket.gaierror: wc.log.error(wc.LOG_NET, "invalid host %r", host) return (hostset, nets)
2ecd0206d653574af32efa1ae225b3e5ad4ef5d6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/2ecd0206d653574af32efa1ae225b3e5ad4ef5d6/ip.py
s = """<h1>bla</h1>""" for c in s: p.feed(c)
p.feed("""<a><t""") p.feed("""r>""")
def _broken (): p = HtmlPrinter() s = """<h1>bla</h1>""" for c in s: p.feed(c) p.flush()
704d3076206bddfa561398b078727b3961837845 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/704d3076206bddfa561398b078727b3961837845/htmllib.py
if why==(4,'Interrupted system call'):
if why.args == (4, 'Interrupted system call'):
def proxy_poll(timeout=0.0): smap = asyncore.socket_map if smap: r = filter(lambda x: x.readable(), smap.values()) w = filter(lambda x: x.writable(), smap.values()) e = smap.values() try: (r,w,e) = select.select(r,w,e, timeout) except select.error, why: debug(BRING_IT_ON, why) if why==(4,'Interrupted system call'): # this occurs on UNIX systems with a sighup signal return else: raise # Make sure we only process one type of event at a time, # because if something needs to close the connection we # don't want to call another handle_* on it handlerCount = 0 for x in e: try: x.handle_expt_event() handlerCount = handlerCount + 1 except: x.handle_error(sys.exc_type, sys.exc_value, sys.exc_traceback) for x in w: try: t = time.time() if x not in e: x.handle_write_event() handlerCount = handlerCount + 1 if time.time() - t > 0.1: debug(BRING_IT_ON, 'wslow', '%4.1f'%(time.time()-t), 's', x) except: x.handle_error(sys.exc_type, sys.exc_value, sys.exc_traceback) for x in r: try: t = time.time() if x not in e and x not in w: x.handle_read_event() handlerCount = handlerCount + 1 if time.time() - t > 0.1: debug(BRING_IT_ON, 'rslow', '%4.1f'%(time.time()-t), 's', x) except: x.handle_error(sys.exc_type, sys.exc_value, sys.exc_traceback) return handlerCount #_OBFUSCATE_IP = config['obfuscateip']
8cebbe7552cd2cb4d7e67f31b4f352c6716168a3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/8cebbe7552cd2cb4d7e67f31b4f352c6716168a3/__init__.py
self.decoders.append(wc.proxy.UnchunkStream.UnchunkStream())
self.decoders.append( wc.proxy.decoders.UnchunkStream.UnchunkStream())
def process_headers (self): """read and filter client request headers""" # Two newlines ends headers i = self.recv_buffer.find('\r\n\r\n') if i < 0: return i += 4 # Skip over newline terminator # the first 2 chars are the newline of request fp = StringIO.StringIO(self.read(i)[2:]) msg = wc.proxy.Headers.WcMessage(fp) # put unparsed data (if any) back to the buffer msg.rewindbody() self.recv_buffer = fp.read() + self.recv_buffer fp.close() wc.log.debug(wc.LOG_PROXY, "%s client headers \n%s", self, msg) self.fix_request_headers(msg) clientheaders = msg.copy() stage = wc.filter.STAGE_REQUEST_HEADER self.attrs = wc.filter.get_filterattrs(self.url, [stage], clientheaders=clientheaders, headers=msg) self.set_persistent(msg, self.http_ver) self.mangle_request_headers(msg) self.compress = wc.proxy.Headers.client_set_encoding_headers(msg) # filter headers self.headers = wc.filter.applyfilter(stage, msg, "finish", self.attrs) # add decoders self.decoders = [] # if content-length header is missing, assume zero length self.bytes_remaining = \ wc.proxy.Headers.get_content_length(self.headers, 0) # chunked encoded if self.headers.has_key('Transfer-Encoding'): # XXX don't look at value, assume chunked encoding for now wc.log.debug(wc.LOG_PROXY, '%s Transfer-encoding %r', self, self.headers['Transfer-encoding']) self.decoders.append(wc.proxy.UnchunkStream.UnchunkStream()) wc.proxy.Headers.client_remove_encoding_headers(self.headers) self.bytes_remaining = None if self.bytes_remaining is None: self.persistent = False if not self.hostname and self.headers.has_key('Host'): if self.method == 'CONNECT': defaultport = 443 else: defaultport = 80 host = self.headers['Host'] self.hostname, self.port = urllib.splitnport(host, defaultport) if not self.hostname: wc.log.error(wc.LOG_PROXY, "%s missing hostname in request", self) self.error(400, _("Bad Request")) # local request? if self.hostname in wc.proxy.dns_lookups.resolver.localhosts and \ self.port == wc.configuration.config['port']: # this is a direct proxy call, jump directly to content self.state = 'content' return # add missing host headers for HTTP/1.1 if not self.headers.has_key('Host'): wc.log.warn(wc.LOG_PROXY, "%s request without Host header encountered", self) if self.port != 80: self.headers['Host'] = "%s:%d\r" % (self.hostname, self.port) else: self.headers['Host'] = "%s\r" % self.hostname if wc.configuration.config["proxyuser"]: creds = wc.proxy.auth.get_header_credentials(self.headers, 'Proxy-Authorization') if not creds: auth = ", ".join(wc.proxy.auth.get_challenges()) self.error(407, _("Proxy Authentication Required"), auth=auth) return if 'NTLM' in creds: if creds['NTLM'][0]['type'] == \ wc.proxy.auth.ntlm.NTLMSSP_NEGOTIATE: attrs = { 'host': creds['NTLM'][0]['host'], 'domain': creds['NTLM'][0]['domain'], 'type': wc.proxy.auth.ntlm.NTLMSSP_CHALLENGE, } auth = ",".join(wc.proxy.auth.get_challenges(**attrs)) self.error(407, _("Proxy Authentication Required"), auth=auth) return # XXX the data=None argument should hold POST data if not wc.proxy.auth.check_credentials(creds, username=wc.configuration.config['proxyuser'], password_b64=wc.configuration.config['proxypass'], uri=wc.proxy.auth.get_auth_uri(self.url), method=self.method, data=None): wc.log.warn(wc.LOG_AUTH, "Bad proxy authentication from %s", self.addr[0]) auth = ", ".join(wc.proxy.auth.get_challenges()) self.error(407, _("Proxy Authentication Required"), auth=auth) return if self.method in ['OPTIONS', 'TRACE'] and \ wc.proxy.Headers.client_get_max_forwards(self.headers) == 0: # XXX display options ? self.state = 'done' headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = 'text/plain\r' wc.proxy.ServerHandleDirectly.ServerHandleDirectly(self, '%s 200 OK' % self.protocol, 200, headers, '') return if self.needs_redirect: self.state = 'done' headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = 'text/plain\r' headers['Location'] = '%s\r' % self.url wc.proxy.ServerHandleDirectly.ServerHandleDirectly(self, '%s 302 Found' % self.protocol, 302, headers, '') return self.state = 'content'
90af7d84c582f452b47b4d557e2b90b2bf2731b0 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/90af7d84c582f452b47b4d557e2b90b2bf2731b0/HttpClient.py
return result.rstrip().lstrip('\x08').replace(' \x08', '')
result = result.lstrip('\x08').strip().replace(' \x08', '') return result
def classify (self, f): if not self.entries: raise StandardError("Not initialised properly") # Are we still looking for the ruleset to apply or are we in a rule found_rule = False # If we failed part of the rule there is no point looking for # higher level subrule allow_next = 0 # String provided by the successfull rule result = ""
9d58ec4c10acdbb97f6bdd06bf2f23d5cfb686fa /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/9d58ec4c10acdbb97f6bdd06bf2f23d5cfb686fa/__init__.py
attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY],
attrs = wc.filter.get_filterattrs(fname, "127.0.0.1", [wc.filter.STAGE_RESPONSE_MODIFY],
def _main (): """USAGE: test/run.sh test/filterfile.py <config dir> <.html file>""" if len(sys.argv)!=3: print _main.__doc__ sys.exit(1) confdir = sys.argv[1] fname = sys.argv[2] if fname=="-": f = sys.stdin else: f = file(fname) logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name, filelogs=False) wc.configuration.config = wc.configuration.init(confdir=confdir) wc.configuration.config.init_filter_modules() wc.proxy.dns_lookups.init_resolver() headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = "text/html" attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY], headers=headers, serverheaders=headers) filtered = "" data = f.read(2048) while data: print >>sys.stderr, "Test: data", len(data) try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs) except wc.filter.FilterException, msg: print >>sys.stderr, "Test: exception:", msg pass data = f.read(2048) print >>sys.stderr, "Test: finishing" i = 1 while True: print >>sys.stderr, "Test: finish", i try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs) break except wc.filter.FilterException, msg: print >>sys.stderr, "Test: finish: exception:", msg wc.proxy.proxy_poll(timeout=max(0, wc.proxy.run_timers())) i += 1 if i==200: # background downloading if javascript is too slow print >>sys.stderr, "Test: oooooops" break print "Filtered:", filtered
678ba849fbf388983e9878b8f7f0379239e5ab00 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/678ba849fbf388983e9878b8f7f0379239e5ab00/filterfile.py
filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs)
filtered += wc.filter.applyfilter( wc.filter.STAGE_RESPONSE_MODIFY, data, 'filter', attrs)
def _main (): """USAGE: test/run.sh test/filterfile.py <config dir> <.html file>""" if len(sys.argv)!=3: print _main.__doc__ sys.exit(1) confdir = sys.argv[1] fname = sys.argv[2] if fname=="-": f = sys.stdin else: f = file(fname) logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name, filelogs=False) wc.configuration.config = wc.configuration.init(confdir=confdir) wc.configuration.config.init_filter_modules() wc.proxy.dns_lookups.init_resolver() headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = "text/html" attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY], headers=headers, serverheaders=headers) filtered = "" data = f.read(2048) while data: print >>sys.stderr, "Test: data", len(data) try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs) except wc.filter.FilterException, msg: print >>sys.stderr, "Test: exception:", msg pass data = f.read(2048) print >>sys.stderr, "Test: finishing" i = 1 while True: print >>sys.stderr, "Test: finish", i try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs) break except wc.filter.FilterException, msg: print >>sys.stderr, "Test: finish: exception:", msg wc.proxy.proxy_poll(timeout=max(0, wc.proxy.run_timers())) i += 1 if i==200: # background downloading if javascript is too slow print >>sys.stderr, "Test: oooooops" break print "Filtered:", filtered
678ba849fbf388983e9878b8f7f0379239e5ab00 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/678ba849fbf388983e9878b8f7f0379239e5ab00/filterfile.py
filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs)
filtered += wc.filter.applyfilter( wc.filter.STAGE_RESPONSE_MODIFY, "", 'finish', attrs)
def _main (): """USAGE: test/run.sh test/filterfile.py <config dir> <.html file>""" if len(sys.argv)!=3: print _main.__doc__ sys.exit(1) confdir = sys.argv[1] fname = sys.argv[2] if fname=="-": f = sys.stdin else: f = file(fname) logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name, filelogs=False) wc.configuration.config = wc.configuration.init(confdir=confdir) wc.configuration.config.init_filter_modules() wc.proxy.dns_lookups.init_resolver() headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = "text/html" attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY], headers=headers, serverheaders=headers) filtered = "" data = f.read(2048) while data: print >>sys.stderr, "Test: data", len(data) try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs) except wc.filter.FilterException, msg: print >>sys.stderr, "Test: exception:", msg pass data = f.read(2048) print >>sys.stderr, "Test: finishing" i = 1 while True: print >>sys.stderr, "Test: finish", i try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs) break except wc.filter.FilterException, msg: print >>sys.stderr, "Test: finish: exception:", msg wc.proxy.proxy_poll(timeout=max(0, wc.proxy.run_timers())) i += 1 if i==200: # background downloading if javascript is too slow print >>sys.stderr, "Test: oooooops" break print "Filtered:", filtered
678ba849fbf388983e9878b8f7f0379239e5ab00 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/678ba849fbf388983e9878b8f7f0379239e5ab00/filterfile.py
wc.log.debug(wc.LOG_PROXY, '%s server_response %r (%d)',
wc.log.debug(wc.LOG_PROXY, '%s server_response %r (%r)',
def server_response (self, server, response, status, headers): """read and filter server response data""" assert server.connected, "%s server was not connected" % self wc.log.debug(wc.LOG_PROXY, '%s server_response %r (%d)', self, response, status) # try google options if status in wc.google.google_try_status and \ wc.configuration.config['try_google']: server.client_abort() self.try_google(self.url, response) else: self.server = server self.write("%s\r\n" % response) if not headers.has_key('Content-Length'): # without content length the client can not determine # when all data is sent self.persistent = False #self.set_persistent(headers, self.http_ver) # note: headers is a WcMessage object, not a dict self.write("".join(headers.headers)) self.write('\r\n')
492eae8bb92f29216c4f8c0df18bd8b285ec8264 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/492eae8bb92f29216c4f8c0df18bd8b285ec8264/HttpClient.py
f = tarfile.gzopen(source)
f = TarFile.gzopen(source)
def blacklist (file): source = "downloads/"+file # extract tar if file.endswith(".tar.gz"): print "extracting archive..." d = "extracted/"+file[:-7] f = tarfile.gzopen(source) for m in f: a, b = os.path.split(m.name) a = os.path.basename(a) if b in myfiles and a in mycats: print m.name f.extract(m, d) f.close() read_blacklists(d) elif file.endswith(".gz"): print "gunzip..." f = gzip.open(source) file = "extracted/"+file[:-3] os.makedirs(os.path.dirname(file)) w = open(file, 'wb') w.write(f.read()) w.close() f.close() read_data(file, "domains", domains)
a5d285909d75ddb5c2beda0199d259fc4c1ccc7a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/a5d285909d75ddb5c2beda0199d259fc4c1ccc7a/bl2wc.py
if not os.path.exists(small_file):
if not os.path.exists("downloads/%s"%smallfile):
def dmozlists (file): print "filtering %s..." % file smallfile = "small_%s"%file if not os.path.exists(small_file): os.system(("zcat downloads/%s | config/dmozfilter.py | "+ \ "gzip --best > downloads/%s") % (file, smallfile)) file = smallfile print "dmozlist %s..." % file f = gzip.GzipFile("downloads/"+file) line = f.readline() topic = None while line: line = line.strip() if line.startswith("<Topic r:id="): topic = line[13:line.rindex('"')].split("/", 2)[1].lower() elif topic=='kids_and_teens' and line.startswith("<link r:resource="): #split url, and add to domains or urls url = line[18:line.rindex('"')] if url.startswith("http://"): url = url[7:] tup = url.split("/", 1) if len(tup)>1 and tup[1]: categories.setdefault(topic, {})["urls"] = None entry = "%s/%s" % (tup[0].lower(), tup[1]) urls.setdefault(entry, {})[topic] = None else: categories.setdefault(topic, {})["domains"] = None domains.setdefault(tup[0].lower(), {})[topic] = None line = f.readline() f.close()
a5d285909d75ddb5c2beda0199d259fc4c1ccc7a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/a5d285909d75ddb5c2beda0199d259fc4c1ccc7a/bl2wc.py
lines.append(' bindaddress="%s"' % xmlquoteattr(self['bindaddress'))
lines.append(' bindaddress="%s"' % xmlquoteattr(self['bindaddress']))
def write_proxyconf (self): """write proxy configuration""" lines = [] lines.append('<?xml version="1.0" encoding="%s"?>' % ConfigCharset) lines.append('<!DOCTYPE webcleaner SYSTEM "webcleaner.dtd">') lines.append('<webcleaner') lines.append(' version="%s"' % xmlquoteattr(self['version'])) lines.append(' bindaddress="%s"' % xmlquoteattr(self['bindaddress')) lines.append(' port="%d"' % self['port']) lines.append(' sslport="%d"' % self['sslport']) if self['sslgateway']: lines.append(' sslgateway="%d"' % self['sslgateway']) lines.append(' adminuser="%s"' % xmlquoteattr(self['adminuser'])) lines.append(' adminpass="%s"' % xmlquoteattr(self['adminpass'])) lines.append(' proxyuser="%s"' % xmlquoteattr(self['proxyuser'])) lines.append(' proxypass="%s"' % xmlquoteattr(self['proxypass'])) if self['parentproxy']: lines.append(' parentproxy="%s"' % xmlquoteattr(self['parentproxy'])) lines.append(' parentproxyuser="%s"' % xmlquoteattr(self['parentproxyuser'])) lines.append(' parentproxypass="%s"' % xmlquoteattr(self['parentproxypass'])) lines.append(' parentproxyport="%d"' % self['parentproxyport']) lines.append(' timeout="%d"' % self['timeout']) lines.append(' gui_theme="%s"' % xmlquoteattr(self['gui_theme'])) lines.append(' auth_ntlm="%d"' % self['auth_ntlm']) lines.append(' try_google="%d"' % self['try_google']) lines.append(' clamavconf="%s"' % xmlquoteattr(self['clamavconf'])) hosts = self['nofilterhosts'] lines.append(' nofilterhosts="%s"' % xmlquoteattr(",".join(hosts))) hosts = self['allowedhosts'] lines.append(' allowedhosts="%s"' % xmlquoteattr(",".join(hosts))) lines.append('>') for key in self['filters']: lines.append('<filter name="%s"/>' % xmlquoteattr(key)) lines.append('</webcleaner>') f = file(self.configfile, 'w') f.write(os.linesep.join(lines)) f.close()
af5d91f69afbf28af8fee8cd01d152967612ce2c /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/af5d91f69afbf28af8fee8cd01d152967612ce2c/configuration.py
out = wc.webgui.TAL.TALInterpreter.FasterStringIO()
out = wc.webgui.ZTUtils.FasterStringIO()
def render (self, context): """Render this Page Template""" out = wc.webgui.TAL.TALInterpreter.FasterStringIO() __traceback_supplement__ = \
3a21dff7f59de63f55c5456413a737e247577ed8 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/3a21dff7f59de63f55c5456413a737e247577ed8/template.py
"After DELAY seconds, run the CALLBACK function"
"""after DELAY seconds, run the CALLBACK function""" debug(PROXY, "Adding %s to %d timers", callback, len(TIMERS))
def make_timer (delay, callback): "After DELAY seconds, run the CALLBACK function" TIMERS.append( (time.time()+delay, callback) ) TIMERS.sort() debug(PROXY, "%d timers", len(TIMERS))
5ae7beb4f2697f30b450b5a6ff693abdc67d9bf5 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/5ae7beb4f2697f30b450b5a6ff693abdc67d9bf5/__init__.py
debug(PROXY, "%d timers", len(TIMERS))
def make_timer (delay, callback): "After DELAY seconds, run the CALLBACK function" TIMERS.append( (time.time()+delay, callback) ) TIMERS.sort() debug(PROXY, "%d timers", len(TIMERS))
5ae7beb4f2697f30b450b5a6ff693abdc67d9bf5 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/3948/5ae7beb4f2697f30b450b5a6ff693abdc67d9bf5/__init__.py