bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def _form_rule_urlparts (form): scheme = getval(form, 'rule_urlscheme').strip() if scheme!=currule.scheme: currule.scheme = scheme info.append("Rule url scheme changed") host = getval(form, 'rule_urlhost').strip() if host!=currule.host: currule.host = host info.append("Rule url host changed") port = getval(form, 'rule_urlport').strip() if port!=currule.port: currule.port = port info.append("Rule url port changed") path = getval(form, 'rule_urlpath').strip() if path!=currule.path: currule.path = path info.append("Rule url path changed") parameters = getval(form, 'rule_urlparameters').strip() if parameters!=currule.parameters: currule.parameters = parameters info.append("Rule url parameters changed") query = getval(form, 'rule_urlquery').strip() if query!=currule.query: currule.query = query info.append("Rule url query changed") fragment = getval(form, 'rule_urlfragment').strip() if fragment!=currule.fragment: currule.fragment = fragment info.append("Rule url fragment changed")
def _form_rule_urlparts (form): scheme = getval(form, 'rule_urlscheme').strip() if scheme!=currule.scheme: currule.scheme = scheme info.append("Rule url scheme changed") host = getval(form, 'rule_urlhost').strip() if host!=currule.host: currule.host = host info.append("Rule url host changed") port = getval(form, 'rule_urlport').strip() if port!=currule.port: currule.port = port info.append("Rule url port changed") path = getval(form, 'rule_urlpath').strip() if path!=currule.path: currule.path = path info.append("Rule url path changed") parameters = getval(form, 'rule_urlparameters').strip() if parameters!=currule.parameters: currule.parameters = parameters info.append("Rule url parameters changed") query = getval(form, 'rule_urlquery').strip() if query!=currule.query: currule.query = query info.append(i18n._("Rule url query changed")) fragment = getval(form, 'rule_urlfragment').strip() if fragment!=currule.fragment: currule.fragment = fragment info.append("Rule url fragment changed")
16,300
def _form_rule_urlparts (form): scheme = getval(form, 'rule_urlscheme').strip() if scheme!=currule.scheme: currule.scheme = scheme info.append("Rule url scheme changed") host = getval(form, 'rule_urlhost').strip() if host!=currule.host: currule.host = host info.append("Rule url host changed") port = getval(form, 'rule_urlport').strip() if port!=currule.port: currule.port = port info.append("Rule url port changed") path = getval(form, 'rule_urlpath').strip() if path!=currule.path: currule.path = path info.append("Rule url path changed") parameters = getval(form, 'rule_urlparameters').strip() if parameters!=currule.parameters: currule.parameters = parameters info.append("Rule url parameters changed") query = getval(form, 'rule_urlquery').strip() if query!=currule.query: currule.query = query info.append("Rule url query changed") fragment = getval(form, 'rule_urlfragment').strip() if fragment!=currule.fragment: currule.fragment = fragment info.append("Rule url fragment changed")
def _form_rule_urlparts (form): scheme = getval(form, 'rule_urlscheme').strip() if scheme!=currule.scheme: currule.scheme = scheme info.append("Rule url scheme changed") host = getval(form, 'rule_urlhost').strip() if host!=currule.host: currule.host = host info.append("Rule url host changed") port = getval(form, 'rule_urlport').strip() if port!=currule.port: currule.port = port info.append("Rule url port changed") path = getval(form, 'rule_urlpath').strip() if path!=currule.path: currule.path = path info.append("Rule url path changed") parameters = getval(form, 'rule_urlparameters').strip() if parameters!=currule.parameters: currule.parameters = parameters info.append("Rule url parameters changed") query = getval(form, 'rule_urlquery').strip() if query!=currule.query: currule.query = query info.append("Rule url query changed") fragment = getval(form, 'rule_urlfragment').strip() if fragment!=currule.fragment: currule.fragment = fragment info.append(i18n._("Rule url fragment changed"))
16,301
def _form_apply_block (form): _form_rule_urlparts(form) url = getval(form, 'rule_blockedurl').strip() if url!=currule.url: currule.url = url info.append("Rule blocked url changed")
def _form_apply_block (form): _form_rule_urlparts(form) url = getval(form, 'rule_blockedurl').strip() if url!=currule.url: currule.url = url info.append(i18n._("Rule blocked url changed"))
16,302
def _form_apply_header (form): _form_rule_matchurl(form) name = getval(form, 'rule_headername').strip() if not name: error.append("Empty header rule name") elif name!=currule.name: currule.name = name info.append("Rule header name changed") value = getval(form, 'rule_headervalue').strip() if value!=currule.value: currule.value = value info.append("Rule header value changed")
def _form_apply_header (form): _form_rule_matchurl(form) name = getval(form, 'rule_headername').strip() if not name: error.append(i18n._("Empty header rule name")) elif name!=currule.name: currule.name = name info.append("Rule header name changed") value = getval(form, 'rule_headervalue').strip() if value!=currule.value: currule.value = value info.append("Rule header value changed")
16,303
def _form_apply_header (form): _form_rule_matchurl(form) name = getval(form, 'rule_headername').strip() if not name: error.append("Empty header rule name") elif name!=currule.name: currule.name = name info.append("Rule header name changed") value = getval(form, 'rule_headervalue').strip() if value!=currule.value: currule.value = value info.append("Rule header value changed")
def _form_apply_header (form): _form_rule_matchurl(form) name = getval(form, 'rule_headername').strip() if not name: error.append("Empty header rule name") elif name!=currule.name: currule.name = name info.append(i18n._("Rule header name changed")) value = getval(form, 'rule_headervalue').strip() if value!=currule.value: currule.value = value info.append("Rule header value changed")
16,304
def _form_apply_header (form): _form_rule_matchurl(form) name = getval(form, 'rule_headername').strip() if not name: error.append("Empty header rule name") elif name!=currule.name: currule.name = name info.append("Rule header name changed") value = getval(form, 'rule_headervalue').strip() if value!=currule.value: currule.value = value info.append("Rule header value changed")
def _form_apply_header (form): _form_rule_matchurl(form) name = getval(form, 'rule_headername').strip() if not name: error.append("Empty header rule name") elif name!=currule.name: currule.name = name info.append("Rule header name changed") value = getval(form, 'rule_headervalue').strip() if value!=currule.value: currule.value = value info.append(i18n._("Rule header value changed"))
16,305
def _form_apply_image (form): _form_rule_matchurl(form) width = getval(form, 'rule_imgwidth').strip() try: width = int(width) except ValueError: error.append("Invalid image width value") return if width!=currule.width: currule.width = width info.append("Rule image width changed") height = getval(form, 'rule_imgheight').strip() try: height = int(height) except ValueError: error.append("Invalid image height value") return if height!=currule.height: currule.height = height info.append("Rule image height changed") # XXX todo: image types
def _form_apply_image (form): _form_rule_matchurl(form) width = getval(form, 'rule_imgwidth').strip() try: width = int(width) except ValueError: error.append(i18n._("Invalid image width value")) return if width!=currule.width: currule.width = width info.append("Rule image width changed") height = getval(form, 'rule_imgheight').strip() try: height = int(height) except ValueError: error.append("Invalid image height value") return if height!=currule.height: currule.height = height info.append("Rule image height changed") # XXX todo: image types
16,306
def _form_apply_image (form): _form_rule_matchurl(form) width = getval(form, 'rule_imgwidth').strip() try: width = int(width) except ValueError: error.append("Invalid image width value") return if width!=currule.width: currule.width = width info.append("Rule image width changed") height = getval(form, 'rule_imgheight').strip() try: height = int(height) except ValueError: error.append("Invalid image height value") return if height!=currule.height: currule.height = height info.append("Rule image height changed") # XXX todo: image types
def _form_apply_image (form): _form_rule_matchurl(form) width = getval(form, 'rule_imgwidth').strip() try: width = int(width) except ValueError: error.append("Invalid image width value") return if width!=currule.width: currule.width = width info.append(i18n._("Rule image width changed")) height = getval(form, 'rule_imgheight').strip() try: height = int(height) except ValueError: error.append("Invalid image height value") return if height!=currule.height: currule.height = height info.append("Rule image height changed") # XXX todo: image types
16,307
def _form_apply_image (form): _form_rule_matchurl(form) width = getval(form, 'rule_imgwidth').strip() try: width = int(width) except ValueError: error.append("Invalid image width value") return if width!=currule.width: currule.width = width info.append("Rule image width changed") height = getval(form, 'rule_imgheight').strip() try: height = int(height) except ValueError: error.append("Invalid image height value") return if height!=currule.height: currule.height = height info.append("Rule image height changed") # XXX todo: image types
def _form_apply_image (form): _form_rule_matchurl(form) width = getval(form, 'rule_imgwidth').strip() try: width = int(width) except ValueError: error.append("Invalid image width value") return if width!=currule.width: currule.width = width info.append("Rule image width changed") height = getval(form, 'rule_imgheight').strip() try: height = int(height) except ValueError: error.append(i18n._("Invalid image height value")) return if height!=currule.height: currule.height = height info.append("Rule image height changed") # XXX todo: image types
16,308
def _form_apply_image (form): _form_rule_matchurl(form) width = getval(form, 'rule_imgwidth').strip() try: width = int(width) except ValueError: error.append("Invalid image width value") return if width!=currule.width: currule.width = width info.append("Rule image width changed") height = getval(form, 'rule_imgheight').strip() try: height = int(height) except ValueError: error.append("Invalid image height value") return if height!=currule.height: currule.height = height info.append("Rule image height changed") # XXX todo: image types
def _form_apply_image (form): _form_rule_matchurl(form) width = getval(form, 'rule_imgwidth').strip() try: width = int(width) except ValueError: error.append("Invalid image width value") return if width!=currule.width: currule.width = width info.append("Rule image width changed") height = getval(form, 'rule_imgheight').strip() try: height = int(height) except ValueError: error.append("Invalid image height value") return if height!=currule.height: currule.height = height info.append(i18n._("Rule image height changed")) # XXX todo: image types
16,309
def _form_apply_pics (form): _form_rule_matchurl(form) print "XXX apply pics"
def _form_apply_pics (form): _form_rule_matchurl(form) for service in pics_services: if form.has_key("service_%s"%service): if not currule.ratings.has_key(service): currule.ratings[service] = {} for category in pics_categories[service]: currule.ratings[service][category] = 0 info.append(i18n._("PICS service %s enabled") % \ pics_data[service]['name']) else: if currule.ratings.has_key(service): del currule.ratings[service] info.append(i18n._("PICS service %s disabled") % \ pics_data[service]['name']) if currule.ratings.has_key(service): for category in pics_categories[service]: if form.has_key("category_%s_%s" % (service, category)): if not currule.ratings[service][category]: currule.ratings[service][category] = 1 info.append(i18n._("PICS service %s, category %s enabled") %\ (pics_data[service]['name'], category)) else: if currule.ratings[service][category]: currule.ratings[service][category] = 0 info.append(i18n._("PICS service %s, category %s disabled") %\ (pics_data[service]['name'], category))
16,310
def _form_apply_replace (form): _form_rule_matchurl(form) # note: do not strip() the search and replace form values search = getval(form, 'rule_search') if search!=currule.search: currule.search = search info.append("Rule replace search changed") replace = getval(form, 'rule_replace') if replace!=currule.replace: currule.replace = replace info.append("Rule replacement changed")
def _form_apply_replace (form): _form_rule_matchurl(form) # note: do not strip() the search and replace form values search = getval(form, 'rule_search') if search!=currule.search: currule.search = search info.append(i18n._("Rule replace search changed")) replace = getval(form, 'rule_replace') if replace!=currule.replace: currule.replace = replace info.append("Rule replacement changed")
16,311
def _form_apply_replace (form): _form_rule_matchurl(form) # note: do not strip() the search and replace form values search = getval(form, 'rule_search') if search!=currule.search: currule.search = search info.append("Rule replace search changed") replace = getval(form, 'rule_replace') if replace!=currule.replace: currule.replace = replace info.append("Rule replacement changed")
def _form_apply_replace (form): _form_rule_matchurl(form) # note: do not strip() the search and replace form values search = getval(form, 'rule_search') if search!=currule.search: currule.search = search info.append("Rule replace search changed") replace = getval(form, 'rule_replace') if replace!=currule.replace: currule.replace = replace info.append(i18n._("Rule replacement changed"))
16,312
def __repr__ (self): """object representation""" extra = self.persistent and "persistent " or "" if self.request: try: extra += self.request.split()[1] except IndexError: extra += '???'+self.request else: extra += 'being read' return '<%s:%-8s %s>' % ('client', self.state, extra)
def __repr__ (self): """object representation""" extra = "" if self.persistent: extra += "persistent " if self.server: extra += "server " if self.request: try: extra += self.request.split()[1] except IndexError: extra += '???'+self.request else: extra += 'being read' return '<%s:%-8s %s>' % ('client', self.state, extra)
16,313
def server_content (self, data): """The server received some content. Write it to the client.""" assert self.server, "%s server_content(%s) had no server" % \ (self, data) if data: self.write(data)
def server_content (self, data): """The server received some content. Write it to the client.""" assert self.server, "%s server_content(%r) had no server" % \ (self, data) if data: self.write(data)
16,314
def handle_close (self): """The client closed the connection, so cancel the server connection""" wc.log.debug(wc.LOG_PROXY, '%s handle_close', self) self.send_buffer = '' super(HttpClient, self).handle_close() if self.server: self.server.client_abort() self.server = None # If there isn't a server, then it's in the process of # doing DNS lookup or connecting. The matchmaker will # check to see if the client is still connected.
def handle_close (self): """The client closed the connection, so cancel the server connection""" wc.log.debug(wc.LOG_PROXY, '%s handle_close', self) self.send_buffer = '' if self.server: self.server.client_abort() self.server = None # If there isn't a server, then it's in the process of # doing DNS lookup or connecting. The matchmaker will # check to see if the client is still connected.
16,315
def __init__ (self, client, request, headers, content, nofilter, compress, mime=None): self.client = client self.server = None self.request = request self.headers = headers self.compress = compress self.content = content self.nofilter = nofilter self.mime = mime debug(PROXY, "ClientServer: %s", `self.request`) self.method, self.url, protocol = self.request.split() # strip leading zeros and other stuff protocol = fix_http_version(protocol) scheme, hostname, port, document = spliturl(self.url) # some clients send partial URI's without scheme, hostname # and port to clients, so we have to handle this if not scheme: # default scheme is http scheme = "http" elif scheme != 'http': warn(PROXY, "Forbidden scheme encountered at %s", self.url) client.error(403, i18n._("Forbidden")) return if not hostname and self.headers.has_key('Host'): host = self.headers['Host'] hostname, port = splitnport(host, 80) if not hostname or \ (hostname in config['localhosts'] and port==config['port']): # this is a direct proxy call, delegate it to local handler client.handle_local() return # fix missing trailing / if not document: document = '/' # add missing host headers for HTTP/1.1 if protocol=='HTTP/1.1' and not self.headers.has_key('Host'): if port!=80: self.headers['Host'] += "%s:%d\r"%(hostname, port) else: self.headers['Host'] = "%s\r"%hostname debug(PROXY, "ClientServer: splitted url %s %s %d %s", scheme, hostname, port, document) # prepare DNS lookup if config['parentproxy']: self.hostname = config['parentproxy'] self.port = config['parentproxyport'] self.document = self.url if config['parentproxycreds']: auth = config['parentproxycreds'] self.headers['Proxy-Authorization'] = "%s\r"%auth else: self.hostname = hostname self.port = port self.document = document # append information for wcheaders tool wc.proxy.HEADERS.append((self.url, 'client', self.headers.items())) # start DNS lookup self.state = 'dns' dns_lookups.background_lookup(self.hostname, self.handle_dns)
def __init__ (self, client, request, headers, content, nofilter, compress, mime=None): self.client = client self.server = None self.request = request self.headers = headers self.compress = compress self.content = content self.nofilter = nofilter self.mime = mime debug(PROXY, "ClientServer: %s", `self.request`) self.method, self.url, protocol = self.request.split() # strip leading zeros and other stuff protocol = fix_http_version(protocol) scheme, hostname, port, document = spliturl(self.url) # some clients send partial URI's without scheme, hostname # and port to clients, so we have to handle this if not scheme: # default scheme is http scheme = "http" elif scheme != 'http': warn(PROXY, "Forbidden scheme encountered at %s", self.url) client.error(403, i18n._("Forbidden")) return if not hostname and self.headers.has_key('Host'): host = self.headers['Host'] hostname, port = splitnport(host, 80) if not hostname or \ (hostname in config['localhosts'] and port==config['port']): # this is a direct proxy call, delegate it to local handler client.handle_local() return # fix missing trailing / if not document: document = '/' # add missing host headers for HTTP/1.1 if protocol=='HTTP/1.1' and not self.headers.has_key('Host'): if port!=80: self.headers['Host'] = "%s:%d\r"%(hostname, port) else: self.headers['Host'] = "%s\r"%hostname debug(PROXY, "ClientServer: splitted url %s %s %d %s", scheme, hostname, port, document) # prepare DNS lookup if config['parentproxy']: self.hostname = config['parentproxy'] self.port = config['parentproxyport'] self.document = self.url if config['parentproxycreds']: auth = config['parentproxycreds'] self.headers['Proxy-Authorization'] = "%s\r"%auth else: self.hostname = hostname self.port = port self.document = document # append information for wcheaders tool wc.proxy.HEADERS.append((self.url, 'client', self.headers.items())) # start DNS lookup self.state = 'dns' dns_lookups.background_lookup(self.hostname, self.handle_dns)
16,316
def rating_cache_load (): """load cached rating data from disk or return an empty cache if no cached data is found""" if os.path.isfile(rating_cachefile): fp = file(rating_cachefile) data = pickle.load(fp) fp.close() # remove invalid entries for url in data: if not is_valid_url(url): error(FILTER, "Invalid rating url %r", url) del data[url] return data return {}
def rating_cache_load (): """load cached rating data from disk or return an empty cache if no cached data is found""" if os.path.isfile(rating_cachefile): fp = file(rating_cachefile) rating_cache = pickle.load(fp) fp.close() # remove invalid entries for url in data: if not is_valid_url(url): error(FILTER, "Invalid rating url %r", url) del data[url] return data return {}
16,317
def rating_cache_load (): """load cached rating data from disk or return an empty cache if no cached data is found""" if os.path.isfile(rating_cachefile): fp = file(rating_cachefile) data = pickle.load(fp) fp.close() # remove invalid entries for url in data: if not is_valid_url(url): error(FILTER, "Invalid rating url %r", url) del data[url] return data return {}
def rating_cache_load (): """load cached rating data from disk or return an empty cache if no cached data is found""" if os.path.isfile(rating_cachefile): fp = file(rating_cachefile) data = pickle.load(fp) fp.close() # remove invalid entries toremove = [] for url in rating_cache: if not is_valid_url(url): error(FILTER, "Invalid rating url %r", url) del data[url] return data return {}
16,318
def rating_cache_load (): """load cached rating data from disk or return an empty cache if no cached data is found""" if os.path.isfile(rating_cachefile): fp = file(rating_cachefile) data = pickle.load(fp) fp.close() # remove invalid entries for url in data: if not is_valid_url(url): error(FILTER, "Invalid rating url %r", url) del data[url] return data return {}
def rating_cache_load (): """load cached rating data from disk or return an empty cache if no cached data is found""" if os.path.isfile(rating_cachefile): fp = file(rating_cachefile) data = pickle.load(fp) fp.close() # remove invalid entries for url in data: if not is_valid_url(url): error(FILTER, "Invalid rating url %r", url) toremove.append(url) if toremove: for url in toremove: del rating_cache[url] rating_cache_write()
16,319
def rating_cache_load (): """load cached rating data from disk or return an empty cache if no cached data is found""" if os.path.isfile(rating_cachefile): fp = file(rating_cachefile) data = pickle.load(fp) fp.close() # remove invalid entries for url in data: if not is_valid_url(url): error(FILTER, "Invalid rating url %r", url) del data[url] return data return {}
def rating_cache_load (): """load cached rating data from disk or return an empty cache if no cached data is found""" if os.path.isfile(rating_cachefile): fp = file(rating_cachefile) data = pickle.load(fp) fp.close() # remove invalid entries for url in data: if not is_valid_url(url): error(FILTER, "Invalid rating url %r", url) del data[url] return data return {}
16,320
def dict_attrs (attrs): _attrs = {} for name in attrs.getQNames(): _attrs[name] = attrs.getValueByQName(name) return _attrs
def dict_attrs (attrs): _attrs = wc.containers.ListDict() for name in attrs.getQNames(): _attrs[name] = attrs.getValueByQName(name) return _attrs
16,321
def __init__ (self, xmlrules, htmlrules, url, localhost): """ Init rules and buffers. """ # filter rules self.xmlrules = xmlrules self.htmlrules = htmlrules self.url = url # XML namespaces {name -> uri} and {uri -> name} self.prefixuri = {} self.uriprefix = {} # already filtered XML data self.outbuf = StringIO() self.tagbuf = [] self.rulestack = [] self.stack = [] self.encoding = "UTF-8"
def __init__ (self, xmlrules, htmlrules, url, localhost): """ Init rules and buffers. """ # filter rules self.xmlrules = xmlrules self.htmlrules = htmlrules self.url = url # XML namespaces {name -> uri} and {uri -> name} self.ns_current = [] self.ns_stack = [] # already filtered XML data self.outbuf = StringIO() self.tagbuf = [] self.rulestack = [] self.stack = [] self.encoding = "UTF-8"
16,322
def setDocumentLocator (self, locator): print "XXX setDocumentLocator", locator
def setDocumentLocator (self, locator): print "XXX setDocumentLocator", locator
16,323
def startPrefixMapping (self, prefix, uri): self.prefixuri[prefix] = uri self.uriprefix[uri] = prefix
def startPrefixMapping (self, prefix, uri): self.prefixuri[prefix] = uri self.uriprefix[uri] = prefix
16,324
def endPrefixMapping (self, prefix): if prefix in self.prefixuri: uri = self.prefixuri[prefix] del self.uriprefix[uri] del self.prefixuri[prefix] else: self.error("Removing unknown prefix mapping %r" % prefix)
def endPrefixMapping (self, prefix): if prefix in self.prefixuri: uri = self.prefixuri[prefix] del self.uriprefix[uri] del self.prefixuri[prefix] else: self.error("Removing unknown prefix mapping %r" % prefix)
16,325
def startElement (self, name, attrs): attrs = dict_attrs(attrs) if not self.stack: for prefix, uri in self.prefixuri.items(): if prefix: attrs[u"xmlns:%s" % prefix] = uri else: attrs[u"xmlns"] = uri self.stack.append((wc.filter.xmlfilt.STARTTAG, name, attrs)) item = [wc.filter.xmlfilt.STARTTAG, name, attrs] self.tagbuf.append(item) rulelist = [rule for rule in self.xmlrules \ if rule.match_tag(self.stack)] if rulelist: pos = len(self.tagbuf) self.rulestack.append((pos, rulelist))
def startElement (self, name, attrs): attrs = dict_attrs(attrs) for prefix, uri in self.ns_current: if prefix: attrs["xmlns:%s" % prefix] = uri else: attrs["xmlns"] = uri self.ns_current = [] self.stack.append((wc.filter.xmlfilt.STARTTAG, name, attrs)) item = [wc.filter.xmlfilt.STARTTAG, name, attrs] self.tagbuf.append(item) rulelist = [rule for rule in self.xmlrules \ if rule.match_tag(self.stack)] if rulelist: pos = len(self.tagbuf) self.rulestack.append((pos, rulelist))
16,326
def startElementNS (self, name, qname, attrs): if name[0]: ns = self.uriprefix[name[0]] if ns: name = u"%s:%s" % (ns, name[1]) else: name = name[1] else: name = name[1] self.startElement(name, attrs)
def startElementNS (self, name, qname, attrs): if name[0]: ns = self.uriprefix[name[0]] if ns: name = u"%s:%s" % (ns, name[1]) else: name = name[1] else: name = name[1] self.startElement(name, attrs)
16,327
def endElementNS (self, name, qname): if name[0]: ns = self.uriprefix[name[0]] if ns: name = u"%s:%s" % (ns, name[1]) else: name = name[1] else: name = name[1] self.endElement(name)
def endElementNS (self, name, qname): if name[0]: ns = self.uriprefix[name[0]] if ns: name = u"%s:%s" % (ns, name[1]) else: name = name[1] else: name = name[1] self.endElement(name)
16,328
def skippedEntity (self, name): print "XXX skippedEntity", name
def skippedEntity (self, name): print "XXX skippedEntity", name
16,329
def notationDecl (self, name, publicId, systemId): print "XXX notationDecl", name, publicId, systemId
def notationDecl (self, name, publicId, systemId): print "XXX notationDecl", name, publicId, systemId
16,330
def unparsedEntityDecl (self, name, publicId, systemId, ndata): print "XXX unparsedEntityDecl", name, publicId, systemId, ndata
def unparsedEntityDecl (self, name, publicId, systemId, ndata): print "XXX unparsedEntityDecl", name, publicId, systemId, ndata
16,331
def norm_url (url): """replace empty paths with / and normalize them""" urlparts = list(urlparse.urlparse(url)) path = urlparts[2] if not path: urlparts[2] = '/' else: # XXX only windows and posix?? # collapse redundant path segments urlparts[2] = os.path.normpath(path).replace('\\', '/') if path.endswith('/'): urlparts[2] += '/' return urlparse.urlunparse(urlparts)
def norm_url (url): """replace empty paths with / and normalize them""" urlparts = list(urlparse.urlparse(url)) path = urlparts[2] if not path or path=='/': urlparts[2] = '/' else: # XXX only windows and posix?? # collapse redundant path segments urlparts[2] = os.path.normpath(path).replace('\\', '/') if path.endswith('/'): urlparts[2] += '/' return urlparse.urlunparse(urlparts)
16,332
def applies_to_mime (self, mime): if mime is None: return False if not self.mimelist: return True for ro in self.mimelist: if ro.match(mime): return True return False
def applies_to_mime (self, mime): if mime is None: return False for ro in self.mimelist: if ro.match(mime): return True return False
16,333
def _main (): """USAGE: test/run.sh test/pconfig.py""" from test import initlog initlog("test/logging.conf") import profile, wc profile.run("config = wc.Configuration()", "filter.prof")
def _main (): """USAGE: test/run.sh test/pconfig.py""" from test import initlog initlog("test/logging.conf") import profile profile.run("config = wc.Configuration()", "filter.prof")
16,334
def geturl (basedir, file, fun, saveas=None): if saveas is not None: target = saveas else: target = file if os.path.exists("downloads/"+target): print "downloads/%s already exists"%target else: print "downloading", basedir+file os.makedirs(os.path.dirname("downloads/"+target)) urldata = urllib2.urlopen(basedir+file) f = open("downloads/"+target, 'w') f.write(urldata.read()) f.close() fun(target)
def geturl (basedir, file, fun, saveas=None): if saveas is not None: target = saveas else: target = file if os.path.exists("downloads/"+target): print "downloads/%s already exists"%target else: print "downloading", basedir+file d = os.path.dirname("downloads/"+target) if not os.path.isdir(d): os.makedirs(d) urldata = urllib2.urlopen(basedir+file) f = open("downloads/"+target, 'w') f.write(urldata.read()) f.close() fun(target)
16,335
def download_and_merge (): """Download all available filters and merge them""" # remove old files if not os.path.isdir("downloads"): os.mkdir("downloads") # from Pl Baltzersen and Lars Erik Hland (Squidguard guys) geturl("ftp://ftp.teledanmark.no/pub/www/proxy/squidGuard/contrib/", "blacklists.tar.gz", blacklist) # from Stefan Furtmayr geturl("http://www.bn-paf.de/filter/", "de-blacklists.tar.gz", blacklist) # from Craig Baird geturl("http://www.xpressweb.com/sg/", "sites.domains.gz", blacklist, saveas="porn/domains.gz") # from ????? geturl("http://squidguard.mesd.k12.or.us/", "squidguard.tar.gz", blacklist) # from fabrice Prigent geturl("ftp://ftp.univ-tlse1.fr/pub/reseau/cache/squidguard_contrib/", "blacklists.tar.gz", blacklist, saveas="contrib-blacklists.tar.gz") # dmoz category dumps #geturl("http://dmoz.org/rdf/", "content.rdf.u8.gz", dmozlists)
def download_and_merge (): """Download all available filters and merge them""" # remove old files if not os.path.isdir("downloads"): os.mkdir("downloads") # from Pl Baltzersen and Lars Erik Hland (Squidguard guys) geturl("ftp://ftp.teledanmark.no/pub/www/proxy/squidGuard/contrib/", "blacklists.tar.gz", blacklist) # from Stefan Furtmayr geturl("http://www.bn-paf.de/filter/", "de-blacklists.tar.gz", blacklist) # from Craig Baird geturl("http://www.xpressweb.com/sg/", "sites.domains.gz", blacklist, saveas="porn/domains.gz") # from ????? geturl("http://squidguard.mesd.k12.or.us/", "squidguard.tar.gz", blacklist) # from fabrice Prigent geturl("ftp://ftp.univ-tlse1.fr/pub/reseau/cache/squidguard_contrib/", "blacklists.tar.gz", blacklist, saveas="contrib-blacklists.tar.gz") # dmoz category dumps #geturl("http://dmoz.org/rdf/", "content.rdf.u8.gz", dmozlists)
16,336
def remove_old_data (): print "remove old data..." for d in ("extracted", "config/blacklists_new"): if os.path.isdir(d): rm_rf(d)
def remove_old_data (): print "remove old extracted data..." for d in ("extracted", "config/blacklists_new"): if os.path.isdir(d): rm_rf(d)
16,337
def remove_old_data (): print "remove old data..." for d in ("extracted", "config/blacklists_new"): if os.path.isdir(d): rm_rf(d)
def remove_old_data (): print "remove old data..." for d in ("extracted", "config/blacklists_new"): if os.path.isdir(d): rm_rf(d)
16,338
def process_headers (self): """read and filter client request headers""" # Two newlines ends headers i = self.recv_buffer.find('\r\n\r\n') if i < 0: return i += 4 # Skip over newline terminator # the first 2 chars are the newline of request fp = StringIO(self.read(i)[2:]) msg = WcMessage(fp) # put unparsed data (if any) back to the buffer msg.rewindbody() self.recv_buffer = fp.read() + self.recv_buffer fp.close() debug(PROXY, "%s client headers \n%s", self, msg) filters = [FILTER_REQUEST_HEADER, FILTER_REQUEST_DECODE, FILTER_REQUEST_MODIFY, FILTER_REQUEST_ENCODE, ] self.attrs['headers'] = msg self.set_persistent(msg, self.http_ver) self.mangle_request_headers(msg) self.compress = client_set_encoding_headers(msg) # filter headers self.headers = applyfilter(FILTER_REQUEST_HEADER, msg, "finish", self.attrs) # add decoders self.decoders = [] self.bytes_remaining = get_content_length(self.headers) # chunked encoded if self.headers.has_key('Transfer-Encoding'): # XXX don't look at value, assume chunked encoding for now debug(PROXY, '%s Transfer-encoding %r', self, self.headers['Transfer-encoding']) self.decoders.append(UnchunkStream()) client_remove_encoding_headers(self.headers) self.bytes_remaining = None if self.bytes_remaining is None: self.persistent = False if not self.hostname and self.headers.has_key('Host'): if self.method=='CONNECT': defaultport = 443 else: defaultport = 80 host = self.headers['Host'] self.hostname, self.port = splitnport(host, defaultport) if not self.hostname: error(PROXY, "%s missing hostname in request", self) self.error(400, i18n._("Bad Request")) # local request? if self.hostname in config['localhosts'] and self.port==config['port']: # this is a direct proxy call, jump directly to content self.state = 'content' return # add missing host headers for HTTP/1.1 if not self.headers.has_key('Host'): warn(PROXY, "%s request without Host header encountered", self) if self.port!=80: self.headers['Host'] = "%s:%d\r"%(self.hostname, self.port) else: self.headers['Host'] = "%s\r"%self.hostname if config["proxyuser"]: creds = get_header_credentials(self.headers, 'Proxy-Authorization') if not creds: auth = ", ".join(get_challenges()) self.error(407, i18n._("Proxy Authentication Required"), auth=auth) return if 'NTLM' in creds: if creds['NTLM'][0]['type']==NTLMSSP_NEGOTIATE: auth = ",".join(creds['NTLM'][0]) self.error(407, i18n._("Proxy Authentication Required"), auth=auth) return # XXX the data=None argument should hold POST data if not check_credentials(creds, username=config['proxyuser'], password_b64=config['proxypass'], uri=get_auth_uri(self.url), method=self.method, data=None): warn(AUTH, "Bad proxy authentication from %s", self.addr[0]) auth = ", ".join(get_challenges()) self.error(407, i18n._("Proxy Authentication Required"), auth=auth) return if self.method in ['OPTIONS', 'TRACE'] and \ client_get_max_forwards(self.headers)==0: # XXX display options ? self.state = 'done' ServerHandleDirectly(self, '%s 200 OK'%self.protocol, 200, WcMessage(StringIO('Content-Type: text/plain\r\n\r\n')), '') return self.state = 'content'
def process_headers (self): """read and filter client request headers""" # Two newlines ends headers i = self.recv_buffer.find('\r\n\r\n') if i < 0: return i += 4 # Skip over newline terminator # the first 2 chars are the newline of request fp = StringIO(self.read(i)[2:]) msg = WcMessage(fp) # put unparsed data (if any) back to the buffer msg.rewindbody() self.recv_buffer = fp.read() + self.recv_buffer fp.close() debug(PROXY, "%s client headers \n%s", self, msg) filters = [FILTER_REQUEST_HEADER, FILTER_REQUEST_DECODE, FILTER_REQUEST_MODIFY, FILTER_REQUEST_ENCODE, ] self.attrs['headers'] = msg self.set_persistent(msg, self.http_ver) self.mangle_request_headers(msg) self.compress = client_set_encoding_headers(msg) # filter headers self.headers = applyfilter(FILTER_REQUEST_HEADER, msg, "finish", self.attrs) # add decoders self.decoders = [] self.bytes_remaining = get_content_length(self.headers) # chunked encoded if self.headers.has_key('Transfer-Encoding'): # XXX don't look at value, assume chunked encoding for now debug(PROXY, '%s Transfer-encoding %r', self, self.headers['Transfer-encoding']) self.decoders.append(UnchunkStream()) client_remove_encoding_headers(self.headers) self.bytes_remaining = None if self.bytes_remaining is None: self.persistent = False if not self.hostname and self.headers.has_key('Host'): if self.method=='CONNECT': defaultport = 443 else: defaultport = 80 host = self.headers['Host'] self.hostname, self.port = splitnport(host, defaultport) if not self.hostname: error(PROXY, "%s missing hostname in request", self) self.error(400, i18n._("Bad Request")) # local request? if self.hostname in config['localhosts'] and self.port==config['port']: # this is a direct proxy call, jump directly to content self.state = 'content' return # add missing host headers for HTTP/1.1 if not self.headers.has_key('Host'): warn(PROXY, "%s request without Host header encountered", self) if self.port!=80: self.headers['Host'] = "%s:%d\r"%(self.hostname, self.port) else: self.headers['Host'] = "%s\r"%self.hostname if config["proxyuser"]: creds = get_header_credentials(self.headers, 'Proxy-Authorization') if not creds: auth = ", ".join(get_challenges()) self.error(407, i18n._("Proxy Authentication Required"), auth=auth) return if 'NTLM' in creds: if creds['NTLM'][0]['type']==NTLMSSP_NEGOTIATE: attrs = { 'host': creds['NTLM'][0]['host'], 'domain': creds['NTLM'][0]['domain'], 'type': NTLMSSP_CHALLENGE, } auth = ",".join(get_challenges(**attrs)) self.error(407, i18n._("Proxy Authentication Required"), auth=auth) return # XXX the data=None argument should hold POST data if not check_credentials(creds, username=config['proxyuser'], password_b64=config['proxypass'], uri=get_auth_uri(self.url), method=self.method, data=None): warn(AUTH, "Bad proxy authentication from %s", self.addr[0]) auth = ", ".join(get_challenges()) self.error(407, i18n._("Proxy Authentication Required"), auth=auth) return if self.method in ['OPTIONS', 'TRACE'] and \ client_get_max_forwards(self.headers)==0: # XXX display options ? self.state = 'done' ServerHandleDirectly(self, '%s 200 OK'%self.protocol, 200, WcMessage(StringIO('Content-Type: text/plain\r\n\r\n')), '') return self.state = 'content'
16,339
def check_url (self, url): if not wc.url.is_safe_url(url): raise RatingParseError("Invalid rating url %s." % repr(url))
def check_url (self, url): if not wc.url.is_safe_url(url): raise RatingParseError("Invalid rating url %s." % repr(url))
16,340
def __init__ (self, sid=None, titles=None, descriptions=None, disable=0, matchurls=None, nomatchurls=None): super(RatingRule, self).__init__(sid=sid, titles=titles, descriptions=descriptions, disable=disable, matchurls=matchurls, nomatchurls=nomatchurls) # list of RuleRating objects self.ratings = [] self.url = ""
def __init__ (self, sid=None, titles=None, descriptions=None, disable=0, matchurls=None, nomatchurls=None): super(RatingRule, self).__init__(sid=sid, titles=titles, descriptions=descriptions, disable=disable, matchurls=matchurls, nomatchurls=nomatchurls) # list of RuleRating objects self.ratings = {} for category in wc.filter.rating.categories: self.ratings[category.name] = None self.url = ""
16,341
def end_data (self, name): super(RatingRule, self).end_data(name) if name == 'category': assert self._category self.ratings.append((self._category, self._data)) pass elif name == 'url': self.url = self._data
def end_data (self, name): super(RatingRule, self).end_data(name) if name == 'category': assert self._category self.ratings[self._category] = self._data pass elif name == 'url': self.url = self._data
16,342
def recognize (self, buf, attrs): # note: recognizing a mime type fixes exploits like # CVE-2002-0025 and CVE-2002-0024 wc.log.debug(wc.LOG_FILTER, "MIME recognize %d bytes of data", buf.tell()) try: mime = wc.magic.classify(buf) wc.log.debug(wc.LOG_FILTER, "MIME recognized %r", mime) if mime is not None and not attrs['mime'].startswith(mime): wc.log.warn(wc.LOG_FILTER, "Adjusting MIME %r -> %r at %r", attrs['mime'], mime, attrs['url']) attrs['mime'] = mime attrs['headers']['data']['Content-Type'] = "%s\r" % mime except StandardError, msg: wc.log.exception(wc.LOG_FILTER, "Mime recognize error") data = buf.getvalue() buf.close() return data
def recognize (self, buf, attrs): # note: recognizing a mime type fixes exploits like # CVE-2002-0025 and CVE-2002-0024 wc.log.debug(wc.LOG_FILTER, "MIME recognize %d bytes of data", buf.tell()) try: mime = wc.magic.classify(buf) wc.log.debug(wc.LOG_FILTER, "MIME recognized %r", mime) origmime = attrs['mime'] if mime is not None and origmime is not None and \ not origmime.startswith(mime): wc.log.warn(wc.LOG_FILTER, "Adjusting MIME %r -> %r at %r", attrs['mime'], mime, attrs['url']) attrs['mime'] = mime attrs['headers']['data']['Content-Type'] = "%s\r" % mime except StandardError, msg: wc.log.exception(wc.LOG_FILTER, "Mime recognize error") data = buf.getvalue() buf.close() return data
16,343
def recognize (self, buf, attrs): # note: recognizing a mime type fixes exploits like # CVE-2002-0025 and CVE-2002-0024 wc.log.debug(wc.LOG_FILTER, "MIME recognize %d bytes of data", buf.tell()) try: mime = wc.magic.classify(buf) wc.log.debug(wc.LOG_FILTER, "MIME recognized %r", mime) if mime is not None and not attrs['mime'].startswith(mime): wc.log.warn(wc.LOG_FILTER, "Adjusting MIME %r -> %r at %r", attrs['mime'], mime, attrs['url']) attrs['mime'] = mime attrs['headers']['data']['Content-Type'] = "%s\r" % mime except StandardError, msg: wc.log.exception(wc.LOG_FILTER, "Mime recognize error") data = buf.getvalue() buf.close() return data
def recognize (self, buf, attrs): # note: recognizing a mime type fixes exploits like # CVE-2002-0025 and CVE-2002-0024 wc.log.debug(wc.LOG_FILTER, "MIME recognize %d bytes of data", buf.tell()) try: mime = wc.magic.classify(buf) wc.log.debug(wc.LOG_FILTER, "MIME recognized %r", mime) if mime is not None and not attrs['mime'].startswith(mime): wc.log.warn(wc.LOG_FILTER, "Adjusting MIME %r -> %r at %r", origmime, mime, attrs['url']) attrs['mime'] = mime attrs['headers']['data']['Content-Type'] = "%s\r" % mime except StandardError, msg: wc.log.exception(wc.LOG_FILTER, "Mime recognize error") data = buf.getvalue() buf.close() return data
16,344
def reset (self): """Reset to default values""" self['port'] = 8080 self['proxyuser'] = "" self['proxypass'] = "" self['parentproxy'] = "" self['parentproxyport'] = 3128 self['parentproxyuser'] = "" self['parentproxypass'] = "" self['logfile'] = "" self['strict_whitelist'] = 0 self['debuglevel'] = 0 self['rules'] = [] self['filters'] = [] self['filterlist'] = [[],[],[],[],[],[],[],[],[],[]] self['colorize'] = 0 self['noproxyfor'] = [{}, [], {}] self['allowedhosts'] = [{}, [], {}] self['starttime'] = time.time() self['requests'] = {'valid':0, 'error':0, 'blocked':0} self['local_sockets_only'] = 0 self['localip'] = socket.gethostbyname(socket.gethostname()) self['mime_content_rewriting'] = [] self['headersave'] = 100 self['showerrors'] = None
def reset (self): """Reset to default values""" self['port'] = 8080 self['proxyuser'] = "" self['proxypass'] = "" self['parentproxy'] = "" self['parentproxyport'] = 3128 self['parentproxyuser'] = "" self['parentproxypass'] = "" self['logfile'] = "" self['strict_whitelist'] = 0 self['debuglevel'] = 0 self['rules'] = [] self['filters'] = [] self['filterlist'] = [[],[],[],[],[],[],[],[],[],[]] self['colorize'] = 0 self['noproxyfor'] = None self['allowedhosts'] = None self['starttime'] = time.time() self['requests'] = {'valid':0, 'error':0, 'blocked':0} self['local_sockets_only'] = 0 self['localip'] = socket.gethostbyname(socket.gethostname()) self['mime_content_rewriting'] = [] self['headersave'] = 100 self['showerrors'] = None
16,345
def start_element (self, name, attrs): if name=='webcleaner': for key,val in attrs.items(): self.config[str(key)] = unxmlify(val) for key in ('port','parentproxyport', 'debuglevel','colorize','showerrors', 'strict_whitelist'): self.config[key] = int(self.config[key]) for key in ('version', 'parentproxy', 'logfile', 'proxyuser', 'proxypass', 'parentproxyuser', 'parentproxypass', ): if self.config[key] is not None: self.config[key] = str(self.config[key]) if self.config['noproxyfor']: strhosts = str(self.config['noproxyfor']) self.config['noproxyfor'] = host_set(strhosts) if self.config['allowedhosts']: strhosts = str(self.config['allowedhosts']) self.config['allowedhosts'] = host_set(strhosts) if self.config['logfile'] == '<stdout>': self.config['logfile'] = sys.stdout elif self.config['logfile']: self.config['logfile'] = open(self.config['logfile'], 'a') elif name=='filter': debug(BRING_IT_ON, "enable filter module %s" % attrs['name']) self.config['filters'].append(attrs['name'])
def start_element (self, name, attrs): if name=='webcleaner': for key,val in attrs.items(): self.config[str(key)] = unxmlify(val) for key in ('port','parentproxyport', 'debuglevel','colorize','showerrors', 'strict_whitelist'): self.config[key] = int(self.config[key]) for key in ('version', 'parentproxy', 'logfile', 'proxyuser', 'proxypass', 'parentproxyuser', 'parentproxypass', ): if self.config[key] is not None: self.config[key] = str(self.config[key]) if self.config['noproxyfor'] is not None: strhosts = str(self.config['noproxyfor']) self.config['noproxyfor'] = host_set(strhosts) if self.config['allowedhosts']: strhosts = str(self.config['allowedhosts']) self.config['allowedhosts'] = host_set(strhosts) if self.config['logfile'] == '<stdout>': self.config['logfile'] = sys.stdout elif self.config['logfile']: self.config['logfile'] = open(self.config['logfile'], 'a') elif name=='filter': debug(BRING_IT_ON, "enable filter module %s" % attrs['name']) self.config['filters'].append(attrs['name'])
16,346
def start_element (self, name, attrs): if name=='webcleaner': for key,val in attrs.items(): self.config[str(key)] = unxmlify(val) for key in ('port','parentproxyport', 'debuglevel','colorize','showerrors', 'strict_whitelist'): self.config[key] = int(self.config[key]) for key in ('version', 'parentproxy', 'logfile', 'proxyuser', 'proxypass', 'parentproxyuser', 'parentproxypass', ): if self.config[key] is not None: self.config[key] = str(self.config[key]) if self.config['noproxyfor']: strhosts = str(self.config['noproxyfor']) self.config['noproxyfor'] = host_set(strhosts) if self.config['allowedhosts']: strhosts = str(self.config['allowedhosts']) self.config['allowedhosts'] = host_set(strhosts) if self.config['logfile'] == '<stdout>': self.config['logfile'] = sys.stdout elif self.config['logfile']: self.config['logfile'] = open(self.config['logfile'], 'a') elif name=='filter': debug(BRING_IT_ON, "enable filter module %s" % attrs['name']) self.config['filters'].append(attrs['name'])
def start_element (self, name, attrs): if name=='webcleaner': for key,val in attrs.items(): self.config[str(key)] = unxmlify(val) for key in ('port','parentproxyport', 'debuglevel','colorize','showerrors', 'strict_whitelist'): self.config[key] = int(self.config[key]) for key in ('version', 'parentproxy', 'logfile', 'proxyuser', 'proxypass', 'parentproxyuser', 'parentproxypass', ): if self.config[key] is not None: self.config[key] = str(self.config[key]) if self.config['noproxyfor']: strhosts = str(self.config['noproxyfor']) self.config['noproxyfor'] = host_set(strhosts) else: self.config['noproxyfor'] = [{}, [], {}] if self.config['allowedhosts'] is not None: strhosts = str(self.config['allowedhosts']) self.config['allowedhosts'] = host_set(strhosts) if self.config['logfile'] == '<stdout>': self.config['logfile'] = sys.stdout elif self.config['logfile']: self.config['logfile'] = open(self.config['logfile'], 'a') elif name=='filter': debug(BRING_IT_ON, "enable filter module %s" % attrs['name']) self.config['filters'].append(attrs['name'])
16,347
def filter (self, data, **attrs): if not attrs.has_key('buffer') or attrs['buffer'].closed: # we do not block this image # or we do not have enough buffer data yet return data buf = attrs['buffer'] buf.write(data) if buf.tell() > self.min_bufsize: if self.check_sizes(buf, attrs['sizes']): # size is ok data = buf.getvalue() buf.close() return data return ''
def filter (self, data, **attrs): if not attrs.has_key('buffer') or attrs['buffer'].closed: # we do not block this image # or we do not have enough buffer data yet return data buf = attrs['buffer'] buf.write(data) if buf.tell() > self.min_bufsize: if self.check_sizes(buf, attrs['sizes']): # size is ok data = buf.getvalue() buf.close() return data return ''
16,348
def filter (self, data, **attrs): if not attrs.has_key('buffer') or attrs['buffer'].closed: # we do not block this image # or we do not have enough buffer data yet return data buf = attrs['buffer'] buf.write(data) if buf.tell() > self.min_bufsize: if self.check_sizes(buf, attrs['sizes']): # size is ok data = buf.getvalue() buf.close() return data return ''
def filter (self, data, **attrs): if not attrs.has_key('buffer') or attrs['buffer'].closed: # we do not block this image # or we do not have enough buffer data yet return data buf = attrs['buffer'] buf.write(data) if buf.tell() > self.min_bufsize: if self.check_sizes(buf, attrs['sizes']): # size is ok data = buf.getvalue() buf.close() return data return ''
16,349
def finish (self, data, **attrs): if not attrs.has_key('buffer') or attrs['buffer'].closed: # we do not block this image return data buf = attrs['buffer'] buf.write(data) if self.check_sizes(buf, attrs['sizes']): # size is ok data = buf.getvalue() buf.close() return data return ''
def finish (self, data, **attrs): if not attrs.has_key('buffer') or attrs['buffer'].closed: # we do not block this image return data buf = attrs['buffer'] buf.write(data) if self.check_sizes(buf, attrs['sizes']): # size is ok data = buf.getvalue() buf.close() return data return ''
16,350
def finish (self, data, **attrs): if not attrs.has_key('buffer') or attrs['buffer'].closed: # we do not block this image return data buf = attrs['buffer'] buf.write(data) if self.check_sizes(buf, attrs['sizes']): # size is ok data = buf.getvalue() buf.close() return data return ''
def finish (self, data, **attrs): if not attrs.has_key('buffer') or attrs['buffer'].closed: # we do not block this image return data buf = attrs['buffer'] buf.write(data) if self.check_sizes(buf, attrs['sizes']): # size is ok data = buf.getvalue() buf.close() return data return ''
16,351
def check_sizes (self, buf, sizes): try: buf.seek(0) img = Image.open(buf, 'r') for size, formats in sizes: if size==img.size: # size matches, look for format restriction if not formats: return False elif img.format.lower() in formats: return False except IOError: exception(FILTER, "Could not get image size") return True
def check_sizes (self, buf, sizes, url): try: buf.seek(0) img = Image.open(buf, 'r') for size, formats in sizes: if size==img.size: # size matches, look for format restriction if not formats: return False elif img.format.lower() in formats: return False except IOError: exception(FILTER, "Could not get image size") return True
16,352
def check_sizes (self, buf, sizes): try: buf.seek(0) img = Image.open(buf, 'r') for size, formats in sizes: if size==img.size: # size matches, look for format restriction if not formats: return False elif img.format.lower() in formats: return False except IOError: exception(FILTER, "Could not get image size") return True
def check_sizes (self, buf, sizes): try: buf.seek(0) img = Image.open(buf, 'r') for size, formats in sizes: if size==img.size: # size matches, look for format restriction if not formats: return False elif img.format.lower() in formats: return False except IOError: exception(FILTER, "Could not get image size from %s", url) return True
16,353
def convert_adzapper_replace (replace): # replace Perl back references with Python ones replace = re.sub(r"\$(\d)", r"\\1", replace) return replace
def convert_adzapper_replace (replace): # replace Perl back references with Python ones replace = re.sub(r"\${?(\d)}?", r"\\\1", replace) return replace
16,354
def check_connect (self, addr): """ Check if the connection is etablished. See also http://cr.yp.to/docs/connect.html and connect(2) manpage. """ wc.log.debug(wc.LOG_PROXY, '%s check connect', self) self.connect_checks += 1 if self.connect_checks >= 50: wc.log.info(wc.LOG_PROXY, '%s connect timed out', self) self.handle_close() return try: (r, w, e) = select.select([], [self.fileno()], [], 0.2) except select.error, why: # not yet ready wc.log.debug(wc.LOG_PROXY, '%s connect error %s', self, str(why)) wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) return if self.fileno() not in w: # not yet ready wc.log.debug(wc.LOG_PROXY, '%s not writable', self) wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) return err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err == 0: self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() elif err in (errno.EINPROGRESS, errno.EWOULDBLOCK): wc.log.debug(wc.LOG_PROXY, '%s connect status in progress/would block', self) wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) else: strerr = errno.errorcode[err] wc.log.info(wc.LOG_PROXY, '%s connect error %s', self, strerr) self.handle_close()
def check_connect (self, addr): """ Check if the connection is etablished. See also http://cr.yp.to/docs/connect.html and connect(2) manpage. """ wc.log.debug(wc.LOG_PROXY, '%s check connect', self) self.connect_checks += 1 if self.connect_checks >= 50: wc.log.debug(wc.LOG_PROXY, '%s connect timed out', self) self.handle_close() return try: (r, w, e) = select.select([], [self.fileno()], [], 0.2) except select.error, why: # not yet ready wc.log.debug(wc.LOG_PROXY, '%s connect error %s', self, str(why)) wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) return if self.fileno() not in w: # not yet ready wc.log.debug(wc.LOG_PROXY, '%s not writable', self) wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) return err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err == 0: self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() elif err in (errno.EINPROGRESS, errno.EWOULDBLOCK): wc.log.debug(wc.LOG_PROXY, '%s connect status in progress/would block', self) wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) else: strerr = errno.errorcode[err] wc.log.info(wc.LOG_PROXY, '%s connect error %s', self, strerr) self.handle_close()
16,355
def onCmdProxyStart (self, sender, sel, ptr): os.system('invoke-rc.d webcleaner start') debug(GUI, "webcleaner start") return 1
def onCmdProxyStart (self, sender, sel, ptr): from wc import daemon daemon.start(parent_exit=0) debug(GUI, "webcleaner start") return 1
16,356
def onCmdProxyStop (self, sender, sel, ptr): os.system('invoke-rc.d webcleaner stop') debug(GUI, "webcleaner stop") return 1
def onCmdProxyStop (self, sender, sel, ptr): from wc import daemon daemon.stop() debug(GUI, "webcleaner stop") return 1
16,357
def onCmdProxyRestart (self, sender, sel, ptr): os.system('invoke-rc.d webcleaner restart') debug(GUI, "webcleaner restart") return 1
def onCmdProxyRestart (self, sender, sel, ptr): from wc import daemon daemon.restart(parent_exit=0) debug(GUI, "webcleaner restart") return 1
16,358
def onCmdProxyReload (self, sender, sel, ptr): os.system('invoke-rc.d webcleaner reload') debug(GUI, "webcleaner reload") return 1
def onCmdProxyReload (self, sender, sel, ptr): from wc import daemon daemon.reload() debug(GUI, "webcleaner reload") return 1
16,359
def test_rating_range (self): """ Test range parsing. """ # rating_range (range) rating_range = wc.filter.rating.category.intrange_from_string self.assertEqual(rating_range(""), (None, None)) self.assertEqual(rating_range("-"), (None, None)) self.assertEqual(rating_range("1"), (1, None)) self.assertEqual(rating_range("1-"), (1, None)) self.assertEqual(rating_range("-1"), (None, 1)) self.assertEqual(rating_range("1-1"), (1, 1)) self.assertEqual(rating_range("1"), None) self.assertEqual(rating_range("-1-"), None)
def test_rating_range (self): """ Test range parsing. """ # rating_range (range) rating_range = wc.filter.rating.category.intrange_from_string self.assertEqual(rating_range(""), (None, None)) self.assertEqual(rating_range("-"), (None, None)) self.assertEqual(rating_range("1"), (1, None)) self.assertEqual(rating_range("1-"), (1, None)) self.assertEqual(rating_range("-1"), (None, 1)) self.assertEqual(rating_range("1-1"), (1, 1)) self.assertEqual(rating_range("-1-"), None)
16,360
def __init__ (self, url, opts): # True if javascript has to be filtered self.javascript = opts['javascript'] self.level = opts.get('level', 0) self.comments = opts['comments'] self.url = url or "unknown" self.js_src = False self.js_script = '' # HttpProxyClient object used in background downloads, # has self.jsScriptData as handler self.js_client = None # gets set by parent parser self.htmlparser = None # HtmlParser used in background downloads self.js_htmlparser = None if self.javascript: self.js_env = wc.js.jslib.JSEnv() #self.js_env.setBrowser(opts['browser']) self.js_output = 0 self.js_popup = 0
def __init__ (self, url, opts): # True if javascript has to be filtered self.javascript = opts['javascript'] self.level = opts.get('level', 0) self.comments = opts['comments'] self.url = url or "unknown" self.js_src = False self.js_script = u'' # HttpProxyClient object used in background downloads, # has self.jsScriptData as handler self.js_client = None # gets set by parent parser self.htmlparser = None # HtmlParser used in background downloads self.js_htmlparser = None if self.javascript: self.js_env = wc.js.jslib.JSEnv() #self.js_env.setBrowser(opts['browser']) self.js_output = 0 self.js_popup = 0
16,361
def js_end_script (self, item): """</script> was encountered""" wc.log.debug(wc.LOG_JS, "%s js_end_script %s", self, item) self.htmlparser.debugbuf(wc.LOG_JS) if len(self.htmlparser.tagbuf) < 2: assert False, "parser %s must have script start and content " \ "tags in tag buffer" % self.htmlparser if self.js_output: try: self.js_htmlparser.feed('') self.js_htmlparser.flush() except wc.filter.FilterWait: wc.log.debug(wc.LOG_JS, "%s JS subprocessor is waiting", self) self.htmlparser.state = ('wait', 'recursive script') self.htmlparser.waited = 1 wc.proxy.make_timer(1, lambda: self.js_end_script(item)) return self.js_htmlparser.debugbuf(wc.LOG_JS) assert not self.js_htmlparser.inbuf.getvalue() assert not self.js_htmlparser.waitbuf assert len(self.htmlparser.tagbuf) >= 2, \ "too small buffer %s" % self.htmlparser.tagbuf data = self.js_htmlparser.getoutput() self.htmlparser.tagbuf[-2:-2] = \ [[wc.filter.rules.RewriteRule.DATA, data]]+self.js_htmlparser.tagbuf self.htmlparser.debugbuf(wc.LOG_JS) self.js_htmlparser = None if self.js_popup or self.js_output: # either the javascript part popped up some windows or # it wrote something with document.write() # in both cases the javascript is deleted # This could potentially delete too much as there might be # valid JS functions defined that get used by other scripts. # In this case use an exception url in the Javascript filter # rule. del self.htmlparser.tagbuf[-1] del self.htmlparser.tagbuf[-1] elif not self.filter_end_element(item[1]): self.htmlparser.tagbuf.append(item) self.htmlparser.state = ('parse',) wc.log.debug(wc.LOG_JS, "%s switching back to parse with", self) self.htmlparser.debugbuf(wc.LOG_JS)
def js_end_script (self, item): """</script> was encountered""" wc.log.debug(wc.LOG_JS, "%s js_end_script %s", self, item) self.htmlparser.debugbuf(wc.LOG_JS) if len(self.htmlparser.tagbuf) < 2: assert False, "parser %s must have script start and content " \ "tags in tag buffer" % self.htmlparser if self.js_output: try: self.js_htmlparser.feed('') self.js_htmlparser.flush() except wc.filter.FilterWait: wc.log.debug(wc.LOG_JS, "%s JS subprocessor is waiting", self) self.htmlparser.state = ('wait', 'recursive script') self.htmlparser.waited = 1 wc.proxy.make_timer(1, lambda: self.js_end_script(item)) return self.js_htmlparser.debugbuf(wc.LOG_JS) assert not self.js_htmlparser.inbuf.getvalue() assert not self.js_htmlparser.waitbuf assert len(self.htmlparser.tagbuf) >= 2, \ "too small buffer %s" % self.htmlparser.tagbuf data = unicode(self.js_htmlparser.getoutput()) self.htmlparser.tagbuf[-2:-2] = \ [[wc.filter.rules.RewriteRule.DATA, data]]+self.js_htmlparser.tagbuf self.htmlparser.debugbuf(wc.LOG_JS) self.js_htmlparser = None if self.js_popup or self.js_output: # either the javascript part popped up some windows or # it wrote something with document.write() # in both cases the javascript is deleted # This could potentially delete too much as there might be # valid JS functions defined that get used by other scripts. # In this case use an exception url in the Javascript filter # rule. del self.htmlparser.tagbuf[-1] del self.htmlparser.tagbuf[-1] elif not self.filter_end_element(item[1]): self.htmlparser.tagbuf.append(item) self.htmlparser.state = ('parse',) wc.log.debug(wc.LOG_JS, "%s switching back to parse with", self) self.htmlparser.debugbuf(wc.LOG_JS)
16,362
def js_end_element (self, item): """parse generated html for scripts""" wc.log.debug(wc.LOG_JS, "%s js_end_element buf %r", self, self.htmlparser.tagbuf) if len(self.htmlparser.tagbuf)<2: # syntax error, ignore wc.log.warn(wc.LOG_JS, "JS syntax error, self.tagbuf %r", self.htmlparser.tagbuf) return if self.js_src: wc.log.debug(wc.LOG_JS, "JS src, self.tagbuf %r", self.htmlparser.tagbuf) del self.htmlparser.tagbuf[-1] if len(self.htmlparser.tagbuf)<2: # syntax error, ignore wc.log.warn(wc.LOG_JS, "JS end, self.tagbuf %s", self.htmlparser.tagbuf) return if len(self.htmlparser.tagbuf) > 2 and \ self.htmlparser.tagbuf[-3][0] == \ wc.filter.rules.RewriteRule.STARTTAG and \ self.htmlparser.tagbuf[-3][1] == 'script': del self.htmlparser.tagbuf[-1] if len(self.htmlparser.tagbuf)<2 or \ self.htmlparser.tagbuf[-1][0] != \ wc.filter.rules.RewriteRule.DATA or \ self.htmlparser.tagbuf[-2][0] != \ wc.filter.rules.RewriteRule.STARTTAG or \ self.htmlparser.tagbuf[-2][1] != 'script': # syntax error, ignore return js_ok, js_lang = wc.js.get_js_data(self.htmlparser.tagbuf[-2][2]) if not js_ok: # no JavaScript, add end tag and ignore self.htmlparser.tagbuf.append(item) return ver = wc.js.get_js_ver(js_lang) # get script data script = self.htmlparser.tagbuf[-1][1].strip() # remove html comments script = wc.js.remove_html_comments(script) if not script: # again, ignore an empty script del self.htmlparser.tagbuf[-1] del self.htmlparser.tagbuf[-1] return # put correctly quoted script data into buffer self.htmlparser.tagbuf[-1][1] = \ "\n<!--\n%s\n//-->\n" % wc.js.escape_js(script) # execute script self.jsScript(script, ver, item)
def js_end_element (self, item): """parse generated html for scripts""" wc.log.debug(wc.LOG_JS, "%s js_end_element buf %r", self, self.htmlparser.tagbuf) if len(self.htmlparser.tagbuf)<2: # syntax error, ignore wc.log.warn(wc.LOG_JS, "JS syntax error, self.tagbuf %r", self.htmlparser.tagbuf) return if self.js_src: wc.log.debug(wc.LOG_JS, "JS src, self.tagbuf %r", self.htmlparser.tagbuf) del self.htmlparser.tagbuf[-1] if len(self.htmlparser.tagbuf)<2: # syntax error, ignore wc.log.warn(wc.LOG_JS, "JS end, self.tagbuf %s", self.htmlparser.tagbuf) return if len(self.htmlparser.tagbuf) > 2 and \ self.htmlparser.tagbuf[-3][0] == \ wc.filter.rules.RewriteRule.STARTTAG and \ self.htmlparser.tagbuf[-3][1] == 'script': del self.htmlparser.tagbuf[-1] if len(self.htmlparser.tagbuf)<2 or \ self.htmlparser.tagbuf[-1][0] != \ wc.filter.rules.RewriteRule.DATA or \ self.htmlparser.tagbuf[-2][0] != \ wc.filter.rules.RewriteRule.STARTTAG or \ self.htmlparser.tagbuf[-2][1] != 'script': # syntax error, ignore return js_ok, js_lang = wc.js.get_js_data(self.htmlparser.tagbuf[-2][2]) if not js_ok: # no JavaScript, add end tag and ignore self.htmlparser.tagbuf.append(item) return ver = wc.js.get_js_ver(js_lang) # get script data script = self.htmlparser.tagbuf[-1][1].strip() # remove html comments script = wc.js.remove_html_comments(script) if not script: # again, ignore an empty script del self.htmlparser.tagbuf[-1] del self.htmlparser.tagbuf[-1] return # put correctly quoted script data into buffer self.htmlparser.tagbuf[-1][1] = \ u"\n<!--\n%s\n//-->\n" % wc.js.escape_js(script) # execute script self.jsScript(script, ver, item)
16,363
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.LOG_JS, "empty JavaScript src %s", url) self.js_script = u"// "+\ _("error fetching script from %r") % url self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.STARTTAG, "script", {'type': 'text/javascript'}]) # norm html comments script = wc.js.remove_html_comments(self.js_script) script = u"\n<!--\n%s\n//-->\n" % wc.js.escape_js(script) self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.ENDTAG, "script"]) self.js_script = u'' self.htmlparser.state = ('parse',) wc.log.debug(wc.LOG_JS, "%s switching back to parse with", self) self.htmlparser.debugbuf(wc.LOG_JS) else: wc.log.debug(wc.LOG_JS, "JS read %d <= %s", len(data), url) self.js_script += data
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.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.LOG_JS, "empty JavaScript src %s", url) self.js_script = u"// "+\ _("error fetching script from %r") % url self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.STARTTAG, "script", {'type': 'text/javascript'}]) # norm html comments script = wc.js.remove_html_comments(self.js_script) script = u"\n<!--\n%s\n//-->\n" % wc.js.escape_js(script) self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.ENDTAG, u"script"]) self.js_script = u'' self.htmlparser.state = ('parse',) wc.log.debug(wc.LOG_JS, "%s switching back to parse with", self) self.htmlparser.debugbuf(wc.LOG_JS) else: wc.log.debug(wc.LOG_JS, "JS read %d <= %s", len(data), url) self.js_script += data
16,364
def set_unreadable (self, secs): self.connected = False make_timer(secs, self.set_readable)
def set_unreadable (self, secs): self.connected = False make_timer(secs, self.set_readable)
16,365
def get_line_number (s, index): """ Return the line number of s[index]. Lines are assumed to be separated by the ASCII character '\\n'. """ i = 0 if index < 0: index = 0 line = 1 while i < index: if s[i] == '\n': line += 1 i += 1 return line
def get_line_number (s, index): r""" Return the line number of s[index] or zero on errors. Lines are assumed to be separated by the ASCII character '\n'. """ i = 0 if index < 0: index = 0 line = 1 while i < index: if s[i] == '\n': line += 1 i += 1 return line
16,366
def get_line_number (s, index): """ Return the line number of s[index]. Lines are assumed to be separated by the ASCII character '\\n'. """ i = 0 if index < 0: index = 0 line = 1 while i < index: if s[i] == '\n': line += 1 i += 1 return line
def get_line_number (s, index): """ Return the line number of s[index]. Lines are assumed to be separated by the ASCII character '\\n'. """ i = 0 if index < 0: return 0 line = 1 while i < index: if s[i] == '\n': line += 1 i += 1 return line
16,367
def strsize (b): """ Return human representation of bytes b. A negative number of bytes raises a value error. """ if b < 0: raise ValueError("Invalid negative byte number") if b == 1: return u"%d Byte" % b if b < 1024: return u"%d Bytes" % b b /= 1024.0 if b < 1024: return u"%.2f kB" % b b /= 1024.0 if b < 1024: return u"%.2f MB" % b b /= 1024.0 return u"%.2f GB"
def strsize (b): """ Return human representation of bytes b. A negative number of bytes raises a value error. """ if b < 0: raise ValueError("Invalid negative byte number") if b == 1: return u"%d Byte" % b if b < 1024: return u"%d Bytes" % b b /= 1024.0 if b < 1024: return u"%.2f kB" % b b /= 1024.0 if b < 1024: return u"%.2f MB" % b b /= 1024.0 return u"%.2f GB" % b
16,368
def strduration (duration): """ Return translated and formatted time duration. """ name = _("seconds") if duration > 60: duration = duration / 60 name = _("minutes") if duration > 60: duration = duration / 60 name = _("hours") return u" %.3f %s" % (duration, name)
def strduration (duration): """ Return translated and formatted time duration. """ name = _("seconds") if duration >= 60: duration /= 60 name = _("minutes") if duration >= 60: duration /= 60 name = _("hours") return u" %.3f %s" % (duration, name)
16,369
def strduration (duration): """ Return translated and formatted time duration. """ name = _("seconds") if duration > 60: duration = duration / 60 name = _("minutes") if duration > 60: duration = duration / 60 name = _("hours") return u" %.3f %s" % (duration, name)
def strduration (duration): """ Return translated and formatted time duration. """ name = _("seconds") if duration >= 60: duration /= 60 name = _("minutes") if duration >= 60: duration /= 60 name = _("hours") return u" %.3f %s" % (duration, name)
16,370
def strduration (duration): """ Return translated and formatted time duration. """ name = _("seconds") if duration > 60: duration = duration / 60 name = _("minutes") if duration > 60: duration = duration / 60 name = _("hours") return u" %.3f %s" % (duration, name)
def strduration (duration): """ Return translated and formatted time duration. """ name = _("seconds") if duration > 60: duration = duration / 60 name = _("minutes") if duration > 60: duration = duration / 60 name = _("hours") return u"%.3f %s" % (duration, name)
16,371
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")
defdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() rundef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() (self):def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() ifdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() (sys.platformdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() !=def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() "win32"def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() anddef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() notdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() win_cross_compilingdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() anddef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() (self.distribution.has_ext_modules()def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() ordef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() self.distribution.has_c_libraries())):def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() raisedef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() DistutilsPlatformErrordef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() \def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() ("distributiondef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() containsdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() extensionsdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() and/ordef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() Cdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() libraries;def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() "def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() "mustdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() bedef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() compileddef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() ondef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() adef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() Windowsdef get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() 32def get_exe_bytes (self): if win_cross_compiling: bv = "7.1" directory = os.path.dirname(distutils.command.__file__) filename = os.path.join(directory, "wininst-%s.exe" % bv) return open(filename, "rb").read() return super(MyBdistWininst, self).get_exe_bytes() platform")
16,372
def run (self): if (sys.platform != "win32" and not win_cross_compiling and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform")
def run (self): if (sys.platform != "win32" and not win_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")
16,373
def check_pics (rule, labellist): """parse and check pics labels according to given PicsRule return None if no rating is exceeded return non-empty match message if some rating exceeds the configured rating level """ last = 0 for mo in ratings(labellist): rating = mo.group('rating') debug(NIGHTMARE, "PICS rating", rating) # the blurb contains the service name and options blurb = labellist[last:mo.start()].lower() debug(NIGHTMARE, "PICS blurb", blurb) last = mo.end() for service, sdata in services.items(): if service in blurb: msg = check_service(rating, sdata['categories'], sdata['name'], rule.options[service]) if msg: return msg return None
def check_pics (rule, labellist): """parse and check pics labels according to given PicsRule return None if no rating is exceeded return non-empty match message if some rating exceeds the configured rating level """ last = 0 for mo in ratings(labellist): rating = mo.group('rating') debug(NIGHTMARE, "PICS rating", rating) # the blurb contains the service name and options blurb = labellist[last:mo.start()].lower() debug(NIGHTMARE, "PICS blurb", blurb) last = mo.end() for service, sdata in services.items(): if blurb.find(service) != -1: msg = check_service(rating, sdata['categories'], sdata['name'], rule.options[service]) if msg: return msg return None
16,374
def check_pics (rule, labellist): """parse and check pics labels according to given PicsRule return None if no rating is exceeded return non-empty match message if some rating exceeds the configured rating level """ last = 0 for mo in ratings(labellist): rating = mo.group('rating') debug(NIGHTMARE, "PICS rating", rating) # the blurb contains the service name and options blurb = labellist[last:mo.start()].lower() debug(NIGHTMARE, "PICS blurb", blurb) last = mo.end() for service, sdata in services.items(): if service in blurb: msg = check_service(rating, sdata['categories'], sdata['name'], rule.options[service]) if msg: return msg return None
def check_pics (rule, labellist): """parse and check pics labels according to given PicsRule return None if no rating is exceeded return non-empty match message if some rating exceeds the configured rating level """ last = 0 for mo in ratings(labellist): rating = mo.group('rating') debug(NIGHTMARE, "PICS rating", rating) # the blurb contains the service name and options blurb = labellist[last:mo.start()].lower() debug(NIGHTMARE, "PICS blurb", blurb) last = mo.end() for service, sdata in services.items(): if service in blurb: msg = check_service(rating, sdata['categories'], sdata['name'], rule.ratings[service]) if msg: return msg return None
16,375
def check_service (rating, categories, name, options): """find given categories in rating and compare the according option value with the rating value. If one of the ratings exceed its option value, return a non-empty message, else return None. """ for category, value in options: category_label = categories[category] msg = check_pics_option(rating, category_label, value, "%s %s" % (name, category)); if msg: return msg return None
def check_service (rating, categories, name, options): """find given categories in rating and compare the according option value with the rating value. If one of the ratings exceed its option value, return a non-empty message, else return None. """ for category, value in options.items(): category_label = categories[category] msg = check_pics_option(rating, category_label, value, "%s %s" % (name, category)); if msg: return msg return None
16,376
def check_pics_option (rating, category_label, option, category) { """find the given label in rating and compare the value with option. If the rating exceeds the option, a non-empty message is returned, else None""" mo = re.search(r'%s\s+(?P<val>\d+)'%category_label, rating) if not mo: # label not found return None # get the rating value rating = int(mo.group("val")) if rating > option: return i18n._("PICS %s match") % category return None
def check_pics_option (rating, category_label, option, category): """find the given label in rating and compare the value with option. If the rating exceeds the option, a non-empty message is returned, else None""" mo = re.search(r'%s\s+(?P<val>\d+)'%category_label, rating) if not mo: # label not found return None # get the rating value rating = int(mo.group("val")) if rating > option: return i18n._("PICS %s match") % category return None
16,377
def p (path): """norm a path name to platform specific notation""" return os.path.normpath(path)
def p (path): """norm a path name to platform specific notation""" return os.path.normpath(path)
16,378
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 val = getattr(self, attr)[len(self.root):] else: val = getattr(self, attr) if attr=="install_data": base = os.path.join(val, 'share', 'webcleaner') data.append('config_dir = %r' % \ os.path.normcase(os.path.join(base, 'config'))) data.append('template_dir = %r' % \ os.path.normcase(os.path.join(base, 'templates'))) data.append("%s = %r" % (attr, val)) from pprint import pformat data.append('outputs = %s' % pformat(self.get_outputs())) self.distribution.create_conf_file(self.install_lib, data) # install proxy service if os.name=="nt": self.install_nt_service()
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 val = getattr(self, attr)[len(self.root):] else: val = getattr(self, attr) if attr=="install_data": base = os.path.join(val, 'share', 'webcleaner') data.append('config_dir = %r' % \ os.path.normcase(os.path.join(base, 'config'))) data.append('template_dir = %r' % \ os.path.normcase(os.path.join(base, 'templates'))) data.append("%s = %r" % (attr, val)) from pprint import pformat data.append('outputs = %s' % pformat(self.get_outputs())) self.distribution.create_conf_file(self.install_lib, data) # install proxy service if os.name=="nt": self.install_nt_service()
16,379
def create_batch_file (self, directory, data, filename): filename = os.path.join(directory, filename) # write the batch file util.execute(write_file, (filename, data), "creating %s" % filename, self.verbose>=1, self.dry_run)
def create_batch_file (self, directory, data, filename): filename = os.path.join(directory, filename) # write the batch file util.execute(write_file, (filename, data), "creating %s" % filename, self.verbose>=1, self.dry_run)
16,380
def testUnchunk (self): unchunker = wc.proxy.decoder.UnchunkStream.UnchunkStream() data = "a"*0x30 s = "000000000030\r\n%s\r\n0\r\n\r\n" % data self.assertEqual(data, unchunker.decode(s))
def testUnchunk (self): unchunker = wc.proxy.decoder.UnchunkStream.UnchunkStream() data = "a"*0x30 s = "000000000030\r\n%s\r\n0\r\n\r\n" % data self.assertEqual(data, unchunker.decode(s))
16,381
def _form_delete (): global url if _rating_delete(url): info['ratingdeleted'] = True else: error['ratingdeleted'] = True
def _form_delete (): global url try: del rating_store[url] rating_store.write() info['ratingdeleted'] = True else: error['ratingdeleted'] = True
16,382
def _form_delete (): global url if _rating_delete(url): info['ratingdeleted'] = True else: error['ratingdeleted'] = True
def _form_delete (): global url if _rating_delete(url): info['ratingdeleted'] = True except: error['ratingdeleted'] = True
16,383
def _form_generic (form): """Check generic validity""" global generic generic = form.has_key('generic'): return True
def _form_generic (form): """Check generic validity""" global generic generic = form.has_key('generic') return True
16,384
def __init__ (self, key, sub_key): self._key = _winreg.OpenKey(key, sub_key) self.closed = False
def __init__ (self, key, sub_key): self._key = OpenKey(key, sub_key) self.closed = False
16,385
def __getitem__ (self, key): if type(key) != StringType: raise TypeError, "key type must be string" try: val = _winreg.QueryValueEx(self._key, key) except WindowsError: raise IndexError, "subkey %s not found"%key return val[0]
def __getitem__ (self, key): if type(key) != StringType: raise TypeError, "key type must be string" try: val = QueryValueEx(self._key, key) except WindowsError: raise IndexError, "subkey %s not found"%key return val[0]
16,386
def subkeys (self): """get the list of subkeys as key_handle objects""" i = 0 keys = [] while 1: try: #print repr(EnumKey(self._key, i)) keys.append(key_handle(self._key, _winreg.EnumKey(self._key, i))) except EnvironmentError: break i += 1 return keys
def subkeys (self): """get the list of subkeys as key_handle objects""" i = 0 keys = [] while 1: try: #print repr(EnumKey(self._key, i)) keys.append(key_handle(self._key, EnumKey(self._key, i))) except EnvironmentError: break i += 1 return keys
16,387
def __len__ (self): return _winreg.QueryInfoKey(self._key)[0]
def __len__ (self): return _winreg.QueryInfoKey(self._key)[0]
16,388
def __setitem__ (self, key, value): """Set a registry key value. key is the key name, value is a tuple (type, val). For available types see the _winreg module documentation.""" key = self.__getitem__(key) _winreg.SetValueEx(self._key, key, value[0], value[1])
def __setitem__ (self, key, value): """Set a registry key value. key is the key name, value is a tuple (type, val). For available types see the _winreg module documentation.""" key = self.__getitem__(key) _winreg.SetValueEx(self._key, key, value[0], value[1])
16,389
def close (self): _winreg.CloseKey(self._key) self.closed = True
def close (self): CloseKey(self._key) self.closed = True
16,390
def proxySettings (self, tabbook): """generate the proxy setting tab""" FXTabItem(tabbook, i18n._("P&roxy Settings"), None) proxy = FXVerticalFrame(tabbook, FRAME_THICK|FRAME_RAISED) proxy_top = FXHorizontalFrame(proxy, LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_SIDE_TOP)
def proxySettings (self, tabbook): """generate the proxy setting tab""" FXTabItem(tabbook, i18n._("P&roxy Settings"), None) proxy = FXVerticalFrame(tabbook, FRAME_THICK|FRAME_RAISED) proxy_top = FXHorizontalFrame(proxy, LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_SIDE_TOP)
16,391
def onUpdFilterHosts (self, sender, sel, ptr): i = self.nofilterlist.getCurrentItem() if i<0: sender.disable() elif self.nofilterlist.isItemSelected(i): sender.enable() else: sender.disable() return 1
def onUpdNoFilterHosts (self, sender, sel, ptr): i = self.nofilterlist.getCurrentItem() if i<0: sender.disable() elif self.nofilterlist.isItemSelected(i): sender.enable() else: sender.disable() return 1
16,392
def readconfig (self): """read the configuration from disc""" debug(GUI, "reading config") self.config = Configuration() for key in ['version','port','parentproxy','parentproxyport',
def readconfig (self): """read the configuration from disc""" debug(GUI, "reading config") self.config = Configuration() for key in ['version','port','parentproxy','parentproxyport',
16,393
def toxml (self): s = """<?xml version="1.0"?>
def toxml (self): s = """<?xml version="1.0"?>
16,394
def toxml (self): s = """<?xml version="1.0"?>
def toxml (self): s = """<?xml version="1.0"?>
16,395
def startfunc (handle=None): # init logging initlog(os.path.join(ConfigDir, "logging.conf")) # we run single-threaded, decrease check interval sys.setcheckinterval(500) # support reload on posix systems if os.name=='posix': import signal signal.signal(signal.SIGHUP, reload_config) # drop privileges os.chdir("/") # for web configuration, we cannot drop privileges #if os.geteuid()==0: # import pwd, grp # try: # pentry = pwd.getpwnam("nobody") # pw_uid = 2 # nobody = pentry[pw_uid] # gentry = grp.getgrnam("nogroup") # gr_gid = 2 # nogroup = gentry[gr_gid] # os.setgid(nogroup) # os.setuid(nobody) # except KeyError: # warn(WC, "could not drop root privileges, user nobody "+\ # "and/or group nogroup not found") # pass # read configuration global config config = Configuration() config.init_filter_modules() # start the proxy import wc.proxy wc.proxy.mainloop(handle=handle)
def startfunc (handle=None): # init logging initlog(os.path.join(ConfigDir, "logging.conf")) # we run single-threaded, decrease check interval sys.setcheckinterval(500) # support reload on posix systems if os.name=='posix': import signal signal.signal(signal.SIGHUP, reload_config) # drop privileges os.chdir("/") # for web configuration, we cannot drop privileges #if os.geteuid()==0: # import pwd, grp # try: # pentry = pwd.getpwnam("nobody") # pw_uid = 2 # nobody = pentry[pw_uid] # gentry = grp.getgrnam("nogroup") # gr_gid = 2 # nogroup = gentry[gr_gid] # os.setgid(nogroup) # os.setuid(nobody) # except KeyError: # warn(WC, "could not drop root privileges, user nobody "+\ # "and/or group nogroup not found") # pass # read configuration global config config = Configuration() config.init_filter_modules() # start the proxy from wc.proxy import mainloop mainloop(handle=handle)
16,396
def read_filterconf (self): """read filter rules""" # filter configuration for filename in filterconf_files(): p = ZapperParser(filename) p.parse(file(filename)) self['folderrules'].append(p.folder) self.sort()
def read_filterconf (self): """read filter rules""" # filter configuration for filename in filterconf_files(): p = ZapperParser(filename) p.parse(file(filename), self) self['folderrules'].append(p.folder) self.sort()
16,397
def parse (self, fp): debug(WC, "Parsing %s", self.filename) try: self.p.ParseFile(fp) except xml.parsers.expat.ExpatError: error(WC, "Error parsing %s", self.filename) raise
def parse (self, fp, _config): self.config = _config debug(WC, "Parsing %s", self.filename) try: self.p.ParseFile(fp) except xml.parsers.expat.ExpatError: error(WC, "Error parsing %s", self.filename) raise
16,398
def parse (self, fp, _config): self.config = _config super(WConfigParser, self).parse(fp) self.config['configfile'] = self.filename self.config['filters'].sort()
def parse (self, fp, _config): super(WConfigParser, self).parse(fp, _config) self.config['configfile'] = self.filename self.config['filters'].sort()
16,399