rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
del self.buffer[-1] if not (self.buffer and self.buffer[-1][0]==STARTTAG and \ self.buffer[-1][1]=='script'): | if not (self.buffer[-2][0]==STARTTAG and \ self.buffer[-2][1]=='script'): | 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.buff... |
del self.buffer[-1] | 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.buff... | |
script = script[4:].strip() | i = script.index('\n') if i==-1: script = script[4:] else: script = script[(i+1):] if script.endswith("-->"): script = script[:-3] | 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.buff... |
self.jsScript(script, 0.0) | 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.buff... |
data = "%s%s%s" % (self.waitbuf.getvalue(), self.inbuf.getvalue(), data) | data = "%s%s" % (self.waitbuf.getvalue(), self.inbuf.getvalue(), ) | 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) |
debug(NIGHTMARE, "Filter: matched rule %s on tag %s" % (`rule.title`, `tag`)) | debug(NIGHTMARE, "HtmlFilter: 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 _buf2data([item], self.waitbuf) rulelist = [] filtered = 0 # look for filter rules which ... |
debug(NIGHTMARE, "Filter: put on buffer") | debug(NIGHTMARE, "HtmlFilter: 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 _buf2data([item], self.waitbuf) rulelist = [] filtered = 0 # look for filter rules which ... |
if not self.rulestack and \ (not self.javascript or tag!='script'): | if not self.rulestack and not self.javascript: | 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 ... |
filtered = 1 | filtered = "True" | 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. |
self.buf.append((ENDTAG, tag)) | 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. |
self.jsScriptSrc(url, lang) self.buf.append((STARTTAG, tag, attrs)) | return 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('... |
val = "^%s$" % val | val = "^(%s)$" % val | 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)) |
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.str... | 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.assertEqual... | 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.... |
self.assertEquals(linkcheck.strformat.unquote("'a\""), "a") self.assertEquals(linkcheck.strformat.unquote("\"a'"), "a") | self.assertEquals(wc.strformat.unquote("'a\""), "a") self.assertEquals(wc.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.... |
self.assertEquals(linkcheck.strformat.wrap(s, -1), s) self.assertEquals(linkcheck.strformat.wrap(s, 0), s) | self.assertEquals(wc.strformat.wrap(s, -1), s) self.assertEquals(wc.strformat.wrap(s, 0), s) | 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... |
self.assertEquals(linkcheck.strformat.wrap(s2, 2), s) | self.assertEquals(wc.strformat.wrap(s2, 2), s) | 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... |
self.assertEquals(linkcheck.strformat.wrap(s, 5), s2) | self.assertEquals(wc.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... |
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") | self.assertEquals(wc.strformat.remove_markup("<a>"), "") self.assertEquals(wc.strformat.remove_markup("<>"), "") self.assertEquals(wc.strformat.remove_markup("<<>"), "") self.assertEquals(wc.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") |
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.ass... | self.assertRaises(ValueError, wc.strformat.strsize, -1) self.assertEquals(wc.strformat.strsize(0), "0 Bytes") self.assertEquals(wc.strformat.strsize(1), "1 Byte") self.assertEquals(wc.strformat.strsize(2), "2 Bytes") self.assertEquals(wc.strformat.strsize(1023), "1023 Bytes") self.assertEquals(wc.strformat.strsize(1024... | 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(lin... |
raise RatingParseError(i18n._(",alformed rating line %r")%line) | raise RatingParseError(i18n._("malformed rating line %r")%line) | 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) cate... |
self._debug(ALWAYS, "self.inbuf", `self.inbuf.getvalue()`) | 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.g... | |
self.handleError() | self.handleError(record) | 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() |
categories[cat][type] = gzip.GzipFile(fname, 'wb') | categories[cat][ftype] = 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, fty... |
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) |
"charset": ConfigCharset, "title_en": xmlify("%s %s" % (ftype.capitalize(), cat)), "title_de": xmlify("%s %s" % (transtypes[ftype]['de'].capitalize(), | "charset": wc.ConfigCharset, "title_en": wc.XmlUtils.xmlquote("%s %s" % (ftype.capitalize(), cat)), "title_de": wc.XmlUtils.xmlquote("%s %s" % (transtypes[ftype]['de'].capitalize(), | 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_en": xmlify("Automatically generated on %s" % date), "desc_de": xmlify("Automatisch generiert am %s" % date), | "desc_en": wc.XmlUtils.xmlquote("Automatically generated on %s" % date), "desc_de": wc.XmlUtils.xmlquote("Automatisch generiert am %s" % date), | 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)... |
d['path'] = xmlify(expr) | d['path'] = wc.XmlUtils.xmlquote(expr) | 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. |
f = TarFile.gzopen(source) | f = tarfile.TarFile.gzopen(source) | 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... |
webbrowser.open(config_url) | webbrowser.open(url) | 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) |
scripts = ['webcleaner', 'webcleaner-certificates'] | 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) | |
scripts.append('webcleaner-service') | 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) | |
scripts = scripts, | scripts = ['webcleaner', 'webcleaner-certificates'], | 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 filter (self, data, url): | def filter (self, data, url, rules): encoding = "UTF8" self.parser.encoding = encoding data = data.encode(encoding) self.rules = rules | 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 |
self.valid = True self.stack = [] | 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 | |
self.outbuf = StringIO() | self.reset() | 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 |
tag = wc.filter.HtmlTags.check_spelling(tag, self.url) | tag = wc.filter.html.check_spelling(tag, self.url) | 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 = attr... |
if err in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK): | if err in (errno.EINPROGRESS, errno.EWOULDBLOCK): | 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, e... |
See also http://cr.yp.to/docs/connect.html | See also http://cr.yp.to/docs/connect.html and connect(2) manpage. | 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, '... |
elif err in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK): | elif err in (errno.EINPROGRESS, errno.EWOULDBLOCK): | 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, '... |
return self.enclosed_ro.match(data) | return self.enclosed_ro.search(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, ... |
data += "0000000000%d\r\n" % len(body) | data += "0000000000%s\r\n" % hex(self.body_length)[2:] | 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... |
wc.proxy.make_timer(1, reload_config) | global pending_reload if not pending_reload: pending_reload = True wc.proxy.make_timer(1, reload_config) | def sighup_reload_config (signum, frame): """store timer for reloading configuration data""" wc.proxy.make_timer(1, reload_config) |
p.debug(1) | 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 = ... | |
version = "0.51", | version = "0.52", | 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) |
('share/webcleaner/config/blacklists/audio-video', ['config/blacklists/audio-video/urls.gz', 'config/blacklists/audio-video/domains.gz']), ('share/webcleaner/config/blacklists/drugs', ['config/blacklists/drugs/urls.gz', 'config/blacklists/drugs/domains.gz']), ('share/webcleaner/config/blacklists/gambling', ['config/bla... | 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) | |
['config/blacklists/violence/urls.gz', 'config/blacklists/violence/domains.gz']), ('share/webcleaner/config/blacklists/warez', ['config/blacklists/warez/urls.gz', 'config/blacklists/warez/domains.gz']), | ['config/blacklists/violence/domains.gz']), | 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) |
i = src.find('.') | i = src.rfind('.') | 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'): # p... |
if not scanner.infected and data: | buf = attrs['virus_buf'] if data: | 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 "" |
if not scanner.infected: return data for msg in scanner.infected: warn(FILTER, "Found virus %r in %r", msg, attrs['url']) | buf.write(data) | 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 "" |
if not scanner.infected and data: | buf = attrs['virus_buf'] if data: | 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(FIL... |
d['scanner'] = ClamdScanner() | d['scanner'] = ClamdScanner(get_clamav_conf()) d['virus_buf'] = StringIO() | 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 __init__ (self): """initialize clamd daemon process connection""" | def __init__ (self, clamav_conf): """initialize clamd daemon process sockets""" | 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) |
self.sock, host = clamav_conf.new_connection() self.wsock = clamav_conf.new_scansock(self.sock, host) | self.clamav_conf = clamav_conf self.sock, host = self.clamav_conf.new_connection() self.wsock = self.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) |
def close (self): """close clamd daemon connection""" | 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) | |
clamav_conf = None | _clamav_conf = None | def close (self): """close clamd daemon connection""" self.sock.close() |
global clamav_conf | global _clamav_conf | def init_clamav_conf (): global clamav_conf from wc import config clamav_conf = ClamavConfig(config['clamavconf']) |
clamav_conf = ClamavConfig(config['clamavconf']) | _clamav_conf = ClamavConfig(config['clamavconf']) def get_clamav_conf (): return _clamav_conf | def init_clamav_conf (): global clamav_conf from wc import config clamav_conf = ClamavConfig(config['clamavconf']) |
warndate = split_quoted_string(warning) | warndate, warning = split_quoted_string(warning) | 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 deb... |
the win_cross_compiling flag""" | the win_compiling flag""" | 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 |
if win_cross_compiling: | if win_compiling: | 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 |
if win_cross_compiling and d in win_path_scheme: | if win_compiling and d in win_path_scheme: | 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 cutof... |
oldpath = "/%s" % oldpath | oldpath = "%s%s" % (os.sep, oldpath) | 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 cutof... |
if (sys.platform != "win32" and not win_cross_compiling and | if (sys.platform != "win32" and not win_compiling and | 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") |
if win_cross_compiling: | if win_compiling: | 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, sel... |
if os.name=='nt': extensions.append(Extension('wc.js.jslib', sources=['wc/js/jslib.c'], define_macros = [('WIN32', None), ('XP_WIN', None), ('EXPORT_JS_API', None)], include_dirs = include_dirs + ['libjs'], extra_compile_args = extra_compile_args, extra_objects = ['libjs/.libs/libjs.a'], library_dirs = library_dirs, ... | if win_compiling: define_macros = [('WIN32', None), ('XP_WIN', None), ('EXPORT_JS_API', None), ] | 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, sel... |
if win_cross_compiling: define_macros = [('WIN32', None), ('XP_WIN', None), ('EXPORT_JS_API', None), ] else: define_macros = [] extensions.append(Extension('wc.js.jslib', sources=['wc/js/jslib.c'], include_dirs = include_dirs + ['libjs'], define_macros = define_macros, extra_compile_args = extra_compile_args, extra_obj... | define_macros = [] extensions.append(Extension('wc.js.jslib', sources=['wc/js/jslib.c'], include_dirs = include_dirs + ['libjs'], define_macros = define_macros, extra_compile_args = extra_compile_args, extra_objects = ['libjs/.libs/libjs.a'], library_dirs = library_dirs, libraries = libraries, )) | 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, sel... |
if os.name=='nt' or win_cross_compiling: | if win_compiling: | 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, sel... |
s += '\n '.join(asyncore.socket_map.values()) | s += '\n '.join(map(str, asyncore.socket_map.values())) | 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... |
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()) | debug(FILTER, "self.outbuf %r", self.outbuf.getvalue()) debug(FILTER, "self.tagbuf %r", self.tagbuf) debug(FILTER, "self.waitbuf %r", self.waitbuf) debug(FILTER, "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()) |
rules = filter(lambda r, u=url: r.appliesTo(u), self.rules) | def getAttrs (self, headers, url): """We need a separate filter instance for stateful filtering""" # first: weed out the rules that dont apply to this url rules = filter(lambda r, u=url: r.appliesTo(u), self.rules) rewrites = [] opts = {'comments': 1, 'javascript': 0} for rule in self.rules: if not rule.appliesTo(url):... | |
val = attrs[name] | val = resolve_html_entities(attrs[name]) | def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" val = attrs[name] if not val: return self.jsEnv.attachListener(self) self.jsEnv.executeScriptAsFunction(val, 0.0) self.jsEnv.detachListener(self) res = self.popup_counter self.popup_counter = 0 return res |
self.jsEnv.executeScriptAsFunction(val, 0.0) | try: self.jsEnv.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass | def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" val = attrs[name] if not val: return self.jsEnv.attachListener(self) self.jsEnv.executeScriptAsFunction(val, 0.0) self.jsEnv.detachListener(self) res = self.popup_counter self.popup_counter = 0 return res |
return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \ | return "%s, %02d %s %04d %02d:%02d:%02d GMT" % \ | def get_date_rfc1123 (timesecs): """ RFC 822, updated by RFC 1123 Grammar: rfc1123-date = wkday "," SP date1 SP time SP "GMT" date1 = 2DIGIT SP month SP 4DIGIT ; day month year (e.g., 02 Jun 1982) time = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00 - 23:59:59 wkday = "Mon" | "Tue" | "Wed" | "Thu" | "Fr... |
return "%s, %02d-%3s-%2d %02d:%02d:%02d GMT" % \ | return "%s, %02d-%s-%02d %02d:%02d:%02d GMT" % \ | def get_date_rfc850 (timesecs): """ RFC 850, obsoleted by RFC 1036 Grammar: rfc850-date = weekday "," SP date2 SP time SP "GMT" date2 = 2DIGIT "-" month "-" 2DIGIT ; day-month-year (e.g., 02-Jun-82) time = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00 - 23:59:59 weekday = "Monday" | "Tuesday" | "Wednesda... |
import wc.filter.rating wc.filter.rating.rating_cache_load() | def init (confdir=wc.ConfigDir): global config config = Configuration(confdir) import wc.filter.rating wc.filter.rating.rating_cache_load() return config | |
raise ParseException, _("unknown tag name %r") % name | wc.log.warn(wc.LOG_PROXY, _("unknown tag name %r"), name) self.error = name self.cmode = None | def start_element (self, name, attrs): """handle start tag of folder, rule or nested element""" super(ZapperParser, self).start_element(name, attrs) self.cmode = name if name in rulenames: self.rule = wc.filter.GetRuleFromName(name) self.rule.fill_attrs(attrs, name) self.folder.append_rule(self.rule) # tag has characte... |
self.cmode = None if self.rule is None: self.folder.end_data(name) | if self.error: if name == self.error: self.error = None | def end_element (self, name): """handle end tag of folder, rule or nested element""" self.cmode = None if self.rule is None: self.folder.end_data(name) else: self.rule.end_data(name) if name in rulenames: if self.compile_data: self.rule.compile_data() elif name == 'folder': if self.compile_data: self.folder.compile_dat... |
self.rule.end_data(name) if name in rulenames: if self.compile_data: self.rule.compile_data() elif name == 'folder': if self.compile_data: self.folder.compile_data() | self.cmode = None if self.rule is None: self.folder.end_data(name) else: self.rule.end_data(name) if name in rulenames: if self.compile_data: self.rule.compile_data() elif name == 'folder': if self.compile_data: self.folder.compile_data() | def end_element (self, name): """handle end tag of folder, rule or nested element""" self.cmode = None if self.rule is None: self.folder.end_data(name) else: self.rule.end_data(name) if name in rulenames: if self.compile_data: self.rule.compile_data() elif name == 'folder': if self.compile_data: self.folder.compile_dat... |
if self.cmode: | if self.error: pass elif self.cmode: | def character_data (self, data): """handle rule of folder character data""" if self.cmode: if self.rule is None: self.folder.fill_data(data, self.cmode) else: self.rule.fill_data(data, self.cmode) |
debug(FILTER, "rule %s filter_tag", self.title) debug(FILTER, "original tag %s attrs %s", `tag`, attrs) debug(FILTER, "replace %s with %s", num_part(self.part), `self.replacement`) | def filter_tag (self, tag, attrs): debug(FILTER, "rule %s filter_tag", self.title) debug(FILTER, "original tag %s attrs %s", `tag`, attrs) debug(FILTER, "replace %s with %s", num_part(self.part), `self.replacement`) if self.part==COMPLETE: return [DATA, ""] if self.part==TAGNAME: return [STARTTAG, self.replacement, att... | |
debug(FILTER, "ro=%s", ro.pattern) | def filter_tag (self, tag, attrs): debug(FILTER, "rule %s filter_tag", self.title) debug(FILTER, "original tag %s attrs %s", `tag`, attrs) debug(FILTER, "replace %s with %s", num_part(self.part), `self.replacement`) if self.part==COMPLETE: return [DATA, ""] if self.part==TAGNAME: return [STARTTAG, self.replacement, att... | |
debug(FILTER, "mo=%s", str(mo.groups())) | def filter_tag (self, tag, attrs): debug(FILTER, "rule %s filter_tag", self.title) debug(FILTER, "original tag %s attrs %s", `tag`, attrs) debug(FILTER, "replace %s with %s", num_part(self.part), `self.replacement`) if self.part==COMPLETE: return [DATA, ""] if self.part==TAGNAME: return [STARTTAG, self.replacement, att... | |
debug(FILTER, "filtered tag %s attrs %s", tag, newattrs) | def filter_tag (self, tag, attrs): debug(FILTER, "rule %s filter_tag", self.title) debug(FILTER, "original tag %s attrs %s", `tag`, attrs) debug(FILTER, "replace %s with %s", num_part(self.part), `self.replacement`) if self.part==COMPLETE: return [DATA, ""] if self.part==TAGNAME: return [STARTTAG, self.replacement, att... | |
self.jsForm(name, attrs.get('action'), attrs.get('target')) | self.jsForm(name, attrs.get('action', ''), attrs.get('target', '')) | 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('... |
self.buffer.append([DATA, self.jsfilter.flushbuf()]) | self.data.append(self.jsfilter.flushbuf()) | def jsScriptSrc (self, url, language): if not url: return #debug(HURT_ME_PLENTY, "jsScriptSrc", url, language) try: script = urlutils.open_url(url) 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)', lang... |
if not script: return | 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.buff... | |
self.jsEnv.attachListener(self) self.jsfilter = HtmlFilter(self.rules, self.document, comments=self.comments, javascript=self.javascript) self.jsEnv.executeScript(script, 0.0) self.jsEnv.detachListener(self) self.jsfilter.flush() self.buffer.append([DATA, self.jsfilter.flushbuf()]) self.buffer += self.jsfilter.buffer s... | 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.buff... |
self.socket.settimeout(wc.config['timeout']) | self.socket.settimeout(wc.configuration.config['timeout']) | def __init__ (self, ipaddr, port, client): """initialize connection object and connect to remove server""" super(wc.proxy.HttpServer.HttpServer, self).__init__(client, 'connect') # default values self.addr = (ipaddr, port) self.reset() # attempt connect self.create_socket(socket.AF_INET, socket.SOCK_STREAM, sslctx=wc.p... |
if self.addr[1] != 80: | extra = "" if hasattr(self, "persistent") and self.persistent: extra += "persistent " if hasattr(self, "addr") and self.addr and self.addr[1] != 80: | def __repr__ (self): """object description""" if self.addr[1] != 80: portstr = ':%d' % self.addr[1] else: portstr = '' extra = '%s%s' % (self.addr[0], portstr) if self.socket: extra += " (%s)" % self.socket.state_string() if not self.connected: extra += " (unconnected)" #if len(extra) > 46: extra = extra[:43] + '...' r... |
else: portstr = '' extra = '%s%s' % (self.addr[0], portstr) | extra += '%s%s' % (self.addr[0], portstr) | def __repr__ (self): """object description""" if self.addr[1] != 80: portstr = ':%d' % self.addr[1] else: portstr = '' extra = '%s%s' % (self.addr[0], portstr) if self.socket: extra += " (%s)" % self.socket.state_string() if not self.connected: extra += " (unconnected)" #if len(extra) > 46: extra = extra[:43] + '...' r... |
if log.isEnabledFor(logging.EXCEPTION): | if log.isEnabledFor(logging.ERROR): | def exception (logname, msg, *args, **kwargs): """ Log an exception. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.EXCEPTION): _log(log.exception, msg, args, tb=kwargs.get("tb")) |
self.basedir = os.path.join(os.getcwd(), "wc", "magic", "tests", "data") | self.basedir = os.path.join(os.getcwd(), "wc", "magic", "tests") | def setUp (self): self.basedir = os.path.join(os.getcwd(), "wc", "magic", "tests", "data") |
replace = _getval(form, 'rule_replace') if replace!=currule.replace: currule.replace = replace | replacement = _getval(form, 'rule_replace') if replacement!=currule.replacement: currule.replacement = replacement | def _form_apply_replace (form): # note: do not strip() the search and replace form values search = _getval(form, 'rule_search') if not search: error['rulesearch'] = True return if search!=currule.search: currule.search = search _compileRegex(currule, "search") info['rulesearch'] = True replace = _getval(form, 'rule_rep... |
new_url = self.scheme+"://"+answer.data | new_url = client.scheme+"://"+answer.data | def handle_dns (self, hostname, answer): assert self.state == 'dns' debug(PROXY, "%s handle dns", self) if not self.client.connected: warn(PROXY, "%s client closed after DNS", self) # The browser has already closed this connection, so abort return if answer.isFound(): self.ipaddr = answer.data[0] self.state = 'server' ... |
from bk.HtmlParser.htmllib import HtmlPrinter from bk.HtmlParser import htmlsax | from wc.HtmlParser.htmllib import HtmlPrinter from wc.HtmlParser import htmlsax | def _main (): """USAGE: test/run.sh test/parsefile.py test.html""" import sys if len(sys.argv)!=2: print _main.__doc__ sys.exit(1) if sys.argv[1]=='-': f = sys.stdin else: f = file(sys.argv[1]) from bk.HtmlParser.htmllib import HtmlPrinter from bk.HtmlParser import htmlsax p = htmlsax.parser(HtmlPrinter()) #p.debug(1) ... |
debug(ALWAYS, "Proxy:", `self.request`) | debug(BRING_IT_ON, "Proxy:", `self.request`) | def __init__ (self, client, request, headers, content, nofilter,compress): self.client = client self.request = request self.headers = headers self.compress = compress self.content = content self.nofilter = nofilter debug(ALWAYS, "Proxy:", `self.request`) self.method, self.url, protocol = self.request.split() scheme, ho... |
("a;", ("a", ";")), ("a/b;c/d;e", ("a/b;c/d", ";e")), | ("a;", ("a", "")), ("a/b;c/d;e", ("a/b;c/d", "e")), | def test_splitparam (self): """path parameter split test""" p = [ ("", ("", "")), ("/", ("/", "")), ("a", ("a", "")), ("a;", ("a", ";")), ("a/b;c/d;e", ("a/b;c/d", ";e")), ] for x in p: self._splitparam (self, x) |
self._splitparam (self, x) | self._splitparam(x) | def test_splitparam (self): """path parameter split test""" p = [ ("", ("", "")), ("/", ("/", "")), ("a", ("a", "")), ("a;", ("a", ";")), ("a/b;c/d;e", ("a/b;c/d", ";e")), ] for x in p: self._splitparam (self, x) |
print >>log, "error fetching %s:"%url, msg | print >>log, wc.i18n._("error fetching %s")%url, msg print >>log, "...", wc.i18n._("done") | def update_filter (wconfig, dryrun=False, log=None): """Update the given configuration object with .zap files found at baseurl. If dryrun is True, only print out the changes but do nothing throws IOError on error """ chg = False baseurl = wconfig['baseurl']+"filter/" url = baseurl+"filter-md5sums.txt" try: page = open_... |
print >>log, "error fetching", url | print >>log, wc.i18n._("error fetching %s")%url print >>log, "...", wc.i18n._("done") | def update_filter (wconfig, dryrun=False, log=None): """Update the given configuration object with .zap files found at baseurl. If dryrun is True, only print out the changes but do nothing throws IOError on error """ chg = False baseurl = wconfig['baseurl']+"filter/" url = baseurl+"filter-md5sums.txt" try: page = open_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.