rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
wc.log.exception(wc.LOG_PROXY, "read error %s", err) | wc.log.exception(wc.LOG_PROXY, "%s read error %s", self, err) | def handle_read (self): """read data from SSL connection, put it into recv_buffer and call process_read""" assert self.connected wc.log.debug(wc.LOG_PROXY, '%s SslConnection.handle_read', self) if len(self.recv_buffer) > wc.proxy.Connection.MAX_BUFSIZE: wc.log.warn(wc.LOG_PROXY, '%s read buffer full', self) return try:... |
wc.log.debug(wc.LOG_NET, 'data %r', data) | def handle_read (self): """read data from SSL connection, put it into recv_buffer and call process_read""" assert self.connected wc.log.debug(wc.LOG_PROXY, '%s SslConnection.handle_read', self) if len(self.recv_buffer) > wc.proxy.Connection.MAX_BUFSIZE: wc.log.warn(wc.LOG_PROXY, '%s read buffer full', self) return try:... | |
def _debugbuf (self): """print debugging information about data buffer status""" | def __str__ (self): return "%s in state %s"%(self.__class__.__name__, str(self.state)) def debugbuf (self): """print debugging information about buffered data""" | def _debugbuf (self): """print debugging information about data buffer status""" 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()) |
debug(FILTER, "%s tagbuf2data", self) | def tagbuf2data (self): """Append all tags of the tag buffer to the output buffer""" tagbuf2data(self.tagbuf, self.outbuf) self.tagbuf = [] | |
waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state[0]!='parse': | if self.waitbuf: waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state[0]=='wait': | def feed (self, data): """feed some data to the parser""" if self.state[0]=='parse': # look if we must replay something if self.waited > 0: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state[0]!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbu... |
debug(FILTER, "parser feed %r", data) | debug(FILTER, "%s parser feed %r", self, data) | def feed (self, data): """feed some data to the parser""" if self.state[0]=='parse': # look if we must replay something if self.waited > 0: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state[0]!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbu... |
debug(FILTER, "empty parser feed") | debug(FILTER, "%s empty parser feed", self) | def feed (self, data): """feed some data to the parser""" if self.state[0]=='parse': # look if we must replay something if self.waited > 0: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state[0]!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbu... |
debug(FILTER, "parser wait") self.inbuf.write(data) | assert False, "parser %s has unknown parser state"%str(self) | def feed (self, data): """feed some data to the parser""" if self.state[0]=='parse': # look if we must replay something if self.waited > 0: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state[0]!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbu... |
def flush (self, finish=False): """flush pending data and return the flushed output buffer""" debug(FILTER, "parser flush finish=%s", str(finish)) | def flush (self): """flush pending data""" debug(FILTER, "%s flush", self) | def flush (self, finish=False): """flush pending data and return the flushed output buffer""" debug(FILTER, "parser flush finish=%s", str(finish)) if self.waited > 100: error(FILTER, "waited too long for %s"%self.state[1]) # tell recursive background downloaders to stop if hasattr(self.handler, "finish"): self.handler.... |
error(FILTER, "waited too long for %s"%self.state[1]) | assert self.state[0]=='wait', 'parser %s has waited flag set in non-wait state' % str(self) error(FILTER, "%s waited too long", self) | def flush (self, finish=False): """flush pending data and return the flushed output buffer""" debug(FILTER, "parser flush finish=%s", str(finish)) if self.waited > 100: error(FILTER, "waited too long for %s"%self.state[1]) # tell recursive background downloaders to stop if hasattr(self.handler, "finish"): self.handler.... |
raise FilterWait("HtmlParser[wait]: waited %d times for %s"%\ (self.waited, self.state[1])) if finish: super(HtmlParser, self).flush() self.tagbuf2data() | raise FilterWait("waited %d at parser %s"%(self.waited, str(self))) super(HtmlParser, self).flush() def getoutput (self): """returns all data in output buffer and clears the output buffer""" | def flush (self, finish=False): """flush pending data and return the flushed output buffer""" debug(FILTER, "parser flush finish=%s", str(finish)) if self.waited > 100: error(FILTER, "waited too long for %s"%self.state[1]) # tell recursive background downloaders to stop if hasattr(self.handler, "finish"): self.handler.... |
return False chg = False | return chg | def update (config, baseurl, 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 """ url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, "error ... |
for filename in filterconf_files(): | for filename in wc.filterconf_files(): | def update (config, baseurl, 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 """ url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, "error ... |
lines = page.read().splitlines() for line in lines: | for line in page.read().splitlines(): | def update (config, baseurl, 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 """ url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, "error ... |
return False | return chg | def update (config, baseurl, 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 """ url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, "error ... |
fullname = os.path.join(ConfigDir, filename) | fullname = os.path.join(wc.ConfigDir, filename) | def update (config, baseurl, 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 """ url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, "error ... |
p = ZapperParser(fullname) | p = wc.ZapperParser(fullname, compile_data=False) | def update (config, baseurl, 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 """ url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, "error ... |
return False lines = page.read().splitlines() for line in lines: | return chg for line in page.read().splitlines(): | def update (config, baseurl, 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 """ url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >>log, "error ... |
config = Configuration() | def _test (): # read local configuration config = Configuration() # test base url for all files baseurl = "http://localhost/~calvin/webcleaner.sf.net/htdocs/test/" update(config, baseurl, dryrun=True) | |
update(config, baseurl, dryrun=True) | update(wc.Configuration(), baseurl, dryrun=True) | def _test (): # read local configuration config = Configuration() # test base url for all files baseurl = "http://localhost/~calvin/webcleaner.sf.net/htdocs/test/" update(config, baseurl, dryrun=True) |
print "Test: oooooops" | print >>sys.stderr, "Test: oooooops" | def _main (): """USAGE: test/run.sh test/filterfile.py <.html file>""" import sys if len(sys.argv)!=2: print _main.__doc__ sys.exit(1) fname = sys.argv[1] if fname=="-": f = sys.stdin else: f = file(fname) from test import initlog, disable_rating_rules initlog("test/logging.conf") import wc wc.config = wc.Configuration... |
if not (scheme and hostname and port): | if not scheme: | def __init__ (self, client, request, headers, content, nofilter, compress, mime=None): self.client = client self.request = request self.headers = headers self.compress = compress self.content = content self.nofilter = nofilter self.mime = mime debug(BRING_IT_ON, "Proxy:", `self.request`) self.method, self.url, protocol... |
if not scheme: | def __init__ (self, client, request, headers, content, nofilter, compress, mime=None): self.client = client self.request = request self.headers = headers self.compress = compress self.content = content self.nofilter = nofilter self.mime = mime debug(BRING_IT_ON, "Proxy:", `self.request`) self.method, self.url, protocol... | |
if not hostname: | if scheme!='file' and not hostname: | def __init__ (self, client, request, headers, content, nofilter, compress, mime=None): self.client = client self.request = request self.headers = headers self.compress = compress self.content = content self.nofilter = nofilter self.mime = mime debug(BRING_IT_ON, "Proxy:", `self.request`) self.method, self.url, protocol... |
if not port: | if scheme!='file' and not port: | def __init__ (self, client, request, headers, content, nofilter, compress, mime=None): self.client = client self.request = request self.headers = headers self.compress = compress self.content = content self.nofilter = nofilter self.mime = mime debug(BRING_IT_ON, "Proxy:", `self.request`) self.method, self.url, protocol... |
headers.addheader("Via", "1.1 unknown") | headers.addheader("Via", "1.1 unknown\r") | def set_via_header (headers): """ Set "Via:" header. """ headers.addheader("Via", "1.1 unknown") |
headers.addheader('Warning', warning) | headers.addheader('Warning', warning+"\r") | def remove_warning_headers (headers): """ Remove old warning headers. """ if "Warning" not in headers: return tokeep = [] date = wc.http.date.parse_http_date(headers['Date']) for warning in headers.getheaders("Warning"): warncode, warnagent, warntext, warndate = \ wc.http.parse_http_warning(warning) if warndate is None... |
headers.addheader('Trailer', trailer) | headers.addheader('Trailer', trailer+'\r') | def check_trailer_headers (headers): """ Message header fields listed in the Trailer header field MUST NOT include the following header fields: . Transfer-Encoding . Content-Length . Trailer """ if "Trailer" not in headers: return tokeep = [] for trailer in headers.getheaders("Trailer"): if trailer.lower() not in forbi... |
urlparts = [ urllib.quote(p) for p in urlparts ] return urlparse.urlunparse(urlparts) | urlparts = [ urllib.quote(p, '/=&') for p in urlparts ] url = urlparse.urlunparse(urlparts) return url | def norm_url (url): """replace empty paths with / and normalize them""" url = urllib.unquote(url) urlparts = list(urlparse.urlparse(url)) path = urlparts[2].replace('\\', '/') if not path or path=='/': urlparts[2] = '/' else: # XXX this works only under windows and posix?? # collapse redundant path segments urlparts[2]... |
toremove = _getlist(form, 'rule_matchurls') | toremove = [u for u in _getlist(form, 'rule_matchurls') if u in currule.matchurls] | def _form_rule_delmatchurls (form): toremove = _getlist(form, 'rule_matchurls') if toremove: for matchurl in toremove: currule.matchurls.remove(matchurl) currule.compile_matchurls() info['rulematchurl'] = True |
toremove = _getlist(form, 'rule_nomatchurls') | toremove = [u for u in _getlist(form, 'rule_nomatchurls') if u in currule.nomatchurls] | def _form_rule_delnomatchurls (form): toremove = _getlist(form, 'rule_nomatchurls') if toremove: for nomatchurl in toremove: currule.nomatchurls.remove(nomatchurl) currule.compile_nomatchurls() info['rulenomatchurl'] = True |
"charset": wc.ConfigCharset, "title_en": wc.XmlUtils.xmlquote("%s %s" % (ftype.capitalize(), cat)), "title_de": wc.XmlUtils.xmlquote("%s %s" % (transtypes[ftype]['de'].capitalize(), transcats[cat]['de'].capitalize())), "desc_en": wc.XmlUtils.xmlquote("Automatically generated on %s" % date), | "charset": wc.configuration.ConfigCharset, "title_en": wc.XmlUtils.xmlquote("%s %s" % (ftype.capitalize(), cat)), "title_de": wc.XmlUtils.xmlquote("%s %s" % (transtypes[ftype]['de'].capitalize(), transcats[cat]['de'].capitalize())), "desc_en": wc.XmlUtils.xmlquote( "Automatically generated on %s" % date), | def write_folder (cat, ftype, data, f): print "write", cat, "folder" d = { "charset": wc.ConfigCharset, "title_en": wc.XmlUtils.xmlquote("%s %s" % (ftype.capitalize(), cat)), "title_de": wc.XmlUtils.xmlquote("%s %s" % (transtypes[ftype]['de'].capitalize(), transcats[cat]['de'].capitalize())), "desc_en": wc.XmlUtils.xml... |
self._debug(NIGHTMARE, "feed", `data`) | def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO()... | |
self._debug(NIGHTMARE, "feed") | def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO()... | |
self._debug(NIGHTMARE, "wait") | def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO()... | |
self._debug(NIGHTMARE, "startElement", `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 self._debug(NIGHTMARE, "startElement", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.wa... | |
self._debug(NIGHTMARE, "matched rule %s on tag %s" % (`rule.title`, `tag`)) | def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data self._debug(NIGHTMARE, "startElement", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.wa... | |
self._debug(NIGHTMARE, "put on buffer") | def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data self._debug(NIGHTMARE, "startElement", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.wa... | |
self._debug(NIGHTMARE, "switching back to parse with") | def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.js_script: print >> sys.stderr, "HtmlParser[%d]: empty JS src"%self.level, url else: self.buf.append([STARTTAG, "scri... | |
self._debug(HURT_ME_PLENTY, "JS read", len(data), "<=", url) | def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.js_script: print >> sys.stderr, "HtmlParser[%d]: empty JS src"%self.level, url else: self.buf.append([STARTTAG, "scri... | |
self._debug(HURT_ME_PLENTY, "JS jsScriptSrc", `url`, `ver`) | def jsScriptSrc (self, url, language): """Start a background download for <script src=""> tags""" assert self.state=='parse' ver = 0.0 if language: mo = re.search(r'(?i)javascript(?P<num>\d\.\d)', language) if mo: ver = float(mo.group('num')) url = urlparse.urljoin(self.url, url) self._debug(HURT_ME_PLENTY, "JS jsScrip... | |
if self.addr[0] not in config['allowed_hosts']: | if not config['allowedhosts'].has_key(self.addr[0]): | def __init__ (self, socket, addr): Connection.__init__(self, socket) self.addr = addr self.state = 'request' self.server = None self.request = '' self.headers = None self.bytes_remaining = None # for content only self.content = '' if self.addr[0] not in config['allowed_hosts']: self.close() |
if self.enclosed and self.tag in NO_CLOSE_TAGS: raise ValueError, "reading rule %r: tag %r has no end tag, " \ "so specifying an enclose value is invalid." % \ (self.titles['en'], tag) | def __init__ (self, sid=None, titles=None, descriptions=None, disable=0, tag=u"a", attrs=None, enclosed=u"", part=wc.filter.html.COMPLETE, replacement=u""): """ Initialize rule data. """ super(HtmlrewriteRule, self).__init__(sid=sid, titles=titles, descriptions=descriptions, disable=disable) self.tag = tag self.tag_ro ... | |
if self.tag in NO_CLOSE_TAGS: return True | for tag in NO_CLOSE_TAGS: if self.match_tag(tag): return True | def matches_starttag (self): """ See if this rule matches start tags. """ if self.tag in NO_CLOSE_TAGS: return True return self.part not in [ wc.filter.html.ENCLOSED, wc.filter.html.COMPLETE, ] |
if self.tag in NO_CLOSE_TAGS: return False | for tag in NO_CLOSE_TAGS: if self.match_tag(tag): return False | def matches_endtag (self): """ See if this rule matches end tags. """ if self.tag in NO_CLOSE_TAGS: return False return self.part not in [ wc.filter.html.ATTR, wc.filter.html.ATTRVAL, wc.filter.html.ATTRNAME, ] |
def XtestScriptSrc1 (self): | def testScriptSrc1 (self): | def XtestScriptSrc1 (self): self.filt( |
def XtestScriptSrc2 (self): | def testScriptSrc2 (self): | def XtestScriptSrc2 (self): self.filt( |
def XtestScriptSrc3 (self): | def testScriptSrc3 (self): | def XtestScriptSrc3 (self): """missing </script>""" self.filt( |
print "line", `l` | def parse_headers (): headers = [] try: s = get_data("/headers/") #debug(BRING_IT_ON, "headers data", s) except (IOError, ValueError): print >> sys.stderr, _("WebCleaner is not running") return headers if s=="-": return headers lines = s.split("\n") for l in lines: print "line", `l` # strip off paranthesis l = l[1:-1] ... | |
print >>sys.stderr, "JS:", data | self.jsfilter.feed(data) | def processData (self, data): print >>sys.stderr, "JS:", data # XXX parse recursively |
self.buffer.append((ENDTAG, tag)) | 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. | |
if not filtered and self.javascript: | if not filtered and self.javascript and tag=='script': | 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. |
if tag!='script': return if not self.buffer: print >>sys.stderr, "empty buffer on </script>" | if len(self.buffer)<2: print >>sys.stderr, "short buffer on </script>", self.buffer | def jsEndElement (self, tag): """parse generated html for scripts""" if tag!='script': return if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return last = self.buffer[-1] if last[0]!=DATA: print >>sys.stderr, "missing body for </script>", last return script = last[1].strip() if script.startswith("<... |
last = self.buffer[-1] if last[0]!=DATA: print >>sys.stderr, "missing body for </script>", last | if self.buffer[-1][0]!=DATA or self.buffer[-2][0]!=STARTTAG: print >>sys.stderr, "missing tags for </script>", self.buffer[-2:] | def jsEndElement (self, tag): """parse generated html for scripts""" if tag!='script': return if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return last = self.buffer[-1] if last[0]!=DATA: print >>sys.stderr, "missing body for </script>", last return script = last[1].strip() if script.startswith("<... |
script = last[1].strip() | script = self.buffer[-1][1].strip() self.buffer[-2:] = [] | def jsEndElement (self, tag): """parse generated html for scripts""" if tag!='script': return if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return last = self.buffer[-1] if last[0]!=DATA: print >>sys.stderr, "missing body for </script>", last return script = last[1].strip() if script.startswith("<... |
self.jsEnv.executeScriptAsFunction(val, 0.0) | self.jsfilter = HtmlFilter(self.rules, self.document, comments=self.comments, javascript=self.javascript) self.jsEnv.executeScriptAsFunction(script, 0.0) | def jsEndElement (self, tag): """parse generated html for scripts""" if tag!='script': return if not self.buffer: print >>sys.stderr, "empty buffer on </script>" return last = self.buffer[-1] if last[0]!=DATA: print >>sys.stderr, "missing body for </script>", last return script = last[1].strip() if script.startswith("<... |
if attrs.get('imgreducer_convert'): img = img.convert() | if img.mode not in ('RGB', 'L'): img.draft("RGB", img.size) img = img.convert("RGB") | def finish (self, data, attrs): """ Feed image data to buffer, then convert it and return result. """ if self.init_image_reducer: self.set_ctype_header(attrs) self.init_image_reducer = False if not attrs.has_key('imgreducer_buf'): return data p = attrs['imgreducer_buf'] if data: p.write(data) p.seek(0) try: img = Image... |
"I/O error reading image data: %s", str(msg)) | "I/O error reading image data %r: %s", attrs['url'], str(msg)) | def finish (self, data, attrs): """ Feed image data to buffer, then convert it and return result. """ if self.init_image_reducer: self.set_ctype_header(attrs) self.init_image_reducer = False if not attrs.has_key('imgreducer_buf'): return data p = attrs['imgreducer_buf'] if data: p.write(data) p.seek(0) try: img = Image... |
d['imgreducer_convert'] = convert(ctype) | def get_attrs (self, url, localhost, stages, headers): """ Initialize image reducer buffer and flags. """ if not self.applies_to_stages(stages): return {} # don't filter tiny images d = super(ImageReducer, self).get_attrs(url, localhost, stages, headers) # weed out the rules that don't apply to this url rules = [ rule ... | |
def convert (ctype): """ Return True if an image has to be convert()ed before saving. """ return ctype in ('image/gif',) | def get_attrs (self, url, localhost, stages, headers): """ Initialize image reducer buffer and flags. """ if not self.applies_to_stages(stages): return {} # don't filter tiny images d = super(ImageReducer, self).get_attrs(url, localhost, stages, headers) # weed out the rules that don't apply to this url rules = [ rule ... | |
data += content | data += request.content | def construct_request_data (self, request): """ Construct valid HTTP request data string. """ lines = [] version = "HTTP/%d.%d" % request.version lines.append("%s %s %s" % (request.method, request.uri, version)) lines.extend(request.headers) # an empty line ends the headers lines.extend(("", "")) data = "\r\n".join(lin... |
if subkey.get('EnableDHCP')==1: ip = subkey.get('DhcpIPAddress') | if subkey.get('EnableDHCP'): ip = subkey.get('DhcpIPAddress', '') | def get_localaddrs (): """all active interfaces' ip addresses""" addrs = sets.Set() try: # search interfaces key = wc.winreg.key_handle(wc.winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces") for subkey in key.subkeys(): if subkey.get('EnableDHCP')==1: ip = subkey.get('DhcpIPAddr... |
ip = subkey.get('IPAddress') if ip: addrs.add(ip) | ip = subkey.get('IPAddress', '') if not (isinstance(ip, basestring) and ip): continue addrs.add(str(ip)) | def get_localaddrs (): """all active interfaces' ip addresses""" addrs = sets.Set() try: # search interfaces key = wc.winreg.key_handle(wc.winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces") for subkey in key.subkeys(): if subkey.get('EnableDHCP')==1: ip = subkey.get('DhcpIPAddr... |
p.debug(1) | 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 wc.parser.htmllib import HtmlPrinter from wc.parser import htmlsax p = htmlsax.parser(HtmlPrinter()) p.debug(1) size = 10... | |
""" % fname("example") | """ % fname("example", sep="/") | def fname (name): return os.path.join("wc", "dns", "tests", name) |
translator = gettext.translation(Name, LocaleDir, [lang]) | if lang!='en': translator = gettext.translation(Name, LocaleDir, [lang]) else: translator = None | def __init__ (self, client, url, form, protocol, status=200, msg=i18n._('Ok'), context={}, headers={'Content-Type': 'text/html'}): self.client = client # we pretend to be the server self.connected = True try: lang = i18n.get_headers_lang(headers) # get the template filename path, dirs, lang = get_template_url(url, lang... |
if os.path.isdir(fname) or os.path.islink(fname): return False try: if os.path.exists(fname): open(fname, 'a').close() return True else: open(fname, 'w').close() os.remove(fname) return True except IOError: pass return False def get_log_file (name, logname, trydirs=[]): """get full path name to writeable logfile""" d... | if os.path.isdir(fname) or os.path.islink(fname): return False try: if os.path.exists(fname): open(fname, 'a').close() return True else: open(fname, 'w').close() os.remove(fname) return True except IOError: pass return False def get_log_file (name, logname, trydirs=None): """get full path name to writeable logfile"""... | def iswritable (fname): """return True if given file is writable""" if os.path.isdir(fname) or os.path.islink(fname): return False try: if os.path.exists(fname): open(fname, 'a').close() return True else: open(fname, 'w').close() os.remove(fname) return True except IOError: pass return False |
p.feed("""<a b="c"><""") p.feed("""d>""") | s = """<h1>bla</h1>""" for c in s: p.feed(c) p.flush() | def _broken (): p = HtmlPrinter() p.feed("""<a b="c"><""") p.feed("""d>""") |
return (mo.group(1), mo.group(2)) if __name__=='__main__': for url in ['', 'a', 'a/b', 'http://imadoofus.com', 'http://imadoofus.com//', 'http://imadoofus.com/?q=a', 'http://imadoofus.com/?q=a 'http://imadoofus.com/a/b//c', 'http://imadoofus.com/forum', 'http://imadoofus.com/forum/', ]: print rating_split_url(url) pr... | vmin, vmax = mo.group(1), mo.group(2) if vmin=="": vmin = None else: vmin = int(vmin) if vmax=="": vmax = None else: vmax = int(vmax) return (vmin, vmax) | def rating_range (value): """parse value as range; return tuple (rmin, rmax) or None on error""" mo = _range_re.match(value) if not mo: return None return (mo.group(1), mo.group(2)) |
def server_response (self, response, statuscode, headers): | def server_response (self, response, statuscode, status, headers): | def server_response (self, response, statuscode, headers): """the server got a response""" # Okay, transfer control over to the real client if self.client.connected: config['requests']['valid'] += 1 self.server.client = self.client self.client.server_response(self.server, response, statuscode, headers) else: self.serve... |
self.client.server_response(self.server, response, statuscode, headers) | self.client.server_response(self.server, response, status, headers) | def server_response (self, response, statuscode, headers): """the server got a response""" # Okay, transfer control over to the real client if self.client.connected: config['requests']['valid'] += 1 self.server.client = self.client self.client.server_response(self.server, response, statuscode, headers) else: self.serve... |
elif not ct.startswith(gm[0]) and \ gm[0] in _fix_content_types: warn(PROXY, i18n._("change Content-Type from %s to %s in %s"), `ct`, `gm[0]`, `self.url`) self.headers['Content-Type'] = "%s\r"%gm[0] if gm[1] and gm[1] in _fix_content_encodings: ce = self.headers.get('Content-Encoding', None) if ce is None: self.header... | def check_headers (self): """add missing content-type and/or encoding headers""" # 304 Not Modified does not send any type or encoding info, # because this info was cached if self.statuscode == '304': return # check content-type against our own guess i = self.document.find('?') if i>0: document = self.document[:i] else... | |
headers.append("Content-Length: %d" % len(content)-5) | headers.append("Content-Length: %d" % (len(content)-5)) | def get_request_headers (self, content): port = self.server.socket.getsockname()[1] headers = [ "Host: localhost:%d" % port, "Proxy-Connection: close", ] if content: headers.append("Content-Length: %d" % len(content)) headers.append("Content-Length: %d" % len(content)-5) return headers |
"Content-Length: %d" % len(content)-5, | "Content-Length: %d" % (len(content)-5), | def get_response_headers (self, content): return [ "Content-Type: text/plain", "Content-Length: %d" % len(content), "Content-Length: %d" % len(content)-5, ] |
def generate_sids (): | def generate_sids (prefix="wc"): | def generate_sids (): for rule in _rules_without_sid: rule.sid = generate_unique_sid("wc") del _rules_without_sid[:] |
rule.sid = generate_unique_sid("wc") | rule.sid = generate_unique_sid(prefix) | def generate_sids (): for rule in _rules_without_sid: rule.sid = generate_unique_sid("wc") del _rules_without_sid[:] |
hosts = sort_seq(ip.map2hosts(self['nofilterhosts'])) | hosts = self['nofilterhosts'] | def write_proxyconf (self): """write proxy configuration""" f = file(self['configfile'], 'w') f.write("""<?xml version="1.0" encoding="%s"?> |
'HTTP/1.0 %d Use different host\r\n', | 'HTTP/1.0 %d %s\r\n', 'Server: WebCleaner Proxy\r\n' | def error(self, code, msg): ServerHandleDirectly( self.client, 'HTTP/1.0 %d Use different host\r\n', 'Content-type: text/html\r\n' 'Location: http://%s\r\n' '\r\n' % (code, new_url), msg) |
'Location: http://%s\r\n' '\r\n' % (code, new_url), | '\r\n' '<html><head>' '<title>WebCleaner Proxy Error %d %s</title>' '</head><body bgcolor=" 'WebCleaner Proxy Error %d %s<br>' '%s<br></center></body></html>' % (code, msg, code, msg), | def error(self, code, msg): ServerHandleDirectly( self.client, 'HTTP/1.0 %d Use different host\r\n', 'Content-type: text/html\r\n' 'Location: http://%s\r\n' '\r\n' % (code, new_url), msg) |
assert self.state == 'dns' if answer.isError(): self.error(400, _(answer.data)) return self.state = 'server' self.ipaddr = socket.gethostbyname(self.hostname) self.find_server() def _handle_dns(self, hostname, answer): | def handle_dns(self, hostname, answer): assert self.state == 'dns' if answer.isError(): self.error(400, _(answer.data)) return self.state = 'server' self.ipaddr = socket.gethostbyname(self.hostname) | |
print "X", repr(file_length) print "X", repr(offset) | def classify (self, f): if not self.entries: raise StandardError("Not initialised properly") # Are we still looking for the ruleset to apply or are we in a rule found_rule = False # When we found the rule, what is the level that we successfull passed in_level = 0 # If we failed part of the rule there is no point lookin... | |
debug(PROXY, '%s <= read %d', self, len(data)) debug(CONNECTION, 'data %r', data) | def handle_read (self): """read data from connection, put it into recv_buffer and call process_read""" assert self.connected debug(PROXY, '%s handle_read', self) | |
debug(HURT_ME_PLENTY, "request", `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(HURT_ME_PLENTY, "request", `self.request`) self.method, self.url, protocol = self.request.split() s... | |
url = baseurl+filename+".gz" | url = baseurl+filename | 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_... |
if encoding in ('gzip', 'x-gzip', 'deflate') and rewrite: | if encoding in ('gzip', 'x-gzip', 'deflate'): | def process_headers (self): # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.... |
elif encoding and encoding!='identity' and rewrite: | elif encoding and encoding!='identity': | def process_headers (self): # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.... |
self.attrs = initStateObjects(self.headers, self.url) if self.headers.get('Content-Length') is None: self.headers['Connection'] = 'close' wc.proxy.HEADERS.append((self.url, 1, self.headers.headers)) self.client.server_response(self.response, self.headers) self.attrs['nofilter'] = self.nofilter['nofilter'] if ((respons... | def process_headers (self): # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.... | |
if self.document.endswith(".bz2") or \ self.document.endswith(".tgz") or \ self.document.endswith(".gz"): gm = mimetypes.guess_type(self.document, False) if gm[1]: self.headers['Content-Encoding'] = gm[1] if gm[0]: self.headers['Content-Type'] = gm[0] | def process_headers (self): # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.... | |
p.feed("""<a><t""") p.feed("""r>""") | p.feed("""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <META NAME="Description" CONTENT="Obsession Development: Products"> <META NAME="Resource-Type" CONTENT="document"> <META NAME="Content-Type" CONTENT="text/html, charset=iso-8859-1"> <META HTTP-EQUIV="Content-Style-Type... | def _broken (): p = HtmlPrinter() p.feed("""<a><t""") p.feed("""r>""") p.flush() |
if not category.valid_value(value): | if category.iterable: realvalue = value else: realvalue = _intrange_from_string(value) if not category.valid_value(realvalue): | def _form_ratings (form): """Check category value validity""" for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname) if category is None: # unknown category error['categoryvalue'] = True return False if not category.valid_value(value): error['categoryvalue'] = True return False if ... |
p = wc.configuration.ZapperParser(filename) | p = wc.configuration.confparse.ZapperParser(filename) | def read_ids (filename, ids): p = wc.configuration.ZapperParser(filename) p.parse() ids['folder']['sid'] = str(p.folder.sid) ids['folder']['oid'] = p.folder.oid ids['folder']['configversion'] = str(p.folder.configversion) for rule in p.folder.rules: for ftype in ('domains', 'urls'): if rule.name.endswith(ftype): ids[ft... |
fname = "extracted/"+fname[:-3] | fname = os.path.join(extract_to, fname[:-3]) | def blacklist (fname, extract_to="extracted"): source = os.path.join("downloads", fname) # extract tar if fname.endswith(".tar.gz") or fname.endswith(".tgz"): print "extracting archive", fname f = tarfile.TarFile.gzopen(source) for m in f: a, b = os.path.split(m.name) a = os.path.basename(a) if b in myfiles and a in my... |
self.js_script += data | self.js_script += data.decode(self.htmlparser.encoding, "ignore") | def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.htmlparser.state[0] == 'wait', "non-wait state" wc.log.debug(wc.LOG_JS, "%s jsScriptData %r", self, data) if data is None: if not self.js_script: wc.log.warn(wc... |
res = [None] | def _form_reset (): """reset info/error and global vars""" global filterenabled, filterdisabled filterenabled = u"" filterdisabled = u"" for key in info.keys(): info[key] = False for key in error.keys(): error[key] = False res = [None] | |
def update (wconfig, baseurl, dryrun=False, log=None): | def update (wconfig, dryrun=False, log=None): | def update (wconfig, baseurl, 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 url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >... |
p = wc.ZapperParser(fullname, compile_data=False) p.parse(page, wconfig) | p = wc.ZapperParser(fullname, wconfig, compile_data=False) p.parse(fp=page) | def update (wconfig, baseurl, 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 url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >... |
def _test (): initlog("test/logging.conf") baseurl = "http://localhost/~calvin/webcleaner.sf.net/htdocs/test/" update(wc.Configuration(), baseurl, dryrun=True) if __name__=='__main__': _test() | def update (wconfig, baseurl, 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 url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >... | |
def new_instance (self, opts): | def new_instance (self, **opts): | def new_instance (self, opts): return HtmlFilter(self.rules, self.ratings, self.url, **opts) |
self._debug("cdata %r", data) | debug(FILTER, "%s cdata %r", self, data) | def cdata (self, data): """character data""" self._debug("cdata %r", data) return self._data(data) |
self._debug("characters %r", data) | debug(FILTER, "%s characters %r", self, data) | def characters (self, data): """characters""" self._debug("characters %r", data) return self._data(data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.