rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return self.evaluateNot (expr[4:].lstrip())
res = self.evaluateNot (expr[4:].lstrip())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
return self.evaluateString (expr[7:].lstrip())
res = self.evaluateString (expr[7:].lstrip())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
return self.evaluatePython (expr[7:].lstrip())
res = self.evaluatePython (expr[7:].lstrip())
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
return self.evaluatePath (expr)
res = self.evaluatePath (expr) self.log.debug("... result %s", str(res)) return res
def evaluate (self, expr, originalAtts = None): # Returns a ContextVariable self.log.debug ("Evaluating %s" % expr) if (originalAtts is not None): # Call from outside self.globals['attrs'] = ContextVariable(originalAtts) # Supports path, exists, nocall, not, and string expr = expr.strip () if expr.startswith ('path:'): return self.evaluatePath (expr[5:].lstrip ()) elif expr.startswith ('exists:'): return self.evaluateExists (expr[7:].lstrip()) elif expr.startswith ('nocall:'): return self.evaluateNoCall (expr[7:].lstrip()) elif expr.startswith ('not:'): return self.evaluateNot (expr[4:].lstrip()) elif expr.startswith ('string:'): return self.evaluateString (expr[7:].lstrip()) elif expr.startswith ('python:'): return self.evaluatePython (expr[7:].lstrip()) else: # Not specified - so it's a path return self.evaluatePath (expr)
def finish(self, data, **attrs): names = data.keys() for name in names: for expr in self.delete: if expr.search(name): del data[name] for key,val in self.add.items(): data[key] = val debug(HURT_ME_PLENTY, "Headers\n", data) return data
def filter(self, data, **attrs): headers = data.keys()[:] for header in headers: for name in self.delete: if header.find(name) != -1: del data[header] for key,val in self.add.items(): data[key] = val debug(HURT_ME_PLENTY, "Headers\n", data) return data
if attrs: self.data += " " for key,val in attrs.items(): self.data += "%s=\"%s\"" % (key, cgi.escape(val, True))
for key,val in attrs.items(): self.data += " %s=\"%s\"" % (key, cgi.escape(val, True))
def unknown_starttag (self, tag, attributes): attrs = {} for key,val in attributes: attrs[key] = val msgid = attrs.get('i18n:translate', None) if msgid == '': if self.tag: raise Exception, "nested i18n:translate is unsupported" self.tag = tag self.data = "" elif msgid is not None: if self.tag: raise Exception, "nested i18n:translate is unsupported" if msgid.startswith("string:"): self.translations.add(msgid[7:].replace(';;', ';')) else: print >>sys.stderr, "tag <%s> has unsupported dynamic msgid %s" % (tag, `msgid`) elif self.tag: # nested tag to translate self.data += "<%s"%tag if attrs: self.data += " " for key,val in attrs.items(): self.data += "%s=\"%s\"" % (key, cgi.escape(val, True)) self.data += ">" argument = attrs.get('i18n:attributes', None) if argument is not None: for name, msgid in get_attribute_list(argument): self.translations.add(msgid)
tc, self.nameserver, self.hostname)
response, self.nameserver, self.hostname)
def process_read (self): if not self.callback: self.close() # Assume that the entire answer comes in one packet if self.tcp: if len(self.recv_buffer) < 2: return header = self.recv_buffer[:2] (l,) = struct.unpack("!H", header) if len(self.recv_buffer) < 2+l: return self.read(2) # header wire = self.read(l) try: self.socket.shutdown(1) except socket.error: pass else: wire = self.read(1024) response = wc.dns.message.from_wire( wire, keyring=self.query.keyring, request_mac=self.query.mac) wc.log.debug(wc.LOG_DNS, "got DNS response %s", response) if not self.query.is_response(response): wc.log.warn(wc.LOG_DNS, '%s was no response to %s', response, self.query) # Oops, this doesn't answer the right question. This can # happen because we're using UDP, and UDP replies might end # up in the wrong place: open conn A, send question to A, # timeout, send question to A, receive answer, close our # object, then open a new conn B, send question to B, # but get the OLD answer to A as a reply. This doesn't happen # with TCP but then TCP is slower.
if self.hostname[-4:] in ('.com','.net') and \ '64.94.110.11' in ip_addrs: callback(self.hostname, DnsResponse('error', 'not found')) else: callback(self.hostname, DnsResponse('found', ip_addrs))
callback(self.hostname, DnsResponse('found', ip_addrs))
def process_read (self): if not self.callback: self.close() # Assume that the entire answer comes in one packet if self.tcp: if len(self.recv_buffer) < 2: return header = self.recv_buffer[:2] (l,) = struct.unpack("!H", header) if len(self.recv_buffer) < 2+l: return self.read(2) # header wire = self.read(l) try: self.socket.shutdown(1) except socket.error: pass else: wire = self.read(1024) response = wc.dns.message.from_wire( wire, keyring=self.query.keyring, request_mac=self.query.mac) wc.log.debug(wc.LOG_DNS, "got DNS response %s", response) if not self.query.is_response(response): wc.log.warn(wc.LOG_DNS, '%s was no response to %s', response, self.query) # Oops, this doesn't answer the right question. This can # happen because we're using UDP, and UDP replies might end # up in the wrong place: open conn A, send question to A, # timeout, send question to A, receive answer, close our # object, then open a new conn B, send question to B, # but get the OLD answer to A as a reply. This doesn't happen # with TCP but then TCP is slower.
def __init__ (self): """initalize filter delete/add lists""" super(Header, self).__init__() self.delete = {
def get_attrs (self, url, headers): """configure header rules to add/delete""" d = super(Header, self).get_attrs(url, headers) delete = {
def __init__ (self): """initalize filter delete/add lists""" super(Header, self).__init__() self.delete = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], } self.add = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], }
self.add = {
add = {
def __init__ (self): """initalize filter delete/add lists""" super(Header, self).__init__() self.delete = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], } self.add = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], }
def addrule (self, rule): """add given rule to filter, filling header delete/add lists""" super(Header, self).addrule(rule) if not rule.name: return if not rule.value: matcher = re.compile(rule.name, re.I).match if rule.filterstage in ('both', 'request'): self.delete[wc.filter.FILTER_REQUEST_HEADER].append(matcher) if rule.filterstage in ('both', 'response'): self.delete[wc.filter.FILTER_RESPONSE_HEADER].append(matcher) else: name = str(rule.name) val = str(rule.value) if rule.filterstage in ('both', 'request'): self.add[wc.filter.FILTER_REQUEST_HEADER].append((name, val)) if rule.filterstage in ('both', 'response'): self.add[wc.filter.FILTER_RESPONSE_HEADER].append((name, val))
for rule in self.rules: if not rule.appliesTo(url) or not rule.name: continue if not rule.value: matcher = re.compile(rule.name, re.I).match if rule.filterstage in ('both', 'request'): delete[wc.filter.FILTER_REQUEST_HEADER].append(matcher) if rule.filterstage in ('both', 'response'): delete[wc.filter.FILTER_RESPONSE_HEADER].append(matcher) else: name = str(rule.name) val = str(rule.value) if rule.filterstage in ('both', 'request'): add[wc.filter.FILTER_REQUEST_HEADER].append((name, val)) if rule.filterstage in ('both', 'response'): add[wc.filter.FILTER_RESPONSE_HEADER].append((name, val)) d['header_add'] = add d['header_delete'] = delete return d
def __init__ (self): """initalize filter delete/add lists""" super(Header, self).__init__() self.delete = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], } self.add = { wc.filter.FILTER_REQUEST_HEADER: [], wc.filter.FILTER_RESPONSE_HEADER: [], }
warn(PROXY, 'read buffer full')
warn(PROXY, '%s read buffer full', str(self))
def handle_read (self): if not self.connected: # It's been closed (presumably recently) return
return len(self.send_buffer)
return self.send_buffer
def writable (self): return len(self.send_buffer)
config['allowedhostset'] = ip.hosts2map(config['allowedhosts'])
config['allowedhostset'] = _hosts2map(config['allowedhosts'])
def _form_addallowed (host): if host not in config['allowedhosts']: config['allowedhosts'].append(host) config['allowedhostset'] = ip.hosts2map(config['allowedhosts']) info['addallowed'] = True config.write_proxyconf()
config['allowedhostset'] = ip.hosts2map(config['allowedhosts'])
config['allowedhostset'] = _hosts2map(config['allowedhosts'])
def _form_delallowed (form): removed = 0 for host in _getlist(form, 'allowedhosts'): if host in config['allowedhosts']: config['allowedhosts'].remove(host) removed += 1 if removed > 0: config['allowedhostset'] = ip.hosts2map(config['allowedhosts']) config.write_proxyconf() info['delallowed'] = True
def _main (fname): import hotshot.stats stats = hotshot.stats.load(fname) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(25)
import sys import os import wc _profile = "webcleaner.prof" def _main (filename): """ Print profiling data and exit. """ if not wc.HasPstats: print >>sys.stderr, "The `pstats' Python module is not installed." sys.exit(1) if not os.path.isfile(filename): print >>sys.stderr, "Could not find regular file %r." % filename sys.exit(1) import pstats stats = pstats.Stats(filename) stats.strip_dirs().sort_stats("cumulative").print_stats(100) sys.exit(0)
def _main (fname): import hotshot.stats stats = hotshot.stats.load(fname) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(25)
import sys
def _main (fname): import hotshot.stats stats = hotshot.stats.load(fname) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(25)
_main("filter.prof")
_main(_profile)
def _main (fname): import hotshot.stats stats = hotshot.stats.load(fname) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(25)
scripts = ['webcleanerconf', 'wcheaders'],
scripts = ['webcleanerconf', 'wcheaders']
def create_batch_file(self, directory, data, filename): filename = os.path.join(directory, filename) # write the batch file util.execute(write_file, (filename, data), "creating %s" % filename, self.verbose>=1, self.dry_run)
scripts = ['webcleaner', 'webcleanerconf', 'wcheaders'],
scripts = ['webcleaner', 'webcleanerconf', 'wcheaders']
def create_batch_file(self, directory, data, filename): filename = os.path.join(directory, filename) # write the batch file util.execute(write_file, (filename, data), "creating %s" % filename, self.verbose>=1, self.dry_run)
def is_valid_bitmask (mask): """Return True if given mask is a valid network bitmask""" return 1 <= mask <= 32
def is_valid_cidrmask (mask): """check if given mask is a valid network bitmask in CIDR notation""" return 0 <= mask <= 32
def is_valid_bitmask (mask): """Return True if given mask is a valid network bitmask""" return 1 <= mask <= 32
def suffix2mask (n): "return a mask of n bits as a long integer" return (1L << (32 - n)) - 1 def mask2suffix (mask): """return suff for given bit mask""" return 32 - int(math.log(mask+1, 2)) def dq2mask (ip):
def cidr2mask (n): "return a mask where the n left-most of 32 bits are set" return ((1L << n) - 1) << (32-n) def netmask2mask (ip):
def suffix2mask (n): "return a mask of n bits as a long integer" return (1L << (32 - n)) - 1
n = dq2num(ip) return -((-n+1) | n)
return dq2num(ip)
def dq2mask (ip): "return a mask of bits as a long integer" n = dq2num(ip) return -((-n+1) | n)
n = dq2num(ip) net = n - (n & mask) return (net, mask) def dq_in_net (n, net, mask): """return True iff numerical ip n is in given net with mask. (net,mask) must be returned previously by ip2net""" m = n - (n & mask) return m == net
return dq2num(ip) & mask def dq_in_net (n, mask): """return True iff numerical ip n is in given network""" return (n & mask) == mask
def dq2net (ip, mask): "return a tuple (network ip, network mask) for given ip and mask" n = dq2num(ip) net = n - (n & mask) return (net, mask)
for net, mask in nets: if dq_in_net(n, net, mask):
for net in nets: if dq_in_net(n, net):
def host_in_set (ip, hosts, nets): """return True if given ip is in host or network list""" if ip in hosts: return True if is_valid_ipv4(ip): n = dq2num(ip) for net, mask in nets: if dq_in_net(n, net, mask): return True return False
if _host_bitmask_re.match(host):
if _host_cidrmask_re.match(host):
def hosts2map (hosts): """return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = sets.Set() nets = [] for host in hosts: if _host_bitmask_re.match(host): host, mask = host.split("/") mask = int(mask) if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask) continue if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue nets.append(dq2net(host, suffix2mask(mask))) elif _host_netmask_re.match(host): host, mask = host.split("/") if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue if not is_valid_ipv4(mask): wc.log.error(wc.LOG_NET, "mask %r is not a valid ip network mask", mask) continue nets.append(dq2net(host, dq2mask(mask))) elif is_valid_ip(host): hostset.add(expand_ip(host)[0]) else: try: hostset |= resolve_host(host) except socket.gaierror: wc.log.error(wc.LOG_NET, "invalid host %r", host) return (hostset, nets)
if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask)
if not is_valid_cidrmask(mask): wc.log.error(wc.LOG_NET, "CIDR mask %d is not a valid network mask", mask)
def hosts2map (hosts): """return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = sets.Set() nets = [] for host in hosts: if _host_bitmask_re.match(host): host, mask = host.split("/") mask = int(mask) if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask) continue if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue nets.append(dq2net(host, suffix2mask(mask))) elif _host_netmask_re.match(host): host, mask = host.split("/") if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue if not is_valid_ipv4(mask): wc.log.error(wc.LOG_NET, "mask %r is not a valid ip network mask", mask) continue nets.append(dq2net(host, dq2mask(mask))) elif is_valid_ip(host): hostset.add(expand_ip(host)[0]) else: try: hostset |= resolve_host(host) except socket.gaierror: wc.log.error(wc.LOG_NET, "invalid host %r", host) return (hostset, nets)
nets.append(dq2net(host, suffix2mask(mask)))
nets.append(dq2net(host, cidr2mask(mask)))
def hosts2map (hosts): """return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = sets.Set() nets = [] for host in hosts: if _host_bitmask_re.match(host): host, mask = host.split("/") mask = int(mask) if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask) continue if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue nets.append(dq2net(host, suffix2mask(mask))) elif _host_netmask_re.match(host): host, mask = host.split("/") if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue if not is_valid_ipv4(mask): wc.log.error(wc.LOG_NET, "mask %r is not a valid ip network mask", mask) continue nets.append(dq2net(host, dq2mask(mask))) elif is_valid_ip(host): hostset.add(expand_ip(host)[0]) else: try: hostset |= resolve_host(host) except socket.gaierror: wc.log.error(wc.LOG_NET, "invalid host %r", host) return (hostset, nets)
nets.append(dq2net(host, dq2mask(mask)))
nets.append(dq2net(host, netmask2mask(mask)))
def hosts2map (hosts): """return a set of named hosts, and a list of subnets (host/netmask adresses). Only IPv4 host/netmasks are supported. """ hostset = sets.Set() nets = [] for host in hosts: if _host_bitmask_re.match(host): host, mask = host.split("/") mask = int(mask) if not is_valid_bitmask(mask): wc.log.error(wc.LOG_NET, "bitmask %d is not a valid network mask", mask) continue if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue nets.append(dq2net(host, suffix2mask(mask))) elif _host_netmask_re.match(host): host, mask = host.split("/") if not is_valid_ipv4(host): wc.log.error(wc.LOG_NET, "host %r is not a valid ip address", host) continue if not is_valid_ipv4(mask): wc.log.error(wc.LOG_NET, "mask %r is not a valid ip network mask", mask) continue nets.append(dq2net(host, dq2mask(mask))) elif is_valid_ip(host): hostset.add(expand_ip(host)[0]) else: try: hostset |= resolve_host(host) except socket.gaierror: wc.log.error(wc.LOG_NET, "invalid host %r", host) return (hostset, nets)
s = """<h1>bla</h1>""" for c in s: p.feed(c)
p.feed("""<a><t""") p.feed("""r>""")
def _broken (): p = HtmlPrinter() s = """<h1>bla</h1>""" for c in s: p.feed(c) p.flush()
if why==(4,'Interrupted system call'):
if why.args == (4, 'Interrupted system call'):
def proxy_poll(timeout=0.0): smap = asyncore.socket_map if smap: r = filter(lambda x: x.readable(), smap.values()) w = filter(lambda x: x.writable(), smap.values()) e = smap.values() try: (r,w,e) = select.select(r,w,e, timeout) except select.error, why: debug(BRING_IT_ON, why) if why==(4,'Interrupted system call'): # this occurs on UNIX systems with a sighup signal return else: raise # Make sure we only process one type of event at a time, # because if something needs to close the connection we # don't want to call another handle_* on it handlerCount = 0 for x in e: try: x.handle_expt_event() handlerCount = handlerCount + 1 except: x.handle_error(sys.exc_type, sys.exc_value, sys.exc_traceback) for x in w: try: t = time.time() if x not in e: x.handle_write_event() handlerCount = handlerCount + 1 if time.time() - t > 0.1: debug(BRING_IT_ON, 'wslow', '%4.1f'%(time.time()-t), 's', x) except: x.handle_error(sys.exc_type, sys.exc_value, sys.exc_traceback) for x in r: try: t = time.time() if x not in e and x not in w: x.handle_read_event() handlerCount = handlerCount + 1 if time.time() - t > 0.1: debug(BRING_IT_ON, 'rslow', '%4.1f'%(time.time()-t), 's', x) except: x.handle_error(sys.exc_type, sys.exc_value, sys.exc_traceback) return handlerCount #_OBFUSCATE_IP = config['obfuscateip']
self.decoders.append(wc.proxy.UnchunkStream.UnchunkStream())
self.decoders.append( wc.proxy.decoders.UnchunkStream.UnchunkStream())
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.StringIO(self.read(i)[2:]) msg = wc.proxy.Headers.WcMessage(fp) # put unparsed data (if any) back to the buffer msg.rewindbody() self.recv_buffer = fp.read() + self.recv_buffer fp.close() wc.log.debug(wc.LOG_PROXY, "%s client headers \n%s", self, msg) self.fix_request_headers(msg) clientheaders = msg.copy() stage = wc.filter.STAGE_REQUEST_HEADER self.attrs = wc.filter.get_filterattrs(self.url, [stage], clientheaders=clientheaders, headers=msg) self.set_persistent(msg, self.http_ver) self.mangle_request_headers(msg) self.compress = wc.proxy.Headers.client_set_encoding_headers(msg) # filter headers self.headers = wc.filter.applyfilter(stage, msg, "finish", self.attrs) # add decoders self.decoders = [] # if content-length header is missing, assume zero length self.bytes_remaining = \ wc.proxy.Headers.get_content_length(self.headers, 0) # chunked encoded if self.headers.has_key('Transfer-Encoding'): # XXX don't look at value, assume chunked encoding for now wc.log.debug(wc.LOG_PROXY, '%s Transfer-encoding %r', self, self.headers['Transfer-encoding']) self.decoders.append(wc.proxy.UnchunkStream.UnchunkStream()) wc.proxy.Headers.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 = urllib.splitnport(host, defaultport) if not self.hostname: wc.log.error(wc.LOG_PROXY, "%s missing hostname in request", self) self.error(400, _("Bad Request")) # local request? if self.hostname in wc.proxy.dns_lookups.resolver.localhosts and \ self.port == wc.configuration.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'): wc.log.warn(wc.LOG_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 wc.configuration.config["proxyuser"]: creds = wc.proxy.auth.get_header_credentials(self.headers, 'Proxy-Authorization') if not creds: auth = ", ".join(wc.proxy.auth.get_challenges()) self.error(407, _("Proxy Authentication Required"), auth=auth) return if 'NTLM' in creds: if creds['NTLM'][0]['type'] == \ wc.proxy.auth.ntlm.NTLMSSP_NEGOTIATE: attrs = { 'host': creds['NTLM'][0]['host'], 'domain': creds['NTLM'][0]['domain'], 'type': wc.proxy.auth.ntlm.NTLMSSP_CHALLENGE, } auth = ",".join(wc.proxy.auth.get_challenges(**attrs)) self.error(407, _("Proxy Authentication Required"), auth=auth) return # XXX the data=None argument should hold POST data if not wc.proxy.auth.check_credentials(creds, username=wc.configuration.config['proxyuser'], password_b64=wc.configuration.config['proxypass'], uri=wc.proxy.auth.get_auth_uri(self.url), method=self.method, data=None): wc.log.warn(wc.LOG_AUTH, "Bad proxy authentication from %s", self.addr[0]) auth = ", ".join(wc.proxy.auth.get_challenges()) self.error(407, _("Proxy Authentication Required"), auth=auth) return if self.method in ['OPTIONS', 'TRACE'] and \ wc.proxy.Headers.client_get_max_forwards(self.headers) == 0: # XXX display options ? self.state = 'done' headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = 'text/plain\r' wc.proxy.ServerHandleDirectly.ServerHandleDirectly(self, '%s 200 OK' % self.protocol, 200, headers, '') return if self.needs_redirect: self.state = 'done' headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = 'text/plain\r' headers['Location'] = '%s\r' % self.url wc.proxy.ServerHandleDirectly.ServerHandleDirectly(self, '%s 302 Found' % self.protocol, 302, headers, '') return self.state = 'content'
return result.rstrip().lstrip('\x08').replace(' \x08', '')
result = result.lstrip('\x08').strip().replace(' \x08', '') return result
def classify (self, f): if not self.entries: raise StandardError("Not initialised properly") # Are we still looking for the ruleset to apply or are we in a rule found_rule = False # If we failed part of the rule there is no point looking for # higher level subrule allow_next = 0 # String provided by the successfull rule result = ""
attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY],
attrs = wc.filter.get_filterattrs(fname, "127.0.0.1", [wc.filter.STAGE_RESPONSE_MODIFY],
def _main (): """USAGE: test/run.sh test/filterfile.py <config dir> <.html file>""" if len(sys.argv)!=3: print _main.__doc__ sys.exit(1) confdir = sys.argv[1] fname = sys.argv[2] if fname=="-": f = sys.stdin else: f = file(fname) logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name, filelogs=False) wc.configuration.config = wc.configuration.init(confdir=confdir) wc.configuration.config.init_filter_modules() wc.proxy.dns_lookups.init_resolver() headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = "text/html" attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY], headers=headers, serverheaders=headers) filtered = "" data = f.read(2048) while data: print >>sys.stderr, "Test: data", len(data) try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs) except wc.filter.FilterException, msg: print >>sys.stderr, "Test: exception:", msg pass data = f.read(2048) print >>sys.stderr, "Test: finishing" i = 1 while True: print >>sys.stderr, "Test: finish", i try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs) break except wc.filter.FilterException, msg: print >>sys.stderr, "Test: finish: exception:", msg wc.proxy.proxy_poll(timeout=max(0, wc.proxy.run_timers())) i += 1 if i==200: # background downloading if javascript is too slow print >>sys.stderr, "Test: oooooops" break print "Filtered:", filtered
filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs)
filtered += wc.filter.applyfilter( wc.filter.STAGE_RESPONSE_MODIFY, data, 'filter', attrs)
def _main (): """USAGE: test/run.sh test/filterfile.py <config dir> <.html file>""" if len(sys.argv)!=3: print _main.__doc__ sys.exit(1) confdir = sys.argv[1] fname = sys.argv[2] if fname=="-": f = sys.stdin else: f = file(fname) logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name, filelogs=False) wc.configuration.config = wc.configuration.init(confdir=confdir) wc.configuration.config.init_filter_modules() wc.proxy.dns_lookups.init_resolver() headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = "text/html" attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY], headers=headers, serverheaders=headers) filtered = "" data = f.read(2048) while data: print >>sys.stderr, "Test: data", len(data) try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs) except wc.filter.FilterException, msg: print >>sys.stderr, "Test: exception:", msg pass data = f.read(2048) print >>sys.stderr, "Test: finishing" i = 1 while True: print >>sys.stderr, "Test: finish", i try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs) break except wc.filter.FilterException, msg: print >>sys.stderr, "Test: finish: exception:", msg wc.proxy.proxy_poll(timeout=max(0, wc.proxy.run_timers())) i += 1 if i==200: # background downloading if javascript is too slow print >>sys.stderr, "Test: oooooops" break print "Filtered:", filtered
filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs)
filtered += wc.filter.applyfilter( wc.filter.STAGE_RESPONSE_MODIFY, "", 'finish', attrs)
def _main (): """USAGE: test/run.sh test/filterfile.py <config dir> <.html file>""" if len(sys.argv)!=3: print _main.__doc__ sys.exit(1) confdir = sys.argv[1] fname = sys.argv[2] if fname=="-": f = sys.stdin else: f = file(fname) logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name, filelogs=False) wc.configuration.config = wc.configuration.init(confdir=confdir) wc.configuration.config.init_filter_modules() wc.proxy.dns_lookups.init_resolver() headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = "text/html" attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY], headers=headers, serverheaders=headers) filtered = "" data = f.read(2048) while data: print >>sys.stderr, "Test: data", len(data) try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs) except wc.filter.FilterException, msg: print >>sys.stderr, "Test: exception:", msg pass data = f.read(2048) print >>sys.stderr, "Test: finishing" i = 1 while True: print >>sys.stderr, "Test: finish", i try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs) break except wc.filter.FilterException, msg: print >>sys.stderr, "Test: finish: exception:", msg wc.proxy.proxy_poll(timeout=max(0, wc.proxy.run_timers())) i += 1 if i==200: # background downloading if javascript is too slow print >>sys.stderr, "Test: oooooops" break print "Filtered:", filtered
wc.log.debug(wc.LOG_PROXY, '%s server_response %r (%d)',
wc.log.debug(wc.LOG_PROXY, '%s server_response %r (%r)',
def server_response (self, server, response, status, headers): """read and filter server response data""" assert server.connected, "%s server was not connected" % self wc.log.debug(wc.LOG_PROXY, '%s server_response %r (%d)', self, response, status) # try google options if status in wc.google.google_try_status and \ wc.configuration.config['try_google']: server.client_abort() self.try_google(self.url, response) else: self.server = server self.write("%s\r\n" % response) if not headers.has_key('Content-Length'): # without content length the client can not determine # when all data is sent self.persistent = False #self.set_persistent(headers, self.http_ver) # note: headers is a WcMessage object, not a dict self.write("".join(headers.headers)) self.write('\r\n')
f = tarfile.gzopen(source)
f = TarFile.gzopen(source)
def blacklist (file): source = "downloads/"+file # extract tar if file.endswith(".tar.gz"): print "extracting archive..." d = "extracted/"+file[:-7] f = tarfile.gzopen(source) for m in f: a, b = os.path.split(m.name) a = os.path.basename(a) if b in myfiles and a in mycats: print m.name f.extract(m, d) f.close() read_blacklists(d) elif file.endswith(".gz"): print "gunzip..." f = gzip.open(source) file = "extracted/"+file[:-3] os.makedirs(os.path.dirname(file)) w = open(file, 'wb') w.write(f.read()) w.close() f.close() read_data(file, "domains", domains)
if not os.path.exists(small_file):
if not os.path.exists("downloads/%s"%smallfile):
def dmozlists (file): print "filtering %s..." % file smallfile = "small_%s"%file if not os.path.exists(small_file): os.system(("zcat downloads/%s | config/dmozfilter.py | "+ \ "gzip --best > downloads/%s") % (file, smallfile)) file = smallfile print "dmozlist %s..." % file f = gzip.GzipFile("downloads/"+file) line = f.readline() topic = None while line: line = line.strip() if line.startswith("<Topic r:id="): topic = line[13:line.rindex('"')].split("/", 2)[1].lower() elif topic=='kids_and_teens' and line.startswith("<link r:resource="): #split url, and add to domains or urls url = line[18:line.rindex('"')] if url.startswith("http://"): url = url[7:] tup = url.split("/", 1) if len(tup)>1 and tup[1]: categories.setdefault(topic, {})["urls"] = None entry = "%s/%s" % (tup[0].lower(), tup[1]) urls.setdefault(entry, {})[topic] = None else: categories.setdefault(topic, {})["domains"] = None domains.setdefault(tup[0].lower(), {})[topic] = None line = f.readline() f.close()
lines.append(' bindaddress="%s"' % xmlquoteattr(self['bindaddress'))
lines.append(' bindaddress="%s"' % xmlquoteattr(self['bindaddress']))
def write_proxyconf (self): """write proxy configuration""" lines = [] lines.append('<?xml version="1.0" encoding="%s"?>' % ConfigCharset) lines.append('<!DOCTYPE webcleaner SYSTEM "webcleaner.dtd">') lines.append('<webcleaner') lines.append(' version="%s"' % xmlquoteattr(self['version'])) lines.append(' bindaddress="%s"' % xmlquoteattr(self['bindaddress')) lines.append(' port="%d"' % self['port']) lines.append(' sslport="%d"' % self['sslport']) if self['sslgateway']: lines.append(' sslgateway="%d"' % self['sslgateway']) lines.append(' adminuser="%s"' % xmlquoteattr(self['adminuser'])) lines.append(' adminpass="%s"' % xmlquoteattr(self['adminpass'])) lines.append(' proxyuser="%s"' % xmlquoteattr(self['proxyuser'])) lines.append(' proxypass="%s"' % xmlquoteattr(self['proxypass'])) if self['parentproxy']: lines.append(' parentproxy="%s"' % xmlquoteattr(self['parentproxy'])) lines.append(' parentproxyuser="%s"' % xmlquoteattr(self['parentproxyuser'])) lines.append(' parentproxypass="%s"' % xmlquoteattr(self['parentproxypass'])) lines.append(' parentproxyport="%d"' % self['parentproxyport']) lines.append(' timeout="%d"' % self['timeout']) lines.append(' gui_theme="%s"' % xmlquoteattr(self['gui_theme'])) lines.append(' auth_ntlm="%d"' % self['auth_ntlm']) lines.append(' try_google="%d"' % self['try_google']) lines.append(' clamavconf="%s"' % xmlquoteattr(self['clamavconf'])) hosts = self['nofilterhosts'] lines.append(' nofilterhosts="%s"' % xmlquoteattr(",".join(hosts))) hosts = self['allowedhosts'] lines.append(' allowedhosts="%s"' % xmlquoteattr(",".join(hosts))) lines.append('>') for key in self['filters']: lines.append('<filter name="%s"/>' % xmlquoteattr(key)) lines.append('</webcleaner>') f = file(self.configfile, 'w') f.write(os.linesep.join(lines)) f.close()
out = wc.webgui.TAL.TALInterpreter.FasterStringIO()
out = wc.webgui.ZTUtils.FasterStringIO()
def render (self, context): """Render this Page Template""" out = wc.webgui.TAL.TALInterpreter.FasterStringIO() __traceback_supplement__ = \
"After DELAY seconds, run the CALLBACK function"
debug(PROXY, "Adding %s to %d timers", callback, len(TIMERS))
def make_timer (delay, callback): "After DELAY seconds, run the CALLBACK function" TIMERS.append( (time.time()+delay, callback) ) TIMERS.sort() debug(PROXY, "%d timers", len(TIMERS))
debug(PROXY, "%d timers", len(TIMERS))
def make_timer (delay, callback): "After DELAY seconds, run the CALLBACK function" TIMERS.append( (time.time()+delay, callback) ) TIMERS.sort() debug(PROXY, "%d timers", len(TIMERS))
self.filt("""<script src="
self.filt("""<script src="http://ivwbox.de"></script>""", "")
def testFilter (self): self.filt("""<script src="#ivwbox.de"></script>""", "")
print "XXX read"
def rawrequest3 (url, port): """raw request with proxy CONNECT protocol""" from wc.proxy.Dispatcher import create_socket from urllib import splitnport parts = urlparse.urlsplit(url) host, sslport = splitnport(parts[1], 443) path = urlparse.urlunsplit(('', '', parts[2], parts[3], parts[4])) _sock = create_socket(socket.AF_INET, socket.SOCK_STREAM) addr = (socket.gethostbyname('localhost'), port) _sock.connect(addr) _sock.send('CONNECT %s:%d HTTP/1.1\r\n' % (host, sslport)) _sock.send('User-Agent: getssl\r\n') _sock.send('\r\n') buf = "" while True: buf += _sock.recv(1024) if "\r\n\r\n" in buf: break print repr(buf) print "initiating SSL handshake" sock = socket.ssl(_sock) print "write SSL request...", sock.write("GET %s HTTP/1.1\r\n" % url) sock.write("Host: %s\r\n" % host) sock.write("\r\n") print " ok." while True: try: print "XXX read" print repr(sock.read(80)) except socket.sslerror, msg: print "Oops" break _sock.close()
print "Oops"
if msg[0] != 6: print "Oops", msg
def rawrequest3 (url, port): """raw request with proxy CONNECT protocol""" from wc.proxy.Dispatcher import create_socket from urllib import splitnport parts = urlparse.urlsplit(url) host, sslport = splitnport(parts[1], 443) path = urlparse.urlunsplit(('', '', parts[2], parts[3], parts[4])) _sock = create_socket(socket.AF_INET, socket.SOCK_STREAM) addr = (socket.gethostbyname('localhost'), port) _sock.connect(addr) _sock.send('CONNECT %s:%d HTTP/1.1\r\n' % (host, sslport)) _sock.send('User-Agent: getssl\r\n') _sock.send('\r\n') buf = "" while True: buf += _sock.recv(1024) if "\r\n\r\n" in buf: break print repr(buf) print "initiating SSL handshake" sock = socket.ssl(_sock) print "write SSL request...", sock.write("GET %s HTTP/1.1\r\n" % url) sock.write("Host: %s\r\n" % host) sock.write("\r\n") print " ok." while True: try: print "XXX read" print repr(sock.read(80)) except socket.sslerror, msg: print "Oops" break _sock.close()
ratings.clear()
def _reset_ratings (): ratings.clear() for category, catdata in service['categories'].items(): if catdata['rvalues']: ratings[category] = catdata['rvalues'][0] else: ratings[category] = "" values.clear() for category, value in ratings.items(): if category not in ["generic", "modified"]: values[category] = {value: True} rating_modified.clear()
values.clear() for category, value in ratings.items(): if category not in ["generic", "modified"]: values[category] = {value: True}
values[category] = {} for value in catdata['rvalues']: values[category][value] = False
def _reset_ratings (): ratings.clear() for category, catdata in service['categories'].items(): if catdata['rvalues']: ratings[category] = catdata['rvalues'][0] else: ratings[category] = "" values.clear() for category, value in ratings.items(): if category not in ["generic", "modified"]: values[category] = {value: True} rating_modified.clear()
info = {} error = {} ratings = {} values = {} rating_modified = {}
def _calc_ratings_display (): global ratings_display urls = rating_cache.keys() urls.sort() ratings_display = urls[curindex:curindex+_entries_per_page] for _url in ratings_display: t = _strtime(float(rating_cache[_url]['modified'])) rating_modified[_url] = t.replace(u" ", u"&nbsp;")
info.clear() error.clear()
for key in info.keys(): info[key] = False for key in error.keys(): error[key] = False
def _form_reset (): info.clear() error.clear() _reset_ratings() global url, generic, curindex url = u"" generic = False curindex = 0
script = escape_js(remove_html_comments(script)) if not jscomments: script = remove_js_comments(script)
script = escape_js(remove_html_comments(script, jscomments=jscomments))
def clean (script, jscomments=True): """ Clean script from comments and HTML. """ script = escape_js(remove_html_comments(script)) if not jscomments: script = remove_js_comments(script) return u"\n<!--\n%s\n//-->\n" % script
def remove_whitespace (script): lines = [] for line in script.splitlines(): line = line.rstrip() if line: lines.append(line) return "\n".join(lines)
def clean (script, jscomments=True): """ Clean script from comments and HTML. """ script = escape_js(remove_html_comments(script)) if not jscomments: script = remove_js_comments(script) return u"\n<!--\n%s\n//-->\n" % script
if script[i:i+9].lower() == '</script>' and quote: script = script[:i]+"</scr"+quote+"+"+quote+"ipt>"+\ script[(i+9):]
if script[i:i+9].lower() == '</script>': if quote: script = script[:i] + "</scr" + quote + "+" + \ quote + "ipt>" + script[(i+9):] else: script = script[:i] + script[(i+9):]
def escape_js_line (script): # if we encounter "</script>" in the script, we assume that is # in a quoted string. The solution is to split it into # "</scr"+"ipt>" (with the proper quotes of course) quote = False escape = False i = 0 while i < len(script): c = script[i] if c == '"' or c == "'": if not escape: if quote == c: quote = False elif not quote: quote = c escape = False elif c == '\\': escape = not escape elif c == '<': if script[i:i+9].lower() == '</script>' and quote: script = script[:i]+"</scr"+quote+"+"+quote+"ipt>"+\ script[(i+9):] escape = False else: escape = False i += 1 #script = script.replace('-->', '--&#62;') #script = script_sub("&#60;/script&#62;", script) return script
def remove_html_comments (script):
def remove_html_comments (script, jscomments=True):
def remove_html_comments (script): """ Remove leading and trailing HTML comments from the script text. """ script = remove_whitespace(script) mo = _start_js_comment(script) if mo: script = script[mo.end():] mo = _end_js_comment(script) if mo: if mo.group("comment") is not None: i = script.rindex("//") else: i = script.rindex("-->") script = script[:i] return script.strip()
script = remove_whitespace(script)
lines = [] for line in script.splitlines(): line = line.rstrip() if line and (jscomments or not line.lstrip().startswith('//')): lines.append(line) script = "\n".join(lines)
def remove_html_comments (script): """ Remove leading and trailing HTML comments from the script text. """ script = remove_whitespace(script) mo = _start_js_comment(script) if mo: script = script[mo.end():] mo = _end_js_comment(script) if mo: if mo.group("comment") is not None: i = script.rindex("//") else: i = script.rindex("-->") script = script[:i] return script.strip()
fp = gzip.GzipFile('', 'rb', 9, StringIO(content))
fp = gzip.GzipFile('', 'rb', 9, StringIO.StringIO(content))
def decode (page): "gunzip or deflate a compressed page" encoding = page.info().get("Content-Encoding") if encoding in ('gzip', 'x-gzip', 'deflate'): # cannot seek in socket descriptors, so must get content now content = page.read() if encoding == 'deflate': fp = StringIO.StringIO(zlib.decompress(content)) else: fp = gzip.GzipFile('', 'rb', 9, StringIO(content)) # remove content-encoding header headers = {} ceheader = re.compile(r"(?i)content-encoding:") for h in page.info().keys(): if not ceheader.match(h): headers[h] = page.info()[h] page = urllib.addinfourl(fp, headers, page.geturl()) return page
self._debug("JS document.write %s", `data`)
def jsProcessData (self, data): """process data produced by document.write() JavaScript""" #self._debug("JS document.write %s", `data`) self.js_output += 1 # parse recursively self.js_html.feed(data)
self._debug("JS: popup")
def jsProcessPopup (self): """process javascript popup""" #self._debug("JS: popup") self.js_popup += 1
self._debug("buf_append_data")
def buf_append_data (self, data): """we have to make sure that we have no two following DATA things in the tag buffer. Why? To be 100% sure that an ENCLOSED match really matches enclosed data. """ #self._debug("buf_append_data") if data[0]==DATA and self.buf and self.buf[-1][0]==DATA: self.buf[-1][1] += data[1] else: self.buf.append(data)
self._debug("flushbuf")
def flushbuf (self): """clear and return the output buffer""" #self._debug("flushbuf") data = self.outbuf.getvalue() self.outbuf.close() self.outbuf = StringIO() return data
self._debug("self.outbuf %s", `self.outbuf.getvalue()`) self._debug("self.buf %s", `self.buf`) self._debug("self.waitbuf %s", `self.waitbuf`) self._debug("self.inbuf %s", `self.inbuf.getvalue()`)
def _debugbuf (self): """print debugging information about data buffer status""" #self._debug("self.outbuf %s", `self.outbuf.getvalue()`) #self._debug("self.buf %s", `self.buf`) #self._debug("self.waitbuf %s", `self.waitbuf`) #self._debug("self.inbuf %s", `self.inbuf.getvalue()`)
self._debug("feed %s", `data`)
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data #self._debug("feed %s", `data`) self.parser.feed(data) else: #self._debug("feed") pass else: # wait state ==> put in input buffer #self._debug("wait") self.inbuf.write(data)
self._debug("feed")
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data #self._debug("feed %s", `data`) self.parser.feed(data) else: #self._debug("feed") pass else: # wait state ==> put in input buffer #self._debug("wait") self.inbuf.write(data)
self._debug("wait")
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data #self._debug("feed %s", `data`) self.parser.feed(data) else: #self._debug("feed") pass else: # wait state ==> put in input buffer #self._debug("wait") self.inbuf.write(data)
self._debug("flush")
def flush (self): #self._debug("flush") # flushing in wait state raises a filter exception if self.state=='wait': raise FilterWait("HtmlParser[%d]: waiting for data"%self.level) self.parser.flush()
self._debug("replay %s", `waitbuf`)
def replay (self, waitbuf): """call the handler functions again with buffer data""" #self._debug("replay %s", `waitbuf`) for item in waitbuf: if item[0]==DATA: self._data(item[1]) elif item[0]==STARTTAG: self.startElement(item[1], item[2]) elif item[0]==ENDTAG: self.endElement(item[1]) elif item[0]==COMMENT: self.comment(item[1])
self._debug("cdata %s", `data`)
def cdata (self, data): """character data""" #self._debug("cdata %s", `data`) return self._data(data)
self._debug("characters %s", `data`)
def characters (self, data): """characters""" #self._debug("characters %s", `data`) return self._data(data)
self._debug("comment %s", `data`)
def comment (self, data): """a comment; accept only non-empty comments""" #self._debug("comment %s", `data`) item = [COMMENT, data] if self.state=='wait': return self.waitbuf.append(item) if self.comments and data: self.buf.append(item)
self._debug("doctype %s", `data`)
def doctype (self, data): #self._debug("doctype %s", `data`) return self._data("<!DOCTYPE%s>"%data)
self._debug("pi %s", `data`)
def pi (self, data): #self._debug("pi %s", `data`) return self._data("<?%s?>"%data)
self._debug("startElement %s", `tag`)
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data #self._debug("startElement %s", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = strip_quotes(attrs['href']) debug(FILTER, "using base url %s", `self.base_url`) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): #self._debug("matched rule %s on tag %s", `rule.title`, `tag`) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: #self._debug("put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
self._debug("matched rule %s on tag %s", `rule.title`, `tag`)
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data #self._debug("startElement %s", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = strip_quotes(attrs['href']) debug(FILTER, "using base url %s", `self.base_url`) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): #self._debug("matched rule %s on tag %s", `rule.title`, `tag`) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: #self._debug("put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
self._debug("put on buffer")
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data #self._debug("startElement %s", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = strip_quotes(attrs['href']) debug(FILTER, "using base url %s", `self.base_url`) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): #self._debug("matched rule %s on tag %s", `rule.title`, `tag`) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: #self._debug("put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
self._debug("endElement %s", `tag`)
def endElement (self, tag): """We know the following: if a rule matches, it must be the one on the top of the stack. So we look only at the top rule.
self._debug("JS: del %s from %s", `name`, `tag`)
def jsStartElement (self, tag, attrs): """Check popups for onmouseout and onmouseover. Inline extern javascript sources""" changed = 0 self.js_src = None self.js_output = 0 self.js_popup = 0 for name in ('onmouseover', 'onmouseout'): if attrs.has_key(name) and self.jsPopup(attrs, name): #self._debug("JS: del %s from %s", `name`, `tag`) del attrs[name] changed = 1 if tag=='form': name = attrs.get('name', attrs.get('id')) self.jsForm(name, attrs.get('action', ''), attrs.get('target', '')) elif tag=='script': lang = attrs.get('language', '').lower() url = attrs.get('src', '') scrtype = attrs.get('type', '').lower() is_js = scrtype=='text/javascript' or \ lang.startswith('javascript') or \ not (lang or scrtype) if is_js and url: return self.jsScriptSrc(url, lang) self.buf.append([STARTTAG, tag, attrs])
self._debug("JS: jsPopup")
def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" #self._debug("JS: jsPopup") val = resolve_html_entities(attrs[name]) if not val: return self.js_env.attachListener(self) try: self.js_env.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.js_env.detachListener(self) res = self.js_popup self.js_popup = 0 return res
self._debug("jsForm %s action %s %s", `name`, `action`, `target`)
def jsForm (self, name, action, target): """when hitting a (named) form, notify the JS engine about that""" if not name: return #self._debug("jsForm %s action %s %s", `name`, `action`, `target`) self.js_env.addForm(name, action, target)
self._debug("switching back to parse with")
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.js_script: warn(PARSER, "HtmlParser[%d]: empty JS src %s", self.level, url) else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) script = "\n<!--\n%s\n//-->\n"%escape_js(self.js_script) self.buf.append([DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.js_script = '' self.state = 'parse' #self._debug("switching back to parse with") self._debugbuf() else: #self._debug("JS read %d <= %s", len(data), url) self.js_script += data
self._debug("JS read %d <= %s", len(data), url)
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.js_script: warn(PARSER, "HtmlParser[%d]: empty JS src %s", self.level, url) else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) script = "\n<!--\n%s\n//-->\n"%escape_js(self.js_script) self.buf.append([DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.js_script = '' self.state = 'parse' #self._debug("switching back to parse with") self._debugbuf() else: #self._debug("JS read %d <= %s", len(data), url) self.js_script += data
self._debug("JS: jsScript %s %s", ver, `script`)
def jsScript (self, script, ver, item): """execute given script with javascript version ver""" #self._debug("JS: jsScript %s %s", ver, `script`) assert self.state == 'parse' assert len(self.buf) >= 2 self.js_output = 0 self.js_env.attachListener(self) # start recursive html filter (used by jsProcessData) self.js_html = FilterHtmlParser(self.rules, self.pics, self.url, comments=self.comments, javascript=self.js_filter, level=self.level+1) # execute self.js_env.executeScript(unescape_js(script), ver) self.js_env.detachListener(self) # wait for recursive filter to finish self.jsEndScript(item)
self._debug("JS: endScript")
def jsEndScript (self, item): #self._debug("JS: endScript") assert len(self.buf) >= 2 if self.js_output: try: self.js_html.feed('') self.js_html.flush() except FilterWait: self.state = 'wait' self.waited = 'True' make_timer(0.1, lambda : self.jsEndScript(item)) return self.js_html._debugbuf() assert not self.js_html.inbuf.getvalue() assert not self.js_html.waitbuf assert len(self.buf) >= 2 self.buf[-2:-2] = [[DATA, self.js_html.outbuf.getvalue()]]+self.js_html.buf self.js_html = None if (self.js_popup + self.js_output) > 0: # delete old script del self.buf[-1] del self.buf[-1] elif not self.filterEndElement(item[1]): self.buf.append(item) #self._debug("JS: switching back to parse with") self._debugbuf() self.state = 'parse'
self._debug("JS: switching back to parse with")
def jsEndScript (self, item): #self._debug("JS: endScript") assert len(self.buf) >= 2 if self.js_output: try: self.js_html.feed('') self.js_html.flush() except FilterWait: self.state = 'wait' self.waited = 'True' make_timer(0.1, lambda : self.jsEndScript(item)) return self.js_html._debugbuf() assert not self.js_html.inbuf.getvalue() assert not self.js_html.waitbuf assert len(self.buf) >= 2 self.buf[-2:-2] = [[DATA, self.js_html.outbuf.getvalue()]]+self.js_html.buf self.js_html = None if (self.js_popup + self.js_output) > 0: # delete old script del self.buf[-1] del self.buf[-1] elif not self.filterEndElement(item[1]): self.buf.append(item) #self._debug("JS: switching back to parse with") self._debugbuf() self.state = 'parse'
if data and self.statuscode != 407 and
if data and self.statuscode != 407 and \
def flush (self): """ Flush data of decoders (if any) and filters and write it to the client. return True if flush was successful. """ assert None == wc.log.debug(wc.LOG_PROXY, "%s HttpServer.flush", self) if not self.statuscode and self.method != 'CONNECT': wc.log.warn(wc.LOG_PROXY, "%s flush without status", self) return True data = self.flush_coders(self.decoders) try: for stage in FilterStages: data = wc.filter.applyfilter(stage, data, "finish", self.attrs) except wc.filter.FilterWait, msg: assert None == wc.log.debug(wc.LOG_PROXY, "%s FilterWait %s", self, msg) # the filter still needs some data # to save CPU time make connection unreadable for a while self.set_unreadable(1.0) return False except wc.filter.FilterRating, msg: assert None == wc.log.debug(wc.LOG_PROXY, "%s FilterRating from content %s", self, msg) self._show_rating_deny(str(msg)) return True data = self.flush_coders(self.encoders, data=data) # the client might already have closed if not self.client: return if self.defer_data: self.defer_data = False self.client.server_response(self, self.response, self.statuscode, self.headers) if not self.client: return # note that self.client still could be a ClientServerMatchMaker if data and self.statuscode != 407 and hasattr(self.client, "server_content"): self.client.server_content(data) return True
def visit_image(self, node):
class FixedHTMLTranslator (html4css1.HTMLTranslator): def visit_image (self, node):
def visit_image(self, node): """ Like html4css1.visit_image(), but with align="middle" enforcement. """ atts = node.non_default_attributes() # The XHTML standard only allows align="middle" if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')): try: im = html4css1.Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts))
Like html4css1.visit_image(), but with align="middle" enforcement.
Like super.visit_image(), but with align="middle" enforcement.
def visit_image(self, node): """ Like html4css1.visit_image(), but with align="middle" enforcement. """ atts = node.non_default_attributes() # The XHTML standard only allows align="middle" if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')): try: im = html4css1.Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts))
atts = node.non_default_attributes() if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')):
atts = {} atts['src'] = node['uri'] if node.has_key('width'): atts['width'] = node['width'] if node.has_key('height'): atts['height'] = node['height'] if node.has_key('scale'): if Image and not (node.has_key('width') and node.has_key('height')):
def visit_image(self, node): """ Like html4css1.visit_image(), but with align="middle" enforcement. """ atts = node.non_default_attributes() # The XHTML standard only allows align="middle" if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')): try: im = html4css1.Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts))
im = html4css1.Image.open(str(atts['src']))
im = Image.open(str(atts['src']))
def visit_image(self, node): """ Like html4css1.visit_image(), but with align="middle" enforcement. """ atts = node.non_default_attributes() # The XHTML standard only allows align="middle" if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')): try: im = html4css1.Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts))
atts['width'] = im.size[0]
atts['width'] = str(im.size[0])
def visit_image(self, node): """ Like html4css1.visit_image(), but with align="middle" enforcement. """ atts = node.non_default_attributes() # The XHTML standard only allows align="middle" if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')): try: im = html4css1.Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts))
atts['height'] = im.size[1]
atts['height'] = str(im.size[1])
def visit_image(self, node): """ Like html4css1.visit_image(), but with align="middle" enforcement. """ atts = node.non_default_attributes() # The XHTML standard only allows align="middle" if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')): try: im = html4css1.Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts))
if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement):
for att_name in 'width', 'height': if atts.has_key(att_name): match = re.match(r'([0-9.]+)(\S*)$', atts[att_name]) assert match atts[att_name] = '%s%s' % ( float(match.group(1)) * (float(node['scale']) / 100), match.group(2)) style = [] for att_name in 'width', 'height': if atts.has_key(att_name): if re.match(r'^[0-9.]+$', atts[att_name]): atts[att_name] += 'px' style.append('%s: %s;' % (att_name, atts[att_name])) del atts[att_name] if style: atts['style'] = ' '.join(style) atts['alt'] = node.get('alt', atts['src']) if (isinstance(node.parent, nodes.TextElement) or (isinstance(node.parent, nodes.reference) and not isinstance(node.parent.parent, nodes.TextElement))): suffix = '' else: suffix = '\n' if node.has_key('align'): if node['align'] == 'center': if suffix: self.body.append('<div align="center" class="align-center">') self.context.append('</div>\n') suffix = '' else: atts['align'] = 'middle' self.context.append('') else: atts['align'] = node['align'] self.context.append('') atts['class'] = 'align-%s' % node['align'] else:
def visit_image(self, node): """ Like html4css1.visit_image(), but with align="middle" enforcement. """ atts = node.non_default_attributes() # The XHTML standard only allows align="middle" if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')): try: im = html4css1.Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts))
else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts)) class HTMLNavTranslator (html4css1.HTMLTranslator):
self.body.append(self.emptytag(node, 'img', suffix, **atts)) class HTMLNavTranslator (FixedHTMLTranslator):
def visit_image(self, node): """ Like html4css1.visit_image(), but with align="middle" enforcement. """ atts = node.non_default_attributes() # The XHTML standard only allows align="middle" if atts.get('align') == u"center": atts['align'] = u"middle" if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if html4css1.Image and not (atts.has_key('width') and atts.has_key('height')): try: im = html4css1.Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts))
<![CDATA[
<!--
def get_topframe_bashing (self): return """<script type="text/javascript">
]]>
// -->
def get_topframe_bashing (self): return """<script type="text/javascript">
p.feed("<hTml>")
def _test(): p = HtmlPrinter() p.feed("<hTml>") p.feed("<a href>") p.feed("<a href=''>") p.feed('<a href="">') p.feed("<a href='a'>") p.feed('<a href="a">') p.feed("<a href=a>") p.feed("<a href='\"'>") p.feed("<a href=\"'\">") p.feed("<a href=' '>") p.feed("<a href=a href=b>") p.feed("<a/>") p.feed("<a href/>") p.feed("<a href=a />") p.feed("</a>") p.feed("<?bla foo?>") p.feed("<?bla?>") p.feed("<!-- - comment -->") p.feed("<!---->") p.feed("<!DOCTYPE \"vla foo>") p.flush()
p.feed("<a href=''>") p.feed('<a href="">') p.feed("<a href='a'>") p.feed('<a href="a">')
def _test(): p = HtmlPrinter() p.feed("<hTml>") p.feed("<a href>") p.feed("<a href=''>") p.feed('<a href="">') p.feed("<a href='a'>") p.feed('<a href="a">') p.feed("<a href=a>") p.feed("<a href='\"'>") p.feed("<a href=\"'\">") p.feed("<a href=' '>") p.feed("<a href=a href=b>") p.feed("<a/>") p.feed("<a href/>") p.feed("<a href=a />") p.feed("</a>") p.feed("<?bla foo?>") p.feed("<?bla?>") p.feed("<!-- - comment -->") p.feed("<!---->") p.feed("<!DOCTYPE \"vla foo>") p.flush()
p.feed("<a href='\"'>") p.feed("<a href=\"'\">") p.feed("<a href=' '>") p.feed("<a href=a href=b>") p.feed("<a/>") p.feed("<a href/>") p.feed("<a href=a />") p.feed("</a>") p.feed("<?bla foo?>") p.feed("<?bla?>") p.feed("<!-- - comment -->") p.feed("<!---->") p.feed("<!DOCTYPE \"vla foo>")
def _test(): p = HtmlPrinter() p.feed("<hTml>") p.feed("<a href>") p.feed("<a href=''>") p.feed('<a href="">') p.feed("<a href='a'>") p.feed('<a href="a">') p.feed("<a href=a>") p.feed("<a href='\"'>") p.feed("<a href=\"'\">") p.feed("<a href=' '>") p.feed("<a href=a href=b>") p.feed("<a/>") p.feed("<a href/>") p.feed("<a href=a />") p.feed("</a>") p.feed("<?bla foo?>") p.feed("<?bla?>") p.feed("<!-- - comment -->") p.feed("<!---->") p.feed("<!DOCTYPE \"vla foo>") p.flush()
p.feed(""" """)
p.feed("")
def _broken (): p = HtmlPrinter() p.feed(""" """) p.flush()
_broken()
_test()
def _broken (): p = HtmlPrinter() p.feed(""" """) p.flush()
for c in '<!-- -->':
for c in '<a/>':
def _broken (): p = HtmlPrinter() for c in '<!-- -->': p.feed(c) p.flush()