bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def doit (self, data, **args): # note: data is the complete request method, url, httpver = data.split() debug(FILTER, "block filter working on url %s", `url`) if self.allowed(url): return data blocked = self.strict_whitelist or self.blocked(url) if blocked: debug(FILTER, "blocked url %s", url) if isinstance(blocked, basestring): doc = blocked # index 3, not 2! elif is_image(url): doc = self.block_image else: # XXX hmmm, what about CGI images? # make HTTP HEAD request? doc = self.block_url port = config['port'] if method=='CONNECT': return 'CONNECT https://localhost:%d%s HTTP/1.1'%(port, doc) return 'GET http://localhost:%d%s HTTP/1.1'%(port, doc) return data
defdoit(self,data,**args):#note:dataisthecompleterequestmethod,url,httpver=data.split()debug(FILTER,"blockfilterworkingonurl%s",`url`)ifself.allowed(url):returndatablocked=self.strict_whitelistorself.blocked(url)ifblocked:debug(FILTER,"blockedurl%s",url)ifisinstance(blocked,basestring):doc=blocked#index3,not2!elifis_image(url):doc=self.block_imageelse:#XXXhmmm,whataboutCGIimages?#makeHTTPHEADrequest?doc=self.block_urlport=config['port']ifmethod=='CONNECT':return'CONNECThttps://localhost:%d%sHTTP/1.1'%(port,doc)return'GEThttp://localhost:%d%sHTTP/1.1'%(port,doc)returndata
15,900
def cmdOutput (self, command, args): if self.translator is not None and self.translateContent: self.log.debug("Translating %s" % `args`) self.file.write(self.translator.gettext(args) % \ self.context.getVariableMap()) else: self.file.write (args) self.programCounter += 1
def cmdOutput (self, command, args): if self.translator is not None and self.translateContent: self.log.debug("Translating %s with %s", `args`, str(self.translator)) self.file.write(self.translator.gettext(args) % \ self.context.getVariableMap()) else: self.file.write (args) self.programCounter += 1
15,901
def cmdI18nTranslate (self, command, args): """ args: translation string, translation args, endTagSymbol Translate tag content. If the translation string is an empty string, the translate message id is the tag content. Otherwise, the value of the tag content is the message id. """ # an empty string means use tag content as message id if args[0] == "": self.translateContent = 1 else: result = self.context.evaluate (args[0], self.originalAttributes) if not (result is None or result.isNothing() or result.isDefault()): if self.translator is not None: self.log.debug("Translating %s" % `result.value()`) self.tagContent = (0, self.translator.gettext(result.value()) % \ self.context.getVariableMap()) else: self.tagContent = (0, result.value()) self.movePCForward = self.symbolTable[args[1]] self.programCounter += 1
def cmdI18nTranslate (self, command, args): """ args: translation string, translation args, endTagSymbol Translate tag content. If the translation string is an empty string, the translate message id is the tag content. Otherwise, the value of the tag content is the message id. """ # an empty string means use tag content as message id if args[0] == "": self.translateContent = 1 else: result = self.context.evaluate (args[0], self.originalAttributes) if not (result is None or result.isNothing() or result.isDefault()): if self.translator is not None: self.log.debug("Translating %s with %s", `result.value()`, str(self.translator)) self.tagContent = (0, self.translator.gettext(result.value()) % \ self.context.getVariableMap()) else: self.tagContent = (0, result.value()) self.movePCForward = self.symbolTable[args[1]] self.programCounter += 1
15,902
def cmdI18nAttributes (self, command, args):
def cmdI18nAttributes (self, command, args):
15,903
def _write_color_nt (text, color): """ Assumes WConio has been imported at module level. """ oldcolor = WConio.gettextinfo()[4] oldtextcolor = oldcolor & 0x000F if ";" in color: control, color = color.split(";", 1) WConio.textcolor(WConioColor.get(color, oldtextcolor)) fp.write(text) WConio.textattr(oldcolor)
def _write_color_nt (fp, text, color): """ Assumes WConio has been imported at module level. """ oldcolor = WConio.gettextinfo()[4] oldtextcolor = oldcolor & 0x000F if ";" in color: control, color = color.split(";", 1) WConio.textcolor(WConioColor.get(color, oldtextcolor)) fp.write(text) WConio.textattr(oldcolor)
15,904
def debug (log, msg, *args): #logging.getLogger(log).debug("collected %d"%gc.collect()) #logging.getLogger(log).debug("objects %d"%len(gc.get_objects())) #logging.getLogger(log).debug("garbage %d"%len(gc.garbage)) #logging.getLogger(log).debug("Mem: %s"%usedmemory()) logging.getLogger(log).debug(msg, *args)
def debug (log, msg, *args): #logging.getLogger(log).debug("collected %d"%gc.collect()) #logging.getLogger(log).debug("objects %d"%len(gc.get_objects())) #logging.getLogger(log).debug("garbage %d"%len(gc.garbage)) #logging.getLogger(log).debug("Mem: %s"%usedmemory())
15,905
def testImgWidthHeight (self): for tag in ("width", "height"): self.filt("""<img %s="9999">""" % tag, """<img %s="9999">""" % tag) self.filt("""<img %s="12345">""" % tag, """<img>""" % tag)
def testImgWidthHeight (self): for tag in ("width", "height"): self.filt("""<img %s="9999">""" % tag, """<img %s="9999">""" % tag) self.filt("""<img %s="12345">""" % tag, """<img>""" % tag)
15,906
def new_instance (self, **opts): JSFilter(self.url, **opts)
def new_instance (self, **opts): JSFilter(self.url, **opts)
15,907
def __setitem__ (self, key, value): if value not in self: super(SetList), self).__setitem__(key, value)
def __setitem__ (self, key, value): if value not in self: super(SetList), self).__setitem__(key, value)
15,908
def fix_install_path (line): """ Replace placeholders written by bdist_wininst with those specified in win_path_scheme. """ key, eq, val = line.split() # unescape string (do not use eval()) val = val[1:-1].replace("\\\\", "\\") for d in win_path_scheme.keys(): # look for placeholders to replace oldpath, newpath = win_path_scheme[d] oldpath = "%s%s" % (os.sep, oldpath) if oldpath in val: val = val.replace(oldpath, newpath) val = os.path.join(sys.prefix, val) val = os.path.normpath(val) return "%s = %r%s" % (key, val, os.linesep)
def fix_install_path (line): """ Replace placeholders written by bdist_wininst with those specified in win_path_scheme. """ key, eq, val = line.split() # unescape string (do not use eval()) val = val[1:-1].replace("\\\\", "\\") for d in win_path_scheme.keys(): # look for placeholders to replace oldpath, newpath = win_path_scheme[d] oldpath = "%s%s" % (os.sep, oldpath) if oldpath in val: val = val.replace(oldpath, newpath) val = os.path.join(sys.prefix, val) val = os.path.normpath(val) return "%s = %r%s" % (key, val, os.linesep)
15,909
def state_nt_service (name): """ Return status of NT service. """ try: return win32serviceutil.QueryServiceStatus(name)[1] except pywintypes.error, msg: print _("Service status error: %s") % str(msg) return None
def state_nt_service (name): """ Return status of NT service. """ try: return win32serviceutil.QueryServiceStatus(name)[1] except pywintypes.error, msg: print _("Service status error: %s") % str(msg) return None
15,910
def open_browser_config (): # sleep a while to let the proxy start... import wc import wc.configuration state = state_nt_service(wc.AppName) while state==win32service.SERVICE_START_PENDING: time.sleep(1) state = state_nt_service(wc.AppName) time.sleep(3) # open configuration config = wc.configuration.init() config_url = "http://localhost:%d/" % config['port'] open_browser(config_url)
def""" Open the WebCleaner administration web interface. """ open_browser_config""" Open the WebCleaner administration web interface. """ ():""" Open the WebCleaner administration web interface. """ #""" Open the WebCleaner administration web interface. """ sleep""" Open the WebCleaner administration web interface. """ a""" Open the WebCleaner administration web interface. """ while""" Open the WebCleaner administration web interface. """ to""" Open the WebCleaner administration web interface. """ let""" Open the WebCleaner administration web interface. """ the""" Open the WebCleaner administration web interface. """ proxy""" Open the WebCleaner administration web interface. """ start...""" Open the WebCleaner administration web interface. """ import""" Open the WebCleaner administration web interface. """ wc""" Open the WebCleaner administration web interface. """ import""" Open the WebCleaner administration web interface. """ wc.configuration""" Open the WebCleaner administration web interface. """ state""" Open the WebCleaner administration web interface. """ =""" Open the WebCleaner administration web interface. """ state_nt_service(wc.AppName)""" Open the WebCleaner administration web interface. """ while""" Open the WebCleaner administration web interface. """ state==win32service.SERVICE_START_PENDING:""" Open the WebCleaner administration web interface. """ time.sleep(1)""" Open the WebCleaner administration web interface. """ state""" Open the WebCleaner administration web interface. """ =""" Open the WebCleaner administration web interface. """ state_nt_service(wc.AppName)""" Open the WebCleaner administration web interface. """ time.sleep(3)""" Open the WebCleaner administration web interface. """ #""" Open the WebCleaner administration web interface. """ open""" Open the WebCleaner administration web interface. """ configuration""" Open the WebCleaner administration web interface. """ config""" Open the WebCleaner administration web interface. """ =""" Open the WebCleaner administration web interface. """ wc.configuration.init()""" Open the WebCleaner administration web interface. """ config_url""" Open the WebCleaner administration web interface. """ =""" Open the WebCleaner administration web interface. """ "http://localhost:%d/"""" Open the WebCleaner administration web interface. """ %""" Open the WebCleaner administration web interface. """ config['port']""" Open the WebCleaner administration web interface. """ open_browser(config_url)""" Open the WebCleaner administration web interface. """ """ Open the WebCleaner administration web interface. """
15,911
def purge_tempfiles (): """ Ask if user wants to purge local config files. """ files = glob.glob(os.path.join(wc.ConfigDir, "local_*.zap")) if not files: return from Tkinter import tkMessageBox answer = tkMessageBox.askyesno(_("Purge local config"), _("""Do you want to remove your local filter rules?
def purge_tempfiles (): """ Ask if user wants to purge local config files. """ files = glob.glob(os.path.join(wc.ConfigDir, "local_*.zap")) if not files: return from Tkinter import tkMessageBox answer = tkMessageBox.askyesno(_("Purge local config"), _("""Do you want to remove your local filter rules?
15,912
def remove_file (fname): """ Remove a single file if it exists. Errors are printed to stdout. """ if os.path.exists(fname): try: os.remove(fname) except OSError, msg: print _("Could not remove %r: %s") % (fname, str(msg))
def remove_file (fname): """ Remove a single file if it exists. Errors are printed to stdout. """ if os.path.exists(fname): try: os.remove(fname) except OSError, msg: print _("Could not remove file %r: %s") % (fname, str(msg)) def is_empty_dir (name): """ Check if given name is a non-empty directory. """ return os.path.isdir(name) and not os.listdir(name) def remove_empty_directories (dname): """ Remove empty directory structure. """ try: if is_empty_dir(dname): os.rmdir(dname) remove_empty_directories(os.path.dirname(dname)) except OSError, msg: print _("Could not remove directory %r: %s") % (dname, str(msg))
15,913
def dump (o, f): """pickle object o to file f""" cPickle.dump(o, f, pickle.HIGHEST_PROTOCOL)
def dump (o, f): """pickle object o to file f""" cPickle.dump(o, f, pickle.HIGHEST_PROTOCOL)
15,914
def _offset (self, text): direct = self._direct_offset(text) offset_type = 'l' offset_delta = 0L offset_relatif = 0L
def _offset (self, text): direct = self._direct_offset(text) offset_type = 'l' offset_delta = 0L offset_relatif = 0L
15,915
def read_magic (self, magic_file): self.magic = []
def read_magic (self, magic_file): self.magic = []
15,916
def _convert (self, kind, endian, data): # Can raise StandardError and IOError value = 0
def _convert (self, kind, endian, data): # Can raise StandardError and IOError value = 0
15,917
def toxml (self): """Rule data as XML for storing, must be overridden in subclass""" s = u'<Rule %s sid="%s"' % (self.get_name(), wc.XmlUtils.xmlquoteattr(self.sid)) if self.disable: s += u' disable="%d"' % self.disable return s
def toxml (self): """Rule data as XML for storing, must be overridden in subclass""" s = u'<%s sid="%s"' % (self.get_name(), wc.XmlUtils.xmlquoteattr(self.sid)) if self.disable: s += u' disable="%d"' % self.disable return s
15,918
def testAppletHspace (self): self.filt("""<frameset><frame src="aaa"><embed name="sp", style><applet hspace="file:\\">""", """<frameset><frame src="aaa"><embed name="sp", style><applet>""")
def testAppletHspace (self): self.filt("""<frameset><frame src="aaa"><embed name="sp", style><applet hspace="file:\\">""", """<frameset><frame src="aaa"><embed name="sp", style><applet>""")
15,919
def jsScriptSrc (self, url, language): if not url: return url = urlparse.urljoin(self.url, url) #debug(HURT_ME_PLENTY, "jsScriptSrc", url, language) try: script = urlutils.open_url(url).read() except: print >>sys.stderr, "exception fetching script url", `url` return if not script: return ver = 0.0 if language: mo = re.search(r'(?i)javascript(?P<num>\d\.\d)', language) if mo: ver = float(mo.group('num')) self.jsScript(script, ver) return 1
def jsScriptSrc (self, url, language): if not url: return url = urlparse.urljoin(self.url, url) #debug(HURT_ME_PLENTY, "jsScriptSrc", url, language) try: script = urlutils.open_url(url).read() except: print >>sys.stderr, "exception fetching script url", `url` return if not script: return ver = 0.0 if language: mo = re.search(r'(?i)javascript(?P<num>\d\.\d)', language) if mo: ver = float(mo.group('num')) self.jsScript(script, ver) return 1
15,920
def jsScript (self, script, ver): """execute given script with javascript version ver""" #debug(HURT_ME_PLENTY, "jsScript", script, ver) 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) self.jsfilter.flush() self.data.append(self.jsfilter.flushbuf()) self.buffer += self.jsfilter.buffer self.rulestack += self.jsfilter.rulestack self.jsfilter = None
def jsScript (self, script, ver): """execute given script with javascript version ver return True if the script generates any output, else False""" #debug(HURT_ME_PLENTY, "jsScript", script, ver) 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) self.jsfilter.flush() self.data.append(self.jsfilter.flushbuf()) self.buffer += self.jsfilter.buffer self.rulestack += self.jsfilter.rulestack self.jsfilter = None
15,921
def jsScript (self, script, ver): """execute given script with javascript version ver""" #debug(HURT_ME_PLENTY, "jsScript", script, ver) 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) self.jsfilter.flush() self.data.append(self.jsfilter.flushbuf()) self.buffer += self.jsfilter.buffer self.rulestack += self.jsfilter.rulestack self.jsfilter = None
def jsScript (self, script, ver): """execute given script with javascript version ver""" #debug(HURT_ME_PLENTY, "jsScript", script, ver) 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.data.append(self.jsfilter.flushbuf()) self.buffer += self.jsfilter.buffer self.rulestack += self.jsfilter.rulestack self.jsfilter = None
15,922
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.
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.
15,923
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
def jsEndElement (self, tag): """parse generated html for scripts return True if the script generates any output, else False""" if len(self.buffer)<2: return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
15,924
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() if not (self.buffer[-2][0]==STARTTAG and \ self.buffer[-2][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
15,925
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
15,926
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): i = script.index('\n') if i==-1: script = script[4:] else: script = script[(i+1):] if script.endswith("-->"): script = script[:-3] if not script: return self.jsScript(script, 0.0)
15,927
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
def jsEndElement (self, tag): """parse generated html for scripts""" if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return if self.buffer[-1][0]!=DATA: print >>sys.stderr, "missing data for </script>", self.buffer[-1:] return script = self.buffer[-1][1].strip() del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): # there was a <script src="..."> already return del self.buffer[-1] if script.startswith("<!--"): script = script[4:].strip() if not script: return self.jsScript(script, 0.0)
15,928
def finish (self, data, **attrs): if not attrs.has_key('filter'): return data p = attrs['filter'] if data: p.feed(data) p.flush() p.buf2data() return p.flushbuf()
def finish (self, data, **attrs): if not attrs.has_key('filter'): return data p = attrs['filter'] if data: p.feed(data) p.flush() p.buf2data() return p.flushbuf()
15,929
def _buf2data (buf, outbuf): """Append all tags of the buffer to the data""" for item in buf: if item[0]==DATA: outbuf.write(item[1]) elif item[0]==STARTTAG: s = "<"+item[1] for name,val in item[2].items(): s += ' %s'%name if val: s += "=%s"%val outbuf.write(s+">") elif item[0]==ENDTAG: outbuf.write("</%s>"%item[1]) elif item[0]==COMMENT: outbuf.write("<!--%s-->"%item[1]) else: error("unknown buffer element %s" % item[0])
def _buf2data (buf, outbuf): """Append all tags of the buffer to the data""" for item in buf: if item[0]==DATA: outbuf.write(item[1]) elif item[0]==STARTTAG: s = "<"+item[1] for name,val in item[2].items(): s += ' %s'%name if val: s += "=%s"%val outbuf.write(s+">") elif item[0]==ENDTAG: outbuf.write("</%s>"%item[1]) elif item[0]==COMMENT: outbuf.write("<!--%s-->"%item[1]) else: error("unknown buffer element %s" % item[0])
15,930
def feed (self, data): if self.state=='parse': if self.waited: data = "%s%s%s" % (self.waitbuf.getvalue(), self.inbuf.getvalue(), data) self.inbuf.close() self.waitbuf.close() self.inbuf = StringIO() self.waitbuf = StringIO() self.waited = 0 HtmlParser.feed(self, data) else: self.inbuf.write(data)
def feed (self, data): if self.state=='parse': if self.waited: data = "%s%s" % (self.waitbuf.getvalue(), self.inbuf.getvalue(), ) self.inbuf.close() self.waitbuf.close() self.inbuf = StringIO() self.waitbuf = StringIO() self.waited = 0 HtmlParser.feed(self, data) else: self.inbuf.write(data)
15,931
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 _buf2data([item], self.waitbuf) 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, "Filter: 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, "Filter: 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 its not yet filtered, try filter javascript if filtered: self.buf_append_data(item) elif self.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 or tag!='script'): self.buf2data()
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 _buf2data([item], self.waitbuf) 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, "Filter: 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 its not yet filtered, try filter javascript if filtered: self.buf_append_data(item) elif self.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 or tag!='script'): self.buf2data()
15,932
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 _buf2data([item], self.waitbuf) 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, "Filter: 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, "Filter: 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 its not yet filtered, try filter javascript if filtered: self.buf_append_data(item) elif self.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 or tag!='script'): self.buf2data()
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 _buf2data([item], self.waitbuf) 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, "Filter: 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 its not yet filtered, try filter javascript if filtered: self.buf_append_data(item) elif self.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 or tag!='script'): self.buf2data()
15,933
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 _buf2data([item], self.waitbuf) 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, "Filter: 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, "Filter: 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 its not yet filtered, try filter javascript if filtered: self.buf_append_data(item) elif self.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 or tag!='script'): self.buf2data()
defstartElement(self,tag,attrs):"""Wegetanewstarttag.Newrulescouldbeappendedtothependingrules.Norulescanberemovedfromthelist."""#defaultdataitem=[STARTTAG,tag,attrs]ifself.state=='wait':return_buf2data([item],self.waitbuf)rulelist=[]filtered=0#lookforfilterruleswhichapplyforruleinself.rules:ifrule.match_tag(tag)andrule.match_attrs(attrs):debug(NIGHTMARE,"Filter:matchedrule%sontag%s"%(`rule.title`,`tag`))ifrule.start_sufficient:item=rule.filter_tag(tag,attrs)filtered="True"#give'emachancetoreplacemorethanoneattributeifitem[0]==STARTTAGanditem[1]==tag:foo,tag,attrs=itemcontinueelse:breakelse:debug(NIGHTMARE,"Filter:putonbuffer")rulelist.append(rule)ifrulelist:#rememberbufferpositionforendtagmatchingpos=len(self.buf)self.rulestack.append((pos,rulelist))#ifitsnotyetfiltered,tryfilterjavascriptiffiltered:self.buf_append_data(item)elifself.javascript:self.jsStartElement(tag,attrs)else:self.buf.append(item)#ifrulestackisempty,writeoutthebuffereddataifnotself.rulestackand\(notself.javascriptortag!='script'):self.buf2data()
15,934
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 _buf2data([item], self.waitbuf) 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, "Filter: 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, "Filter: 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 its not yet filtered, try filter javascript if filtered: self.buf_append_data(item) elif self.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 or tag!='script'): self.buf2data()
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 _buf2data([item], self.waitbuf) 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, "Filter: 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, "Filter: 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 its not yet filtered, try filter javascript if filtered: self.buf_append_data(item) elif self.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()
15,935
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.
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.
15,936
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.
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.
15,937
def jsStartElement (self, tag, attrs): """Check popups for onmouseout and onmouseover. Inline extern javascript sources (only in the same domain)""" changed = 0 for name in ('onmouseover', 'onmouseout'): if attrs.has_key(name) and self.jsPopup(attrs, name): del attrs[name] changed = 1 if tag=='form': name = attrs.get('name', attrs.get('id')) self.jsForm(name, attrs.get('action', ''), attrs.get('target', '')) elif tag=='script': lang = attrs.get('language', '').lower() url = attrs.get('src', '') scrtype = attrs.get('type', '').lower() is_js = scrtype=='text/javascript' or \ lang.startswith('javascript') or \ not (lang or scrtype) if is_js and url: self.jsScriptSrc(url, lang) self.buf.append((STARTTAG, tag, attrs))
def jsStartElement (self, tag, attrs): """Check popups for onmouseout and onmouseover. Inline extern javascript sources (only in the same domain)""" changed = 0 for name in ('onmouseover', 'onmouseout'): if attrs.has_key(name) and self.jsPopup(attrs, name): del attrs[name] changed = 1 if tag=='form': name = attrs.get('name', attrs.get('id')) self.jsForm(name, attrs.get('action', ''), attrs.get('target', '')) elif tag=='script': lang = attrs.get('language', '').lower() url = attrs.get('src', '') scrtype = attrs.get('type', '').lower() is_js = scrtype=='text/javascript' or \ lang.startswith('javascript') or \ not (lang or scrtype) if is_js and url: self.jsScriptSrc(url, lang) self.buf.append((STARTTAG, tag, attrs))
15,938
def jsScriptSrc (self, url, language): 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.script = '' self.state = 'wait' client = HttpProxyClient(self.jsScriptData, (url, ver)) ClientServerMatchmaker(clien t, "GET %s HTTP/1.1" % url, #request {}, #headers '', #content {'nofilter': None}, 'identity', # compress )
def jsScriptSrc (self, url, language): 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.script = '' self.state = 'wait' client = HttpProxyClient(self.jsScriptData, (url, ver)) ClientServerMatchmaker(client, "GET %s HTTP/1.1" % url, #request {}, #headers '', #content {'nofilter': None}, 'identity', # compress )
15,939
def compileRegex (obj, attr, fullmatch=False, flags=0): """ Regex-compile object attribute into <attr>_ro. """ if hasattr(obj, attr): val = getattr(obj, attr) if val: if fullmatch: val = "^%s$" % val setattr(obj, attr+"_ro", re.compile(val, flags))
def compileRegex (obj, attr, fullmatch=False, flags=0): """ Regex-compile object attribute into <attr>_ro. """ if hasattr(obj, attr): val = getattr(obj, attr) if val: if fullmatch: val = "^(%s)$" % val setattr(obj, attr+"_ro", re.compile(val, flags))
15,940
def test_unquote (self): """test quote stripping""" self.assertEquals(linkcheck.strformat.unquote(""), "") self.assertEquals(linkcheck.strformat.unquote(None), None) self.assertEquals(linkcheck.strformat.unquote("'"), "'") self.assertEquals(linkcheck.strformat.unquote("\""), "\"") self.assertEquals(linkcheck.strformat.unquote("\"\""), "") self.assertEquals(linkcheck.strformat.unquote("''"), "") self.assertEquals(linkcheck.strformat.unquote("'a'"), "a") self.assertEquals(linkcheck.strformat.unquote("'a\"'"), "a\"") self.assertEquals(linkcheck.strformat.unquote("'\"a'"), "\"a") self.assertEquals(linkcheck.strformat.unquote('"a\'"'), 'a\'') self.assertEquals(linkcheck.strformat.unquote('"\'a"'), '\'a') # even mis-matching quotes should be removed... self.assertEquals(linkcheck.strformat.unquote("'a\""), "a") self.assertEquals(linkcheck.strformat.unquote("\"a'"), "a")
def test_unquote (self): """test quote stripping""" self.assertEquals(wc.strformat.unquote(""), "") self.assertEquals(wc.strformat.unquote(None), None) self.assertEquals(wc.strformat.unquote("'"), "'") self.assertEquals(wc.strformat.unquote("\""), "\"") self.assertEquals(wc.strformat.unquote("\"\""), "") self.assertEquals(wc.strformat.unquote("''"), "") self.assertEquals(wc.strformat.unquote("'a'"), "a") self.assertEquals(wc.strformat.unquote("'a\"'"), "a\"") self.assertEquals(wc.strformat.unquote("'\"a'"), "\"a") self.assertEquals(wc.strformat.unquote('"a\'"'), 'a\'') self.assertEquals(wc.strformat.unquote('"\'a"'), '\'a') # even mis-matching quotes should be removed... self.assertEquals(linkcheck.strformat.unquote("'a\""), "a") self.assertEquals(linkcheck.strformat.unquote("\"a'"), "a")
15,941
def test_unquote (self): """test quote stripping""" self.assertEquals(linkcheck.strformat.unquote(""), "") self.assertEquals(linkcheck.strformat.unquote(None), None) self.assertEquals(linkcheck.strformat.unquote("'"), "'") self.assertEquals(linkcheck.strformat.unquote("\""), "\"") self.assertEquals(linkcheck.strformat.unquote("\"\""), "") self.assertEquals(linkcheck.strformat.unquote("''"), "") self.assertEquals(linkcheck.strformat.unquote("'a'"), "a") self.assertEquals(linkcheck.strformat.unquote("'a\"'"), "a\"") self.assertEquals(linkcheck.strformat.unquote("'\"a'"), "\"a") self.assertEquals(linkcheck.strformat.unquote('"a\'"'), 'a\'') self.assertEquals(linkcheck.strformat.unquote('"\'a"'), '\'a') # even mis-matching quotes should be removed... self.assertEquals(linkcheck.strformat.unquote("'a\""), "a") self.assertEquals(linkcheck.strformat.unquote("\"a'"), "a")
def test_unquote (self): """test quote stripping""" self.assertEquals(linkcheck.strformat.unquote(""), "") self.assertEquals(linkcheck.strformat.unquote(None), None) self.assertEquals(linkcheck.strformat.unquote("'"), "'") self.assertEquals(linkcheck.strformat.unquote("\""), "\"") self.assertEquals(linkcheck.strformat.unquote("\"\""), "") self.assertEquals(linkcheck.strformat.unquote("''"), "") self.assertEquals(linkcheck.strformat.unquote("'a'"), "a") self.assertEquals(linkcheck.strformat.unquote("'a\"'"), "a\"") self.assertEquals(linkcheck.strformat.unquote("'\"a'"), "\"a") self.assertEquals(linkcheck.strformat.unquote('"a\'"'), 'a\'') self.assertEquals(linkcheck.strformat.unquote('"\'a"'), '\'a') # even mis-matching quotes should be removed... self.assertEquals(linkcheck.strformat.unquote("'a\""), "a") self.assertEquals(linkcheck.strformat.unquote("\"a'"), "a")
15,942
def test_wrap (self): """test line wrapping""" s = "11%(sep)s22%(sep)s33%(sep)s44%(sep)s55" % {'sep': os.linesep} # testing width <= 0 self.assertEquals(linkcheck.strformat.wrap(s, -1), s) self.assertEquals(linkcheck.strformat.wrap(s, 0), s) s2 = "11 22%(sep)s33 44%(sep)s55" % {'sep': os.linesep} # splitting lines self.assertEquals(linkcheck.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
def test_wrap (self): """test line wrapping""" s = "11%(sep)s22%(sep)s33%(sep)s44%(sep)s55" % {'sep': os.linesep} # testing width <= 0 self.assertEquals(wc.strformat.wrap(s, -1), s) self.assertEquals(wc.strformat.wrap(s, 0), s) s2 = "11 22%(sep)s33 44%(sep)s55" % {'sep': os.linesep} # splitting lines self.assertEquals(linkcheck.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
15,943
def test_wrap (self): """test line wrapping""" s = "11%(sep)s22%(sep)s33%(sep)s44%(sep)s55" % {'sep': os.linesep} # testing width <= 0 self.assertEquals(linkcheck.strformat.wrap(s, -1), s) self.assertEquals(linkcheck.strformat.wrap(s, 0), s) s2 = "11 22%(sep)s33 44%(sep)s55" % {'sep': os.linesep} # splitting lines self.assertEquals(linkcheck.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
def test_wrap (self): """test line wrapping""" s = "11%(sep)s22%(sep)s33%(sep)s44%(sep)s55" % {'sep': os.linesep} # testing width <= 0 self.assertEquals(linkcheck.strformat.wrap(s, -1), s) self.assertEquals(linkcheck.strformat.wrap(s, 0), s) s2 = "11 22%(sep)s33 44%(sep)s55" % {'sep': os.linesep} # splitting lines self.assertEquals(wc.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
15,944
def test_wrap (self): """test line wrapping""" s = "11%(sep)s22%(sep)s33%(sep)s44%(sep)s55" % {'sep': os.linesep} # testing width <= 0 self.assertEquals(linkcheck.strformat.wrap(s, -1), s) self.assertEquals(linkcheck.strformat.wrap(s, 0), s) s2 = "11 22%(sep)s33 44%(sep)s55" % {'sep': os.linesep} # splitting lines self.assertEquals(linkcheck.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
def test_wrap (self): """test line wrapping""" s = "11%(sep)s22%(sep)s33%(sep)s44%(sep)s55" % {'sep': os.linesep} # testing width <= 0 self.assertEquals(linkcheck.strformat.wrap(s, -1), s) self.assertEquals(linkcheck.strformat.wrap(s, 0), s) s2 = "11 22%(sep)s33 44%(sep)s55" % {'sep': os.linesep} # splitting lines self.assertEquals(linkcheck.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
15,945
def test_remove_markup (self): """test markup removing""" self.assertEquals(linkcheck.strformat.remove_markup("<a>"), "") self.assertEquals(linkcheck.strformat.remove_markup("<>"), "") self.assertEquals(linkcheck.strformat.remove_markup("<<>"), "") self.assertEquals(linkcheck.strformat.remove_markup("a < b"), "a < b")
def test_remove_markup (self): """test markup removing""" self.assertEquals(linkcheck.strformat.remove_markup("<a>"), "") self.assertEquals(linkcheck.strformat.remove_markup("<>"), "") self.assertEquals(linkcheck.strformat.remove_markup("<<>"), "") self.assertEquals(linkcheck.strformat.remove_markup("a < b"), "a < b")
15,946
def test_strsize (self): """test byte size strings""" self.assertRaises(ValueError, linkcheck.strformat.strsize, -1) self.assertEquals(linkcheck.strformat.strsize(0), "0 Bytes") self.assertEquals(linkcheck.strformat.strsize(1), "1 Byte") self.assertEquals(linkcheck.strformat.strsize(2), "2 Bytes") self.assertEquals(linkcheck.strformat.strsize(1023), "1023 Bytes") self.assertEquals(linkcheck.strformat.strsize(1024), "1.00 kB")
def test_strsize (self): """test byte size strings""" self.assertRaises(ValueError, linkcheck.strformat.strsize, -1) self.assertEquals(linkcheck.strformat.strsize(0), "0 Bytes") self.assertEquals(linkcheck.strformat.strsize(1), "1 Byte") self.assertEquals(linkcheck.strformat.strsize(2), "2 Bytes") self.assertEquals(linkcheck.strformat.strsize(1023), "1023 Bytes") self.assertEquals(linkcheck.strformat.strsize(1024), "1.00 kB")
15,947
def rating_parse (data, debug=0): """parse given rating data, throws ParseError on error""" categories = {} for line in data.splitlines(): if debug: debug(RATING, "Read line %r", line) try: category, value = line.split(None, 1) except ValueError, msg: raise RatingParseError(i18n._(",alformed rating line %r")%line) categories[category] = value return categories
def rating_parse (data, debug=0): """parse given rating data, throws ParseError on error""" categories = {} for line in data.splitlines(): if debug: debug(RATING, "Read line %r", line) try: category, value = line.split(None, 1) except ValueError, msg: raise RatingParseError(i18n._("malformed rating line %r")%line) categories[category] = value return categories
15,948
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self._debug(ALWAYS, "self.inbuf", `self.inbuf.getvalue()`) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data #self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: #self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer #self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data #self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: #self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer #self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
15,949
def emit (self, record): """ A little more verbose emit function. """ try: msg = self.format(record) self.stream.write("%s\n" % msg) self.flush() except: print >>sys.stderr, "Could not format record", record self.handleError()
def emit (self, record): """ A little more verbose emit function. """ try: msg = self.format(record) self.stream.write("%s\n" % msg) self.flush() except: print >>sys.stderr, "Could not format record", record self.handleError()
15,950
def open_files (directory): for cat in categories.keys(): if cat=='kids_and_teens': d='whitelists' else: d='blacklists' basedir = "%s/%s/%s" % (directory, d, cat) if not os.path.isdir(basedir): os.makedirs(basedir) for ftype in categories[cat].keys(): if ftype=="expressions": continue fname = "%s/%s.gz" % (basedir, ftype) if os.path.exists(fname): os.remove(fname) print "opening", fname categories[cat][type] = gzip.GzipFile(fname, 'wb')
def open_files (directory): for cat in categories.keys(): if cat=='kids_and_teens': d='whitelists' else: d='blacklists' basedir = "%s/%s/%s" % (directory, d, cat) if not os.path.isdir(basedir): os.makedirs(basedir) for ftype in categories[cat].keys(): if ftype=="expressions": continue fname = "%s/%s.gz" % (basedir, ftype) if os.path.exists(fname): os.remove(fname) print "opening", fname categories[cat][ftype] = gzip.GzipFile(fname, 'wb')
15,951
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)
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)
15,952
def write_folder (cat, ftype, data, f): print "write", cat, "folder" d = { "charset": ConfigCharset, "title_en": xmlify("%s %s" % (ftype.capitalize(), cat)), "title_de": xmlify("%s %s" % (transtypes[ftype]['de'].capitalize(), transcats[cat]['de'].capitalize())), "desc_en": xmlify("Automatically generated on %s" % date), "desc_de": xmlify("Automatisch generiert am %s" % date), } f.write("""<?xml version="1.0" encoding="%(charset)s"?>
def write_folder (cat, ftype, data, f): print "write", cat, "folder" d = { "charset": wc.ConfigCharset, "title_en": wc.XmlUtils.xmlquote("%s %s" % (ftype.capitalize(), cat)), "title_de": wc.XmlUtils.xmlquote("%s %s" % (transtypes[ftype]['de'].capitalize(), transcats[cat]['de'].capitalize())), "desc_en": xmlify("Automatically generated on %s" % date), "desc_de": xmlify("Automatisch generiert am %s" % date), } f.write("""<?xml version="1.0" encoding="%(charset)s"?>
15,953
def write_folder (cat, ftype, data, f): print "write", cat, "folder" d = { "charset": ConfigCharset, "title_en": xmlify("%s %s" % (ftype.capitalize(), cat)), "title_de": xmlify("%s %s" % (transtypes[ftype]['de'].capitalize(), transcats[cat]['de'].capitalize())), "desc_en": xmlify("Automatically generated on %s" % date), "desc_de": xmlify("Automatisch generiert am %s" % date), } f.write("""<?xml version="1.0" encoding="%(charset)s"?>
def write_folder (cat, ftype, data, f): print "write", cat, "folder" d = { "charset": ConfigCharset, "title_en": xmlify("%s %s" % (ftype.capitalize(), cat)), "title_de": xmlify("%s %s" % (transtypes[ftype]['de'].capitalize(), transcats[cat]['de'].capitalize())), "desc_en": wc.XmlUtils.xmlquote("Automatically generated on %s" % date), "desc_de": wc.XmlUtils.xmlquote("Automatisch generiert am %s" % date), } f.write("""<?xml version="1.0" encoding="%(charset)s"?>
15,954
def write_expressions (cat, b, ftype, f): d = { 'title_en': "%s expression filter"%cat.capitalize(), 'title_de': "%s Ausdruckfilter"%transcats[cat]['de'].capitalize(), 'desc_en': """Automatically generated, you should not edit this filter.
def write_expressions (cat, b, ftype, f): d = { 'title_en': "%s expression filter"%cat.capitalize(), 'title_de': "%s Ausdruckfilter"%transcats[cat]['de'].capitalize(), 'desc_en': """Automatically generated, you should not edit this filter.
15,955
def blacklist (fname): source = os.path.join("downloads", fname) # extract tar if fname.endswith(".tar.gz"): print "extracting archive..." d = os.path.join("extracted", fname[:-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 fname.endswith(".gz"): print "gunzip..." f = gzip.open(source) fname = "extracted/"+fname[:-3] os.makedirs(os.path.dirname(fname)) w = file(fname, 'wb') w.write(f.read()) w.close() f.close() read_data(fname, "domains", domains)
def blacklist (fname): source = os.path.join("downloads", fname) # extract tar if fname.endswith(".tar.gz"): print "extracting archive..." d = os.path.join("extracted", fname[:-7]) f = tarfile.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 fname.endswith(".gz"): print "gunzip..." f = gzip.open(source) fname = "extracted/"+fname[:-3] os.makedirs(os.path.dirname(fname)) w = file(fname, 'wb') w.write(f.read()) w.close() f.close() read_data(fname, "domains", domains)
15,956
def open_browser (url): print _("Opening proxy configuration interface...") # the windows webbrowser.open func raises an exception for http:// # urls, but works nevertheless. Just ignore the error. try: webbrowser.open(config_url) except WindowsError, msg: print _("Could not open webbrowser: %r") % str(msg)
def open_browser (url): print _("Opening proxy configuration interface...") # the windows webbrowser.open func raises an exception for http:// # urls, but works nevertheless. Just ignore the error. try: webbrowser.open(url) except WindowsError, msg: print _("Could not open webbrowser: %r") % str(msg)
15,957
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)
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)
15,958
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)
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)
15,959
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)
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)
15,960
def filter (self, data, url): self.url = url self.parser.feed(data) self.parser.flush() self.parser.reset() self.valid = True self.stack = [] data = self.outbuf.getvalue() self.outbuf.close() self.outbuf = StringIO() return data
def filter (self, data, url, rules): encoding = "UTF8" self.parser.encoding = encoding data = data.encode(encoding) self.rules = rules self.url = url self.parser.feed(data) self.parser.flush() self.parser.reset() self.valid = True self.stack = [] data = self.outbuf.getvalue() self.outbuf.close() self.outbuf = StringIO() return data
15,961
def filter (self, data, url): self.url = url self.parser.feed(data) self.parser.flush() self.parser.reset() self.valid = True self.stack = [] data = self.outbuf.getvalue() self.outbuf.close() self.outbuf = StringIO() return data
def filter (self, data, url): self.url = url self.parser.feed(data) self.parser.flush() self.parser.reset() data = self.outbuf.getvalue() self.outbuf.close() self.outbuf = StringIO() return data
15,962
def filter (self, data, url): self.url = url self.parser.feed(data) self.parser.flush() self.parser.reset() self.valid = True self.stack = [] data = self.outbuf.getvalue() self.outbuf.close() self.outbuf = StringIO() return data
def filter (self, data, url): self.url = url self.parser.feed(data) self.parser.flush() self.parser.reset() self.valid = True self.stack = [] data = self.outbuf.getvalue() self.outbuf.close() self.reset() return data
15,963
def _start_element (self, tag, attrs, startend): tag = wc.filter.HtmlTags.check_spelling(tag, self.url) self.stack.append(tag) if not self.valid: return if tag in rss_allowed: self.outbuf.write(u"<%s" % tag) if attrs: quote = wc.HtmlParser.htmllib.quote_attrval for attr in attrs: if attr in rss_allowed[tag]: val = attrs[attr] self.outbuf.write(u' %s="%s"' % (attr, quote(val))) if startend: self.outbuf.write(u"/>") else: self.outbuf.write(u">") elif not startend: self.valid = False self.stack = [tag]
def _start_element (self, tag, attrs, startend): tag = wc.filter.html.check_spelling(tag, self.url) self.stack.append(tag) if not self.valid: return if tag in rss_allowed: self.outbuf.write(u"<%s" % tag) if attrs: quote = wc.HtmlParser.htmllib.quote_attrval for attr in attrs: if attr in rss_allowed[tag]: val = attrs[attr] self.outbuf.write(u' %s="%s"' % (attr, quote(val))) if startend: self.outbuf.write(u"/>") else: self.outbuf.write(u">") elif not startend: self.valid = False self.stack = [tag]
15,964
def connect (self, addr): wc.log.debug(wc.LOG_PROXY, '%s connecting', self) self.connected = False err = self.socket.connect_ex(addr) if err != 0: strerr = errno.errorcode[err] wc.log.debug(wc.LOG_PROXY, '%s connection error %s', self, strerr) # XXX Should interpret Winsock return values if err in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK): wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) elif err in (0, errno.EISCONN): self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() else: raise socket.error, (err, errno.errorcode[err]) return err
def connect (self, addr): wc.log.debug(wc.LOG_PROXY, '%s connecting', self) self.connected = False err = self.socket.connect_ex(addr) if err != 0: strerr = errno.errorcode[err] wc.log.debug(wc.LOG_PROXY, '%s connection error %s', self, strerr) # XXX Should interpret Winsock return values if err in (errno.EINPROGRESS, errno.EWOULDBLOCK): wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) elif err in (0, errno.EISCONN): self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() else: raise socket.error, (err, errno.errorcode[err]) return err
15,965
def check_connect (self, addr): """ Check if the connection is etablished. See also http://cr.yp.to/docs/connect.html """ wc.log.debug(wc.LOG_PROXY, '%s check connect', self) err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err == 0: self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() elif err in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK): wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) else: self.handle_close()
def check_connect (self, addr): """ Check if the connection is etablished. See also http://cr.yp.to/docs/connect.html and connect(2) manpage. """ wc.log.debug(wc.LOG_PROXY, '%s check connect', self) err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err == 0: self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() elif err in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK): wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) else: self.handle_close()
15,966
def check_connect (self, addr): """ Check if the connection is etablished. See also http://cr.yp.to/docs/connect.html """ wc.log.debug(wc.LOG_PROXY, '%s check connect', self) err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err == 0: self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() elif err in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK): wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) else: self.handle_close()
def check_connect (self, addr): """ Check if the connection is etablished. See also http://cr.yp.to/docs/connect.html """ wc.log.debug(wc.LOG_PROXY, '%s check connect', self) err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err == 0: self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() elif err in (errno.EINPROGRESS, errno.EWOULDBLOCK): wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) else: self.handle_close()
15,967
def match_complete (self, pos, tagbuf): """ We know that the tag (and tag attributes) match. Now match the enclosing block. Return True on a match. """ if not self.enclosed: # no enclosed expression => match return True # put buf items together for matching items = tagbuf[pos:] data = wc.filter.html.tagbuf2data(items, StringIO()).getvalue() return self.enclosed_ro.match(data)
def match_complete (self, pos, tagbuf): """ We know that the tag (and tag attributes) match. Now match the enclosing block. Return True on a match. """ if not self.enclosed: # no enclosed expression => match return True # put buf items together for matching items = tagbuf[pos:] data = wc.filter.html.tagbuf2data(items, StringIO()).getvalue() return self.enclosed_ro.match(data)
15,968
def do_GET (self): """send chunk data""" body = random_chars(self.body_length) data = 'HTTP/1.1 200 OK\r\n' data += "Date: %s\r\n" % self.date_time_string() data += "Transfer-Encoding: chunked\r\n" data += "Connection: close\r\n" data += "\r\n" data += "0000000000%d\r\n" % len(body) data += "%s\r\n" % body data += "0\r\n\r\n" self.server.log.write("server will send %d bytes\n" % len(data)) self.print_lines(data) self.wfile.write(data)
def do_GET (self): """send chunk data""" body = random_chars(self.body_length) data = 'HTTP/1.1 200 OK\r\n' data += "Date: %s\r\n" % self.date_time_string() data += "Transfer-Encoding: chunked\r\n" data += "Connection: close\r\n" data += "\r\n" data += "0000000000%s\r\n" % hex(self.body_length)[2:] data += "%s\r\n" % body data += "0\r\n\r\n" self.server.log.write("server will send %d bytes\n" % len(data)) self.print_lines(data) self.wfile.write(data)
15,969
def sighup_reload_config (signum, frame): """store timer for reloading configuration data""" wc.proxy.make_timer(1, reload_config)
def sighup_reload_config (signum, frame): """store timer for reloading configuration data""" global pending_reload if not pending_reload: pending_reload = True wc.proxy.make_timer(1, reload_config)
15,970
def _main (args): """USAGE: test/run.sh test/parsefile.py test.html""" if len(args) < 1: print _main.__doc__ sys.exit(1) from wc.HtmlParser.htmllib import HtmlPrinter, HtmlPrettyPrinter if args[0] == "-p": klass = HtmlPrettyPrinter filename = args[1] else: klass = HtmlPrinter filename = args[0] if filename == '-': f = sys.stdin else: f = open(filename) from wc.HtmlParser import htmlsax p = htmlsax.parser(klass()) #p.debug(1) size = 1024 #size = 1 data = f.read(size) while data: p.feed(data) data = f.read(size) p.flush()
defp.debug(1) _mainp.debug(1) (args):p.debug(1) """USAGE:p.debug(1) test/run.shp.debug(1) test/parsefile.pyp.debug(1) test.html"""p.debug(1) ifp.debug(1) len(args)p.debug(1) <p.debug(1) 1:p.debug(1) printp.debug(1) _main.__doc__p.debug(1) sys.exit(1)p.debug(1) fromp.debug(1) wc.HtmlParser.htmllibp.debug(1) importp.debug(1) HtmlPrinter,p.debug(1) HtmlPrettyPrinterp.debug(1) ifp.debug(1) args[0]p.debug(1) ==p.debug(1) "-p":p.debug(1) klassp.debug(1) =p.debug(1) HtmlPrettyPrinterp.debug(1) filenamep.debug(1) =p.debug(1) args[1]p.debug(1) else:p.debug(1) klassp.debug(1) =p.debug(1) HtmlPrinterp.debug(1) filenamep.debug(1) =p.debug(1) args[0]p.debug(1) ifp.debug(1) filenamep.debug(1) ==p.debug(1) '-':p.debug(1) fp.debug(1) =p.debug(1) sys.stdinp.debug(1) else:p.debug(1) fp.debug(1) =p.debug(1) open(filename)p.debug(1) fromp.debug(1) wc.HtmlParserp.debug(1) importp.debug(1) htmlsaxp.debug(1) pp.debug(1) =p.debug(1) htmlsax.parser(klass())p.debug(1) #p.debug(1)p.debug(1) sizep.debug(1) =p.debug(1) 1024p.debug(1) #sizep.debug(1) =p.debug(1) 1p.debug(1) datap.debug(1) =p.debug(1) f.read(size)p.debug(1) whilep.debug(1) data:p.debug(1) p.feed(data)p.debug(1) datap.debug(1) =p.debug(1) f.read(size)p.debug(1) p.flush()p.debug(1)
15,971
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)
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)
15,972
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)
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)
15,973
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)
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)
15,974
def scan_start_tag (self, tag, attrs, htmlfilter): if tag=="input" and attrs.has_key('type'): # prevent IE crash bug on empty type attribute if not attrs['type']: warn(FILTER, "%s\n Detected and prevented IE <input type> crash bug", str(htmlfilter)) del attrs['type'] elif tag=="fieldset" and attrs.has_key('style'): # prevent Mozilla crash bug on fieldsets if "position" in attrs['style']: warn(FILTER, "%s\n Detected and prevented Mozilla <fieldset style> crash bug", str(htmlfilter)) del attrs['style'] elif tag=="hr" and attrs.has_key('align'): # prevent CAN-2003-0469, length 50 should be safe if len(attrs['align']) > 50: warn(FILTER, "%s\n Detected and prevented IE <hr align> crash bug", str(htmlfilter)) del attrs['align'] elif tag=="object" and attrs.has_key('type'): # prevent CAN-2003-0344, only one / (slash) allowed t = attrs['type'] c = t.count("/") if c > 1: warn(FILTER, "%s\n Detected and prevented IE <object type> bug", str(htmlfilter)) t = t.replace("/", "", c-1) attrs['type'] = t elif tag=='table' and attrs.has_key('width'): # prevent CAN-2003-0238, table width=-1 crashes ICQ client if attrs['width']=='-1': warn(FILTER, "%s\n Detected and prevented ICQ table width crash bug", str(htmlfilter)) del attrs['width'] elif tag=='object' and attrs.has_key('codebase'): self.in_winhelp = attrs['codebase'].lower().startswith('hhctrl.ocx') elif tag=='param' and attrs.has_key('value') and self.in_winhelp: # prevent CVE-2002-0823 if len(attrs['value']) > 50: warn(FILTER, "%s\n Detected and prevented WinHlp overflow bug", str(htmlfilter)) del attrs['value'] elif tag=='meta' and attrs.has_key('content') and self.macintosh: # prevent CVE-2002-0153 if attrs.get('http-equiv', '').lower()=='refresh': url = attrs['content'].lower() if ";" in url: url = url.split(";", 1)[1] if url.startswith('url='): url = url[4:] if url.startswith('file:/'): warn(FILTER, "%s %s\n Detected and prevented local file redirection", str(htmlfilter), `attrs['content']`) del attrs['content'] elif tag=='embed' and attrs.has_key('src'): src = attrs['src'] if "." in src: # prevent CVE-2002-0022 i = src.find('.') if len(src[i:]) > 10: warn(FILTER, "%s %s\n Detected and prevented IE filename overflow crash", str(htmlfilter), `src`) del attrs['src'] elif tag=='font' and attrs.has_key('size'): if len(attrs['size']) > 10: # prevent CVE-2001-0130 warn(FILTER, "%s %s\n Detected and prevented Lotus Domino font size overflow crash", str(htmlfilter), `attrs['size']`) del attrs['size']
def scan_start_tag (self, tag, attrs, htmlfilter): if tag=="input" and attrs.has_key('type'): # prevent IE crash bug on empty type attribute if not attrs['type']: warn(FILTER, "%s\n Detected and prevented IE <input type> crash bug", str(htmlfilter)) del attrs['type'] elif tag=="fieldset" and attrs.has_key('style'): # prevent Mozilla crash bug on fieldsets if "position" in attrs['style']: warn(FILTER, "%s\n Detected and prevented Mozilla <fieldset style> crash bug", str(htmlfilter)) del attrs['style'] elif tag=="hr" and attrs.has_key('align'): # prevent CAN-2003-0469, length 50 should be safe if len(attrs['align']) > 50: warn(FILTER, "%s\n Detected and prevented IE <hr align> crash bug", str(htmlfilter)) del attrs['align'] elif tag=="object" and attrs.has_key('type'): # prevent CAN-2003-0344, only one / (slash) allowed t = attrs['type'] c = t.count("/") if c > 1: warn(FILTER, "%s\n Detected and prevented IE <object type> bug", str(htmlfilter)) t = t.replace("/", "", c-1) attrs['type'] = t elif tag=='table' and attrs.has_key('width'): # prevent CAN-2003-0238, table width=-1 crashes ICQ client if attrs['width']=='-1': warn(FILTER, "%s\n Detected and prevented ICQ table width crash bug", str(htmlfilter)) del attrs['width'] elif tag=='object' and attrs.has_key('codebase'): self.in_winhelp = attrs['codebase'].lower().startswith('hhctrl.ocx') elif tag=='param' and attrs.has_key('value') and self.in_winhelp: # prevent CVE-2002-0823 if len(attrs['value']) > 50: warn(FILTER, "%s\n Detected and prevented WinHlp overflow bug", str(htmlfilter)) del attrs['value'] elif tag=='meta' and attrs.has_key('content') and self.macintosh: # prevent CVE-2002-0153 if attrs.get('http-equiv', '').lower()=='refresh': url = attrs['content'].lower() if ";" in url: url = url.split(";", 1)[1] if url.startswith('url='): url = url[4:] if url.startswith('file:/'): warn(FILTER, "%s %s\n Detected and prevented local file redirection", str(htmlfilter), `attrs['content']`) del attrs['content'] elif tag=='embed' and attrs.has_key('src'): src = attrs['src'] if "." in src: # prevent CVE-2002-0022 i = src.rfind('.') if len(src[i:]) > 10: warn(FILTER, "%s %s\n Detected and prevented IE filename overflow crash", str(htmlfilter), `src`) del attrs['src'] elif tag=='font' and attrs.has_key('size'): if len(attrs['size']) > 10: # prevent CVE-2001-0130 warn(FILTER, "%s %s\n Detected and prevented Lotus Domino font size overflow crash", str(htmlfilter), `attrs['size']`) del attrs['size']
15,975
def filter (self, data, **attrs): if not attrs.has_key('scanner'): return data scanner = attrs['scanner'] if not scanner.infected and data: scanner.scan(data) if not scanner.infected: return data for msg in scanner.infected: warn(FILTER, "Found virus %r in %r", msg, attrs['url']) return ""
def filter (self, data, **attrs): if not attrs.has_key('scanner'): return data scanner = attrs['scanner'] buf = attrs['virus_buf'] if data: scanner.scan(data) if not scanner.infected: return data for msg in scanner.infected: warn(FILTER, "Found virus %r in %r", msg, attrs['url']) return ""
15,976
def filter (self, data, **attrs): if not attrs.has_key('scanner'): return data scanner = attrs['scanner'] if not scanner.infected and data: scanner.scan(data) if not scanner.infected: return data for msg in scanner.infected: warn(FILTER, "Found virus %r in %r", msg, attrs['url']) return ""
def filter (self, data, **attrs): if not attrs.has_key('scanner'): return data scanner = attrs['scanner'] if not scanner.infected and data: scanner.scan(data) buf.write(data) return ""
15,977
def finish (self, data, **attrs): if not attrs.has_key('scanner'): return data scanner = attrs['scanner'] if not scanner.infected and data: scanner.scan(data) scanner.close() for msg in scanner.errors: warn(FILTER, "Virus scanner error %r", msg) if not scanner.infected: return data for msg in scanner.infected: warn(FILTER, "Found virus %r in %r", msg, attrs['url']) return ""
def finish (self, data, **attrs): if not attrs.has_key('scanner'): return data scanner = attrs['scanner'] buf = attrs['virus_buf'] if data: scanner.scan(data) scanner.close() for msg in scanner.errors: warn(FILTER, "Virus scanner error %r", msg) if not scanner.infected: return data for msg in scanner.infected: warn(FILTER, "Found virus %r in %r", msg, attrs['url']) return ""
15,978
def getAttrs (self, url, headers): d = super(VirusFilter, self).getAttrs(url, headers) # weed out the rules that don't apply to this url rules = [ rule for rule in self.rules if rule.appliesTo(url) ] if not rules: return d d['scanner'] = ClamdScanner() return d
def getAttrs (self, url, headers): d = super(VirusFilter, self).getAttrs(url, headers) # weed out the rules that don't apply to this url rules = [ rule for rule in self.rules if rule.appliesTo(url) ] if not rules: return d d['scanner'] = ClamdScanner(get_clamav_conf()) d['virus_buf'] = StringIO() return d
15,979
def __init__ (self): """initialize clamd daemon process connection""" self.infected = [] self.errors = [] self.sock, host = clamav_conf.new_connection() self.wsock = clamav_conf.new_scansock(self.sock, host)
def __init__ (self, clamav_conf): """initialize clamd daemon process sockets""" self.infected = [] self.errors = [] self.sock, host = clamav_conf.new_connection() self.wsock = clamav_conf.new_scansock(self.sock, host)
15,980
def __init__ (self): """initialize clamd daemon process connection""" self.infected = [] self.errors = [] self.sock, host = clamav_conf.new_connection() self.wsock = clamav_conf.new_scansock(self.sock, host)
def __init__ (self): """initialize clamd daemon process connection""" self.infected = [] self.errors = [] self.sock, host = clamav_conf.new_connection() self.wsock = clamav_conf.new_scansock(self.sock, host)
15,981
def scan (self, data): """scan given data for viruses, add results to infected and errors attributes""" self.wsock.sendall(data) data = self.sock.recv(RECV_BUFSIZE) while data: if "FOUND\n" in data: self.infected.append(data) if "ERROR\n" in data: self.errors.append(data) data = self.sock.recv(RECV_BUFSIZE)
def scan (self, data): """scan given data for viruses""" self.wsock.sendall(data) data = self.sock.recv(RECV_BUFSIZE) while data: if "FOUND\n" in data: self.infected.append(data) if "ERROR\n" in data: self.errors.append(data) data = self.sock.recv(RECV_BUFSIZE)
15,982
def scan (self, data): """scan given data for viruses, add results to infected and errors attributes""" self.wsock.sendall(data) data = self.sock.recv(RECV_BUFSIZE) while data: if "FOUND\n" in data: self.infected.append(data) if "ERROR\n" in data: self.errors.append(data) data = self.sock.recv(RECV_BUFSIZE)
def scan (self, data): """scan given data for viruses, add results to infected and errors attributes""" self.wsock.sendall(data) data = self.sock.recv(RECV_BUFSIZE) while data: if "FOUND\n" in data: self.infected.append(data) if "ERROR\n" in data: self.errors.append(data) data = self.sock.recv(RECV_BUFSIZE)
15,983
def close (self): """close clamd daemon connection""" self.sock.close()
def close (self): """close clamd daemon connection""" self.sock.close()
15,984
def init_clamav_conf (): global clamav_conf from wc import config clamav_conf = ClamavConfig(config['clamavconf'])
def init_clamav_conf (): global _clamav_conf from wc import config clamav_conf = ClamavConfig(config['clamavconf'])
15,985
def init_clamav_conf (): global clamav_conf from wc import config clamav_conf = ClamavConfig(config['clamavconf'])
def init_clamav_conf (): global clamav_conf from wc import config _clamav_conf = ClamavConfig(config['clamavconf']) def get_clamav_conf (): return _clamav_conf
15,986
def parse_http_warning (warning): """ Grammar for a warning: Warning = "Warning" ":" 1#warning-value warning-value = warn-code SP warn-agent SP warn-text [SP warn-date] warn-code = 3DIGIT warn-agent = ( host [ ":" port ] ) | pseudonym ; the name or pseudonym of the server adding ; the Warning header, for use in debugging warn-text = quoted-string warn-date = <"> HTTP-date <"> """ try: warncode, warning = warning.split(None, 1) warncode = int(warncode) warnagent, warning = warning.split(None, 1) warntext, warning = split_quoted_string(warning) if warning: warndate = split_quoted_string(warning) warndate = wc.http.date.parse_http_date(warndate) else: warndate = None except ValueError, OverflowError: return None return warncode, warnagent, warntext, warndate
def parse_http_warning (warning): """ Grammar for a warning: Warning = "Warning" ":" 1#warning-value warning-value = warn-code SP warn-agent SP warn-text [SP warn-date] warn-code = 3DIGIT warn-agent = ( host [ ":" port ] ) | pseudonym ; the name or pseudonym of the server adding ; the Warning header, for use in debugging warn-text = quoted-string warn-date = <"> HTTP-date <"> """ try: warncode, warning = warning.split(None, 1) warncode = int(warncode) warnagent, warning = warning.split(None, 1) warntext, warning = split_quoted_string(warning) if warning: warndate, warning = split_quoted_string(warning) warndate = wc.http.date.parse_http_date(warndate) else: warndate = None except ValueError, OverflowError: return None return warncode, warnagent, warntext, warndate
15,987
def cnormpath (path): """norm a path name to platform specific notation, but honoring the win_cross_compiling flag""" path = normpath(path) if win_cross_compiling: # replace slashes with backslashes path = path.replace("/", "\\") return path
def cnormpath (path): """norm a path name to platform specific notation, but honoring the win_compiling flag""" path = normpath(path) if win_cross_compiling: # replace slashes with backslashes path = path.replace("/", "\\") return path
15,988
def cnormpath (path): """norm a path name to platform specific notation, but honoring the win_cross_compiling flag""" path = normpath(path) if win_cross_compiling: # replace slashes with backslashes path = path.replace("/", "\\") return path
def cnormpath (path): """norm a path name to platform specific notation, but honoring the win_cross_compiling flag""" path = normpath(path) if win_compiling: # replace slashes with backslashes path = path.replace("/", "\\") return path
15,989
def run (self): super(MyInstall, self).run() # we have to write a configuration file because we need the # <install_data> directory (and other stuff like author, url, ...) data = [] for d in ['purelib', 'platlib', 'lib', 'headers', 'scripts', 'data']: attr = 'install_%s'%d if self.root: # cut off root path prefix cutoff = len(self.root) # don't strip the path separator if self.root.endswith(os.sep): cutoff -= 1 val = getattr(self, attr)[cutoff:] else: val = getattr(self, attr) if win_cross_compiling and d in win_path_scheme: # look for placeholders to replace oldpath, newpath = win_path_scheme[d] oldpath = "/%s" % oldpath if oldpath in val: val = val.replace(oldpath, newpath) if attr=="install_data": base = os.path.join(val, 'share', 'webcleaner') data.append('config_dir = %r' % \ cnormpath(os.path.join(base, 'config'))) data.append('template_dir = %r' % \ cnormpath(os.path.join(base, 'templates'))) val = cnormpath(val) data.append("%s = %r" % (attr, val)) self.distribution.create_conf_file(data, directory=self.install_lib)
def run (self): super(MyInstall, self).run() # we have to write a configuration file because we need the # <install_data> directory (and other stuff like author, url, ...) data = [] for d in ['purelib', 'platlib', 'lib', 'headers', 'scripts', 'data']: attr = 'install_%s'%d if self.root: # cut off root path prefix cutoff = len(self.root) # don't strip the path separator if self.root.endswith(os.sep): cutoff -= 1 val = getattr(self, attr)[cutoff:] else: val = getattr(self, attr) if win_compiling and d in win_path_scheme: # look for placeholders to replace oldpath, newpath = win_path_scheme[d] oldpath = "/%s" % oldpath if oldpath in val: val = val.replace(oldpath, newpath) if attr=="install_data": base = os.path.join(val, 'share', 'webcleaner') data.append('config_dir = %r' % \ cnormpath(os.path.join(base, 'config'))) data.append('template_dir = %r' % \ cnormpath(os.path.join(base, 'templates'))) val = cnormpath(val) data.append("%s = %r" % (attr, val)) self.distribution.create_conf_file(data, directory=self.install_lib)
15,990
def run (self): super(MyInstall, self).run() # we have to write a configuration file because we need the # <install_data> directory (and other stuff like author, url, ...) data = [] for d in ['purelib', 'platlib', 'lib', 'headers', 'scripts', 'data']: attr = 'install_%s'%d if self.root: # cut off root path prefix cutoff = len(self.root) # don't strip the path separator if self.root.endswith(os.sep): cutoff -= 1 val = getattr(self, attr)[cutoff:] else: val = getattr(self, attr) if win_cross_compiling and d in win_path_scheme: # look for placeholders to replace oldpath, newpath = win_path_scheme[d] oldpath = "/%s" % oldpath if oldpath in val: val = val.replace(oldpath, newpath) if attr=="install_data": base = os.path.join(val, 'share', 'webcleaner') data.append('config_dir = %r' % \ cnormpath(os.path.join(base, 'config'))) data.append('template_dir = %r' % \ cnormpath(os.path.join(base, 'templates'))) val = cnormpath(val) data.append("%s = %r" % (attr, val)) self.distribution.create_conf_file(data, directory=self.install_lib)
def run (self): super(MyInstall, self).run() # we have to write a configuration file because we need the # <install_data> directory (and other stuff like author, url, ...) data = [] for d in ['purelib', 'platlib', 'lib', 'headers', 'scripts', 'data']: attr = 'install_%s'%d if self.root: # cut off root path prefix cutoff = len(self.root) # don't strip the path separator if self.root.endswith(os.sep): cutoff -= 1 val = getattr(self, attr)[cutoff:] else: val = getattr(self, attr) if win_cross_compiling and d in win_path_scheme: # look for placeholders to replace oldpath, newpath = win_path_scheme[d] oldpath = "%s%s" % (os.sep, oldpath) if oldpath in val: val = val.replace(oldpath, newpath) if attr=="install_data": base = os.path.join(val, 'share', 'webcleaner') data.append('config_dir = %r' % \ cnormpath(os.path.join(base, 'config'))) data.append('template_dir = %r' % \ cnormpath(os.path.join(base, 'templates'))) val = cnormpath(val) data.append("%s = %r" % (attr, val)) self.distribution.create_conf_file(data, directory=self.install_lib)
15,991
def run (self): if (sys.platform != "win32" and not win_cross_compiling and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform")
def run (self): if (sys.platform != "win32" and not win_compiling and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform")
15,992
def get_exe_bytes (self): if win_cross_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
def get_exe_bytes (self): if win_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
15,993
def get_exe_bytes (self): if win_cross_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
def get_exe_bytes (self): if win_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
15,994
def get_exe_bytes (self): if win_cross_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
def get_exe_bytes (self): if win_cross_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
15,995
def get_exe_bytes (self): if win_cross_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
def get_exe_bytes (self): if win_cross_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
15,996
def get_exe_bytes (self): if win_cross_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
def get_exe_bytes (self): if win_cross_compiling: # wininst.exe is in the same directory as bdist_wininst # XXX for python2.4, use wininst-X.Y.exe directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst.exe") return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes()
15,997
def text_status (): data = { 'uptime': format_seconds(time.time() - config['starttime']), 'valid': config['requests']['valid'], 'error': config['requests']['error'], 'blocked': config['requests']['blocked'], } s = STATUS_TEMPLATE % data s += '\n '.join(asyncore.socket_map.values()) s += ']\n\ndnscache: %s'%dns_lookups.dnscache return s
def text_status (): data = { 'uptime': format_seconds(time.time() - config['starttime']), 'valid': config['requests']['valid'], 'error': config['requests']['error'], 'blocked': config['requests']['blocked'], } s = STATUS_TEMPLATE % data s += '\n '.join(map(str, asyncore.socket_map.values())) s += ']\n\ndnscache: %s'%dns_lookups.dnscache return s
15,998
def _debugbuf (self): """print debugging information about data buffer status""" self._debug("self.outbuf %r", self.outbuf.getvalue()) self._debug("self.tagbuf %r", self.tagbuf) self._debug("self.waitbuf %r", self.waitbuf) self._debug("self.inbuf %r", self.inbuf.getvalue())
def _debugbuf (self): """print debugging information about data buffer status""" self._debug("self.outbuf %r", self.outbuf.getvalue()) self._debug("self.tagbuf %r", self.tagbuf) self._debug("self.waitbuf %r", self.waitbuf) self._debug("self.inbuf %r", self.inbuf.getvalue())
15,999