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.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)
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.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)
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.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)
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.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)
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 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()
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 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()
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 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()
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('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))
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.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')
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')
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")
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.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")
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.assertEquals(linkcheck.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
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.assertEquals(linkcheck.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
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.assertEquals(linkcheck.strformat.wrap(s2, 2), s) # combining lines self.assertEquals(linkcheck.strformat.wrap(s, 5), s2)
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.assertEquals(linkcheck.strformat.strsize(1024), "1.00 kB")
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), "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")
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) categories[category] = value return categories
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.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)
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, ftype) if os.path.exists(fname): os.remove(fname) print "opening", fname categories[cat][type] = gzip.GzipFile(fname, 'wb')
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_de": xmlify("Automatisch generiert am %s" % date), } f.write("""<?xml version="1.0" encoding="%(charset)s"?>
"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), "desc_de": xmlify("Automatisch generiert am %s" % date), } f.write("""<?xml version="1.0" encoding="%(charset)s"?>
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.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)
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 = 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]
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, 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
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, '%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()
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, '%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()
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, StringIO()).getvalue() return self.enclosed_ro.match(data)
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\n\r\n" self.server.log.write("server will send %d bytes\n" % len(data)) self.print_lines(data) self.wfile.write(data)
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 = 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()
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/blacklists/gambling/urls.gz', 'config/blacklists/gambling/domains.gz']), ('share/webcleaner/config/blacklists/hacking', ['config/blacklists/hacking/urls.gz', 'config/blacklists/hacking/domains.gz']), ('share/webcleaner/config/blacklists/mail', ['config/blacklists/mail/domains.gz']), ('share/webcleaner/config/blacklists/porn', ['config/blacklists/porn/urls.gz', 'config/blacklists/porn/domains.gz']), ('share/webcleaner/config/blacklists/proxy', ['config/blacklists/proxy/urls.gz', 'config/blacklists/proxy/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)
['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'): # 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']
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(FILTER, "Found virus %r in %r", msg, attrs['url']) return ""
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 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
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 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)
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 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)
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, self).get_exe_bytes()
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, libraries = libraries, ))
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, self).get_exe_bytes()
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_objects = ['libjs/.libs/libjs.a'], library_dirs = library_dirs, libraries = libraries, ))
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, self).get_exe_bytes()
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, self).get_exe_bytes()
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'%dns_lookups.dnscache return 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): continue if rule.get_name()=='rewrite': rewrites.append(rule) elif rule.get_name()=='nocomments': opts['comments'] = 0 elif rule.get_name()=='javascript': opts['javascript'] = 1 # generate the HTML filter return {'filter': HtmlFilter(rewrites, url, **opts)}
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" | "Fri" | "Sat" | "Sun" month = "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec" Example: Sun, 06 Nov 1994 08:49:37 GMT """ year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timesecs) return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \ (wkdayname[wd], day, monthname[month], year, hh, mm, ss)
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" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday" month = "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec" Example: Sunday, 06-Nov-94 08:49:37 GMT """ year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timesecs) return "%s, %02d-%3s-%2d %02d:%02d:%02d GMT" % \ (weekdayname[wd], day, monthname[month], year % 100, hh, mm, ss)
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 character data elif name in _nestedtags: if self.rule is None: self.folder.fill_attrs(attrs, name) else: self.rule.fill_attrs(attrs, name) elif name == 'folder': self.folder.fill_attrs(attrs, name) else: raise ParseException, _("unknown tag name %r") % name
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_data()
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_data()
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, attrs] if self.part==TAG: return [DATA, self.replacement] if self.part==ENCLOSED: return [STARTTAG, tag, attrs] newattrs = {} # look for matching tag attributes for attr,val in attrs.items(): ro = self.attrs.get(attr) if ro: debug(FILTER, "ro=%s", ro.pattern) mo = ro.search(val) if mo: if self.part==ATTR: # replace complete attr, and make it possible # for replacement to generate multiple attributes, # eg "a=b c=d" # XXX split does not honor quotes for f in self.replacement.split(): if '=' in self.replacement: k,v = f.split('=') newattrs[k] = v else: newattrs[self.replacement] = None elif self.part==ATTRVAL: # backreferences are replaced debug(FILTER, "mo=%s", str(mo.groups())) newattrs[attr] = mo.expand(self.replacement) else: error(FILTER, "Invalid part value %s" % str(self.part)) continue # nothing matched, just append the attribute as is newattrs[attr] = val debug(FILTER, "filtered tag %s attrs %s", tag, newattrs) return [STARTTAG, tag, newattrs]
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, attrs] if self.part==TAG: return [DATA, self.replacement] if self.part==ENCLOSED: return [STARTTAG, tag, attrs] newattrs = {} # look for matching tag attributes for attr,val in attrs.items(): ro = self.attrs.get(attr) if ro: debug(FILTER, "ro=%s", ro.pattern) mo = ro.search(val) if mo: if self.part==ATTR: # replace complete attr, and make it possible # for replacement to generate multiple attributes, # eg "a=b c=d" # XXX split does not honor quotes for f in self.replacement.split(): if '=' in self.replacement: k,v = f.split('=') newattrs[k] = v else: newattrs[self.replacement] = None elif self.part==ATTRVAL: # backreferences are replaced debug(FILTER, "mo=%s", str(mo.groups())) newattrs[attr] = mo.expand(self.replacement) else: error(FILTER, "Invalid part value %s" % str(self.part)) continue # nothing matched, just append the attribute as is newattrs[attr] = val debug(FILTER, "filtered tag %s attrs %s", tag, newattrs) return [STARTTAG, tag, newattrs]
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, attrs] if self.part==TAG: return [DATA, self.replacement] if self.part==ENCLOSED: return [STARTTAG, tag, attrs] newattrs = {} # look for matching tag attributes for attr,val in attrs.items(): ro = self.attrs.get(attr) if ro: debug(FILTER, "ro=%s", ro.pattern) mo = ro.search(val) if mo: if self.part==ATTR: # replace complete attr, and make it possible # for replacement to generate multiple attributes, # eg "a=b c=d" # XXX split does not honor quotes for f in self.replacement.split(): if '=' in self.replacement: k,v = f.split('=') newattrs[k] = v else: newattrs[self.replacement] = None elif self.part==ATTRVAL: # backreferences are replaced debug(FILTER, "mo=%s", str(mo.groups())) newattrs[attr] = mo.expand(self.replacement) else: error(FILTER, "Invalid part value %s" % str(self.part)) continue # nothing matched, just append the attribute as is newattrs[attr] = val debug(FILTER, "filtered tag %s attrs %s", tag, newattrs) return [STARTTAG, tag, newattrs]
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, attrs] if self.part==TAG: return [DATA, self.replacement] if self.part==ENCLOSED: return [STARTTAG, tag, attrs] newattrs = {} # look for matching tag attributes for attr,val in attrs.items(): ro = self.attrs.get(attr) if ro: debug(FILTER, "ro=%s", ro.pattern) mo = ro.search(val) if mo: if self.part==ATTR: # replace complete attr, and make it possible # for replacement to generate multiple attributes, # eg "a=b c=d" # XXX split does not honor quotes for f in self.replacement.split(): if '=' in self.replacement: k,v = f.split('=') newattrs[k] = v else: newattrs[self.replacement] = None elif self.part==ATTRVAL: # backreferences are replaced debug(FILTER, "mo=%s", str(mo.groups())) newattrs[attr] = mo.expand(self.replacement) else: error(FILTER, "Invalid part value %s" % str(self.part)) continue # nothing matched, just append the attribute as is newattrs[attr] = val debug(FILTER, "filtered tag %s attrs %s", tag, newattrs) return [STARTTAG, tag, newattrs]
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('name', attrs.get('id')) self.jsForm(name, attrs.get('action'), attrs.get('target')) elif tag=='script': lang = attrs.get('language', '').lower() scrtype = attrs.get('type', '').lower() if scrtype=='text/javascript' or \ lang.startswith('javascript') or \ not (lang or scrtype): self.jsScriptSrc(attrs.get('src'), lang) return self.buffer.append((STARTTAG, tag, attrs))
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)', language) if mo: ver = float(mo.group('num')) self.jsEnv.attachListener(self) self.jsfilter = HtmlFilter(self.rules, self.document, comments=self.comments, javascript=self.javascript) self.jsEnv.executeScript(script, ver) self.jsEnv.detachListener(self) self.jsfilter.flush() self.buffer.append([DATA, self.jsfilter.flushbuf()]) self.buffer += self.jsfilter.buffer self.jsfilter = None
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.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 not script: return if script.startswith("<!--"): script = script[4:].strip() 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 self.jsfilter = None
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 self.jsfilter = None
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 not script: return if script.startswith("<!--"): script = script[4:].strip() 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 self.jsfilter = None
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.proxy.ssl.get_clientctx(wc.configuration.config.configdir)) self.socket.settimeout(wc.config['timeout']) self.try_connect() self.socket.set_connect_state()
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] + '...' return '<%s:%-8s %s>' % ('sslserver', self.state, extra)
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] + '...' return '<%s:%-8s %s>' % ('sslserver', self.state, extra)
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_replace') if replace!=currule.replace: currule.replace = replace info['rulereplace'] = True
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' self.find_server() elif answer.isRedirect(): # Let's use a different hostname new_url = self.scheme+"://"+answer.data if self.port != 80: new_url += ':%d' % self.port new_url += self.document info(PROXY, "%s redirecting %r", self, new_url) self.state = 'done' # XXX find http version! ServerHandleDirectly( self.client, '%s 301 Moved Permanently' % self.protocol, 301, WcMessage(StringIO('Content-type: text/plain\r\n' 'Location: %s\r\n\r\n' % new_url)), i18n._('Host %s is an abbreviation for %s')%(hostname, answer.data)) else: # Couldn't look up the host, # close this connection self.state = 'done' self.client.error(504, i18n._("Host not found"), i18n._('Host %s not found .. %s')%(hostname, answer.data))
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) size = 1024 #size = 1 data = f.read(size) while data: p.feed(data) data = f.read(size) p.flush()
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, hostname, port, document = spliturl(self.url) # fix missing trailing / if not document: document = '/' # fix missing host headers for HTTP/1.1 if protocol=='HTTP/1.1' and not self.headers.has_key('host'): self.headers['Host'] = hostname if port!=80: self.headers['Host'] += ":%d"%port debug(HURT_ME_PLENTY, "Proxy: splitted url", scheme, hostname, port, document) if scheme=='file': # a blocked url is a local file:// link # this means we should _not_ use this proxy for local # file links :) mtype = mimetypes.guess_type(self.url)[0] config['requests']['valid'] += 1 config['requests']['blocked'] += 1 ServerHandleDirectly(self.client, 'HTTP/1.0 200 OK\r\n', 'Content-Type: %s\r\n\r\n'%(mtype or 'application/octet-stream'), open(document, 'rb').read()) return
("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_url(url) except IOError, msg: print >>log, "error fetching %s:"%url, msg return chg # remember all local config files filemap = {} for filename in wc.filterconf_files(wconfig.filterdir): filemap[os.path.basename(filename)] = filename # read md5sums for line in page.read().splitlines(): if "<" in line: print >>log, "error fetching", url return chg if not line: continue md5sum, filename = line.split() assert filename.endswith('.zap') fullname = os.path.join(wc.ConfigDir, filename) # compare checksums if filemap.has_key(filename): f = file(fullname) data = f.read() digest = list(md5.new(data).digest()) f.close() digest = "".join([ "%0.2x"%ord(c) for c in digest ]) if digest==md5sum: print >>log, wc.i18n._("filter %s not changed, ignoring")%filename continue print >>log, wc.i18n._("updating filter %s")%filename else: print >>log, wc.i18n._("adding new filter %s")%filename # parse new filter url = baseurl+filename page = open_url(url) p = wc.ZapperParser(fullname, wconfig, compile_data=False) p.parse(fp=page) page.close() if wconfig.merge_folder(p.folder, dryrun=dryrun, log=log): chg = True url = baseurl+"extern-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, wc.i18n._("error fetching %s:")%url, msg return chg lines = page.read().splitlines() page.close() for line in lines: if "<" in line: print >>log, wc.i18n._("error fetching %s:")%url, wc.i18n._("invalid content") return chg if not line: continue md5sum, filename = line.split() # XXX UNIX-generated md5sum filenames with subdirs are not portable fullname = os.path.join(wc.ConfigDir, filename) # compare checksums if os.path.exists(fullname): f = file(fullname) data = f.read() digest = list(md5.new(data).digest()) f.close() digest = "".join([ "%0.2x"%ord(c) for c in digest ]) if digest==md5sum: print >>log, wc.i18n._("extern filter %s not changed, ignoring")%filename continue print >>log, wc.i18n._("updating extern filter %s")%filename else: print >>log, wc.i18n._("adding new extern filter %s")%filename chg = True if not dryrun: url = baseurl+filename try: page = open_url(url) except IOError, msg: print >>log, wc.i18n._("error fetching %s:")%url, msg continue data = page.read() if not data: print >>log, wc.i18n._("error fetching %s:")%url, \ wc.i18n._("got no data") continue f = file(fullname, 'wb') f.write(data) f.close() return chg
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_url(url) except IOError, msg: print >>log, "error fetching %s:"%url, msg return chg # remember all local config files filemap = {} for filename in wc.filterconf_files(wconfig.filterdir): filemap[os.path.basename(filename)] = filename # read md5sums for line in page.read().splitlines(): if "<" in line: print >>log, "error fetching", url return chg if not line: continue md5sum, filename = line.split() assert filename.endswith('.zap') fullname = os.path.join(wc.ConfigDir, filename) # compare checksums if filemap.has_key(filename): f = file(fullname) data = f.read() digest = list(md5.new(data).digest()) f.close() digest = "".join([ "%0.2x"%ord(c) for c in digest ]) if digest==md5sum: print >>log, wc.i18n._("filter %s not changed, ignoring")%filename continue print >>log, wc.i18n._("updating filter %s")%filename else: print >>log, wc.i18n._("adding new filter %s")%filename # parse new filter url = baseurl+filename page = open_url(url) p = wc.ZapperParser(fullname, wconfig, compile_data=False) p.parse(fp=page) page.close() if wconfig.merge_folder(p.folder, dryrun=dryrun, log=log): chg = True url = baseurl+"extern-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, wc.i18n._("error fetching %s:")%url, msg return chg lines = page.read().splitlines() page.close() for line in lines: if "<" in line: print >>log, wc.i18n._("error fetching %s:")%url, wc.i18n._("invalid content") return chg if not line: continue md5sum, filename = line.split() # XXX UNIX-generated md5sum filenames with subdirs are not portable fullname = os.path.join(wc.ConfigDir, filename) # compare checksums if os.path.exists(fullname): f = file(fullname) data = f.read() digest = list(md5.new(data).digest()) f.close() digest = "".join([ "%0.2x"%ord(c) for c in digest ]) if digest==md5sum: print >>log, wc.i18n._("extern filter %s not changed, ignoring")%filename continue print >>log, wc.i18n._("updating extern filter %s")%filename else: print >>log, wc.i18n._("adding new extern filter %s")%filename chg = True if not dryrun: url = baseurl+filename try: page = open_url(url) except IOError, msg: print >>log, wc.i18n._("error fetching %s:")%url, msg continue data = page.read() if not data: print >>log, wc.i18n._("error fetching %s:")%url, \ wc.i18n._("got no data") continue f = file(fullname, 'wb') f.write(data) f.close() return chg