rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
elif encoding and encoding!='identity' and not rewrite:
|
elif encoding and encoding!='identity' and rewrite:
|
def process_headers (self): # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.match(r'^((?:[^\r\n]+\r?\n)*\r?\n)', self.recv_buffer) if not m: return # handle continue requests (XXX should be in process_response?) response = self.response.split() if response and response[1] == '100': # it's a Continue request, so go back to waiting for headers # XXX for HTTP/1.1 clients, forward this self.state = 'response' return # filter headers self.headers = applyfilter(FILTER_RESPONSE_HEADER, rfc822.Message(StringIO(self.read(m.end()))), attrs=self.nofilter) # check for unusual compressed files if not self.headers.has_key('Content-Type') and \ (self.document.endswith(".bz2") or \ self.document.endswith(".tgz") or \ self.document.endswith(".gz")): gm = mimetypes.guess_type(self.document, False) if gm[0] and gm[1]: self.headers['Content-Encoding'] = gm[1] self.headers['Content-Type'] = gm[0] # will content be rewritten? rewrite = False for ro in config['mime_content_rewriting']: if ro.match(self.headers.get('Content-Type', "")): rewrite = True break #debug(HURT_ME_PLENTY, "S/Headers ", `self.headers.headers`) if self.headers.has_key('Content-Length'): if rewrite: remove_headers(self.headers, ['Content-Length']) self.bytes_remaining = None else: self.bytes_remaining = int(self.headers['Content-Length']) else: self.bytes_remaining = None
|
data = wc.filter.xmlTags.tagbuf2data(items, StringIO()).getvalue()
|
data = wc.filter.XmlTags.tagbuf2data(items, StringIO()).getvalue()
|
def match_complete (self, pos, tagbuf): """ We know that the tag (and tag attributes) match. Now match the enclosing block. Return True on a match. """ if not self.enclosed: # no enclosed expression => match return True # put buf items together for matching items = tagbuf[pos:] data = wc.filter.xmlTags.tagbuf2data(items, StringIO()).getvalue() return self.enclosed_ro.match(data)
|
return True
|
def debug (logname, msg, *args, **kwargs): """ Log a debug message. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.DEBUG): _log(log.debug, msg, args, tb=kwargs.get("tb")) return True
|
|
get_context(dirs, form, localcontext, lang)
|
get_context(dirs, form, localcontext, hostname, lang)
|
def __init__ (self, client, url, form, protocol, clientheaders, status=200, msg=_('Ok'), localcontext=None, auth=''): """load a web configuration template and return response""" wc.log.debug(wc.LOG_GUI, "WebConfig %s %s", url, form) if isinstance(msg, unicode): msg = msg.encode("iso8859-1", "ignore") self.client = client # we pretend to be the server self.connected = True headers = get_headers(url, status, auth, clientheaders) path = "" newstatus = None try: lang = wc.i18n.get_headers_lang(clientheaders) # get the template filename path, dirs, lang = wc.webgui.get_template_url(url, lang) if path.endswith('.html'): # get TAL context context, newstatus = \ get_context(dirs, form, localcontext, lang) if newstatus == 401 and status != newstatus: client.error(401, _("Authentication Required"), auth=wc.proxy.auth.get_challenges()) return # get (compiled) template template = wc.webgui.templatecache.templates[path] # expand template data = expand_template(template, context) # note: data is already encoded else: fp = file(path, 'rb') data = fp.read() fp.close() except IOError: wc.log.exception(wc.LOG_GUI, "Wrong path %r:", url) # XXX this can actually lead to a maximum recursion # error when client.error caused the exception client.error(404, _("Not Found")) return except StandardError: # catch standard exceptions and report internal error wc.log.exception(wc.LOG_GUI, "Template error: %r", path) client.error(500, _("Internal Error")) return # not catched builtin exceptions are: # SystemExit, StopIteration and all warnings
|
def get_context (dirs, form, localcontext, lang):
|
def get_context (dirs, form, localcontext, hostname, lang):
|
def get_context (dirs, form, localcontext, lang): """Get template context, raise ImportError if not found. The context includes the given local context, plus all variables defined by the imported context module Evaluation of the context can set a different HTTP status. Returns tuple `(context, status)`""" # get template-specific context dict status = None modulepath = ".".join(['context'] + dirs[:-1]) template = dirs[-1].replace(".", "_") # this can raise an import error exec "from %s import %s as template_context" % (modulepath, template) # make TAL context context = {} if hasattr(template_context, "_form_reset"): template_context._form_reset() if hasattr(template_context, "_exec_form") and form is not None: # handle form action wc.log.debug(wc.LOG_GUI, "got form %s", form) status = template_context._exec_form(form, lang) # add form vars to context context_add(context, "form", form) # add default context values add_default_context(context, dirs[-1], lang) # augment the context attrs = [ x for x in dir(template_context) if not x.startswith('_') ] for attr in attrs: context_add(context, attr, getattr(template_context, attr)) # add local context if localcontext is not None: for key, value in localcontext.items(): context_add(context, key, value) return context, status
|
add_default_context(context, dirs[-1], lang)
|
add_default_context(context, dirs[-1], hostname, lang)
|
def get_context (dirs, form, localcontext, lang): """Get template context, raise ImportError if not found. The context includes the given local context, plus all variables defined by the imported context module Evaluation of the context can set a different HTTP status. Returns tuple `(context, status)`""" # get template-specific context dict status = None modulepath = ".".join(['context'] + dirs[:-1]) template = dirs[-1].replace(".", "_") # this can raise an import error exec "from %s import %s as template_context" % (modulepath, template) # make TAL context context = {} if hasattr(template_context, "_form_reset"): template_context._form_reset() if hasattr(template_context, "_exec_form") and form is not None: # handle form action wc.log.debug(wc.LOG_GUI, "got form %s", form) status = template_context._exec_form(form, lang) # add form vars to context context_add(context, "form", form) # add default context values add_default_context(context, dirs[-1], lang) # augment the context attrs = [ x for x in dir(template_context) if not x.startswith('_') ] for attr in attrs: context_add(context, attr, getattr(template_context, attr)) # add local context if localcontext is not None: for key, value in localcontext.items(): context_add(context, key, value) return context, status
|
def add_default_context (context, filename, lang):
|
def add_default_context (context, filename, hostname, lang):
|
def add_default_context (context, filename, lang): """add context variables used by all templates""" # rule macros path, dirs = wc.webgui.get_safe_template_path("macros/rules.html") rulemacros = wc.webgui.templatecache.templates[path] context_add(context, "rulemacros", rulemacros.macros) # standard macros path, dirs = wc.webgui.get_safe_template_path("macros/standard.html") macros = wc.webgui.templatecache.templates[path] context_add(context, "macros", macros.macros) # used by navigation macro add_nav_context(context, filename) # page template name context_add(context, "filename", filename) # base url context_add(context, "baseurl", "http://localhost:%d/" % wc.configuration.config['port']) add_i18n_context(context, lang)
|
context_add(context, "baseurl", "http://localhost:%d/" % wc.configuration.config['port'])
|
port = wc.configuration.config['port'] context_add(context, "baseurl", "http://%s:%d/" % (hostname, port)) newport = wc.configuration.config.get('newport', port) context_add(context, "newbaseurl", "http://%s:%d/" % (hostname, newport))
|
def add_default_context (context, filename, lang): """add context variables used by all templates""" # rule macros path, dirs = wc.webgui.get_safe_template_path("macros/rules.html") rulemacros = wc.webgui.templatecache.templates[path] context_add(context, "rulemacros", rulemacros.macros) # standard macros path, dirs = wc.webgui.get_safe_template_path("macros/standard.html") macros = wc.webgui.templatecache.templates[path] context_add(context, "macros", macros.macros) # used by navigation macro add_nav_context(context, filename) # page template name context_add(context, "filename", filename) # base url context_add(context, "baseurl", "http://localhost:%d/" % wc.configuration.config['port']) add_i18n_context(context, lang)
|
elif encoding and encoding!='identity':
|
elif encoding and encoding!='identity' and not rewrite:
|
def process_headers (self): # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.match(r'^((?:[^\r\n]+\r?\n)*\r?\n)', self.recv_buffer) if not m: return # handle continue requests (XXX should be in process_response?) response = self.response.split() if response and response[1] == '100': # it's a Continue request, so go back to waiting for headers # XXX for HTTP/1.1 clients, forward this self.state = 'response' return # filter headers self.headers = applyfilter(FILTER_RESPONSE_HEADER, rfc822.Message(StringIO(self.read(m.end()))), attrs=self.nofilter) # check for unusual compressed files if not self.headers.has_key('Content-Type') and \ (self.document.endswith(".bz2") or \ self.document.endswith(".tgz") or \ self.document.endswith(".gz")): gm = mimetypes.guess_type(self.document, False) if gm[0] and gm[1]: self.headers['Content-Encoding'] = gm[1] self.headers['Content-Type'] = gm[0] # will content be rewritten? rewrite = False for ro in config['mime_content_rewriting']: if ro.match(self.headers.get('Content-Type', "")): rewrite = True break #debug(HURT_ME_PLENTY, "S/Headers ", `self.headers.headers`) if self.headers.has_key('Content-Length'): if rewrite: remove_headers(self.headers, ['Content-Length']) self.bytes_remaining = None else: self.bytes_remaining = int(self.headers['Content-Length']) else: self.bytes_remaining = None
|
def test_multiheader_clen_toclient (self):
|
def test_multiheader_clen_toSrv (self):
|
def test_multiheader_clen_toclient (self): self.start_test()
|
headers.append("Content-Length: %d" % (len(content)-5))
|
headers.append("Content-Length: %d" % (len(content)-1))
|
def get_request_headers (self, content): port = self.server.socket.getsockname()[1] headers = [ "Host: localhost:%d" % port, "Proxy-Connection: close", ] if content: headers.append("Content-Length: %d" % len(content)) headers.append("Content-Length: %d" % (len(content)-5)) return headers
|
class test_multiheader_clen_toserver (ProxyTest):
|
class test_multiheader_clen_toClt (ProxyTest):
|
def check_request_headers (self, request): num_found = 0 for header in request.headers: if header.lower().startswith("content-length:"): num_found += 1 self.assert_(num_found < 2)
|
def test_multiheader_clen_toserver (self):
|
def test_multiheader_clen_toClt (self):
|
def test_multiheader_clen_toserver (self): self.start_test()
|
"Content-Length: %d" % (len(content)-5),
|
"Content-Length: %d" % (len(content)-1),
|
def get_response_headers (self, content): return [ "Content-Type: text/plain", "Content-Length: %d" % len(content), "Content-Length: %d" % (len(content)-5), ]
|
name = "_webcleaner_configdata.py"
|
name = "_webcleaner2_configdata.py"
|
def fix_configdata (): """fix install and config paths in the config file""" name = "_webcleaner_configdata.py" conffile = os.path.join(sys.prefix, "Lib", "site-packages", name) lines = [] for line in file(conffile): if line.startswith("install_") or line.startswith("config_"): lines.append(fix_install_path(line)) else: lines.append(line) f = file(conffile, "w") f.write("".join(lines)) f.close()
|
if has_attr(headers, "getallmatchingheaders"):
|
if hasattr(headers, "getallmatchingheaders"):
|
def has_header_value (headers, key, value): if has_attr(headers, "getallmatchingheaders"): # rfc822.Message() object for h in headers.getallmatchingheaders(key): if h.strip().lower() == value.lower(): return "True" return None return headers.get(key, '').lower() == value.lower()
|
callback(DnsResponse('found', [hostname]))
|
callback(hostname, DnsResponse('found', [hostname]))
|
def __init__ (self, hostname, callback): global resolver if has_whitespace(hostname): # If there's whitespace, it's a copy/paste error hostname = re.sub(r'\s+', '', hostname) if ".." in hostname: # another possible typo hostname = re.sub(r'\.\.+', '.', hostname) if wc.ip.is_valid_ip(hostname): # it is already an ip adress callback(DnsResponse('found', [hostname])) return self.erroranswer = None # set if one answer failed self.hostname = hostname self.callback = callback self.queries = [hostname] # all queries to be made self.answers = {} # Map hostname to DNS answer # How long do we wait before trying another expansion? self.delay = 3 if not dnscache.well_known_hosts.has_key(hostname): for domain in resolver.search: self.queries.append(hostname + domain) if hostname.find('.') < 0: # If there's no dot, we should try expanding patterns for pattern in resolver.search_patterns: self.queries.append(pattern % hostname) # it is likely that search_domains matter self.delay = 0.2 self.requests = self.queries[1:] # queries we haven't yet made # Issue the primary request wc.proxy.make_timer(0, lambda: dnscache.lookup(hostname, self.handle_dns)) # and then start another request as well if it's needed if self.delay < 1 and len(self.requests) > 0: wc.proxy.make_timer(self.delay, self.handle_issue_request)
|
if not self.defer_data:
|
if self.defer_data: wc.log.debug(wc.LOG_PROXY, "deferring header data") else:
|
def process_headers (self): """look for headers and process them if found""" # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.match(r'^((?:[^\r\n]+\r?\n)*\r?\n)', self.recv_buffer) if not m: return # get headers fp = StringIO.StringIO(self.read(m.end())) 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() # make a copy for later serverheaders = msg.copy() wc.log.debug(wc.LOG_PROXY, "%s server headers\n%s", self, serverheaders) if self.statuscode == 100: # it's a Continue request, so go back to waiting for headers # XXX for HTTP/1.1 clients, forward this self.state = 'response' return self.set_persistent(msg, wc.proxy.ServerPool.serverpool.http_versions[self.addr]) self.attrs = wc.filter.get_filterattrs(self.url, [wc.filter.FILTER_RESPONSE_HEADER], clientheaders=self.client.headers, serverheaders=serverheaders) try: self.headers = \ wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_HEADER, msg, "finish", self.attrs) except wc.filter.FilterRating, msg: wc.log.debug(wc.LOG_PROXY, "%s FilterRating from header: %s", self, msg) if msg == wc.filter.Rating.MISSING: # still have to look at content self.defer_data = True else: self._show_rating_deny(str(msg)) return #except wc.filter.FilterMime, msg: # wc.log.debug(wc.LOG_PROXY, "%s FilterMime from header: %s", # self, msg) # self._show_mime_replacement(str(msg)) # return if self.statuscode in (301, 302): location = self.headers.get('Location') if location: host = wc.url.spliturl(location)[1] if host in wc.proxy.dns_lookups.resolver.localhosts: self.handle_error(_('redirection to localhost')) return self.mangle_response_headers() if self.statuscode in (204, 304) or self.method == 'HEAD': # these response codes indicate no content self.state = 'recycle' else: self.state = 'content' self.attrs = wc.filter.get_filterattrs(self.url, FilterLevels, clientheaders=self.client.headers, serverheaders=serverheaders, headers=self.headers) wc.log.debug(wc.LOG_PROXY, "%s filtered headers %s", self, self.headers) if not self.defer_data: self.client.server_response(self, self.response, self.statuscode, self.headers) # note: self.client could be None here
|
def _show_mime_replacement (self, url): self.statuscode = 302 response = "%s 302 %s" % (self.protocol, _("Moved Temporarily")) headers = wc.proxy.Headers.WcMessage() headers['Content-type'] = 'text/plain\r' headers['Location'] = url headers['Content-Length'] = '0\r' wc.log.debug(wc.LOG_PROXY, "%s headers\n%s", self, headers) self.client.server_response(self, response, self.statuscode, headers) if not self.client: return self.client.server_close(self) self.client = None self.state = 'recycle' self.persistent = False self.close()
|
def is_rewrite (self): """return True iff this server will modify content""" for ro in wc.configuration.config['mime_content_rewriting']: if ro.match(self.headers.get('Content-Type', '')): return True return False
|
|
if data and self.statuscode != 407:
|
if self.statuscode != 407:
|
def process_content (self): """process server data: filter it and write it to client""" data = self.read(self.bytes_remaining) wc.log.debug(wc.LOG_PROXY, "%s process %d bytes", self, len(data)) if self.bytes_remaining is not None: # If we do know how many bytes we're dealing with, # we'll close the connection when we're done self.bytes_remaining -= len(data) wc.log.debug(wc.LOG_PROXY, "%s %d bytes remaining", self, self.bytes_remaining) is_closed = False for decoder in self.decoders: data = decoder.decode(data) wc.log.debug(wc.LOG_PROXY, "%s have run decoder %s", self, decoder) if not is_closed and decoder.closed: is_closed = True try: data = wc.filter.applyfilters(FilterLevels, data, "filter", self.attrs) except wc.filter.FilterWait, msg: wc.log.debug(wc.LOG_PROXY, "%s FilterWait %s", self, msg) except wc.filter.FilterRating, msg: wc.log.debug(wc.LOG_PROXY, "%s FilterRating from content %s", self, msg) self._show_rating_deny(str(msg)) return except wc.filter.FilterProxyError, e: self.client.error(e.status, e.msg, txt=e.text) self.handle_error("filter proxy error") return underflow = self.bytes_remaining is not None and \ self.bytes_remaining < 0 if underflow: wc.log.warn(wc.LOG_PROXY, _("server received %d bytes more than content-length"), (-self.bytes_remaining)) if data and self.statuscode != 407: if self.defer_data: self.defer_data = False self.client.server_response(self, self.response, self.statuscode, self.headers) if not self.client: return self.client.server_content(data) if is_closed or self.bytes_remaining == 0: # either we ran out of bytes, or the decoder says we're done self.state = 'recycle'
|
self.client.server_content(data)
|
if data: self.client.server_content(data)
|
def process_content (self): """process server data: filter it and write it to client""" data = self.read(self.bytes_remaining) wc.log.debug(wc.LOG_PROXY, "%s process %d bytes", self, len(data)) if self.bytes_remaining is not None: # If we do know how many bytes we're dealing with, # we'll close the connection when we're done self.bytes_remaining -= len(data) wc.log.debug(wc.LOG_PROXY, "%s %d bytes remaining", self, self.bytes_remaining) is_closed = False for decoder in self.decoders: data = decoder.decode(data) wc.log.debug(wc.LOG_PROXY, "%s have run decoder %s", self, decoder) if not is_closed and decoder.closed: is_closed = True try: data = wc.filter.applyfilters(FilterLevels, data, "filter", self.attrs) except wc.filter.FilterWait, msg: wc.log.debug(wc.LOG_PROXY, "%s FilterWait %s", self, msg) except wc.filter.FilterRating, msg: wc.log.debug(wc.LOG_PROXY, "%s FilterRating from content %s", self, msg) self._show_rating_deny(str(msg)) return except wc.filter.FilterProxyError, e: self.client.error(e.status, e.msg, txt=e.text) self.handle_error("filter proxy error") return underflow = self.bytes_remaining is not None and \ self.bytes_remaining < 0 if underflow: wc.log.warn(wc.LOG_PROXY, _("server received %d bytes more than content-length"), (-self.bytes_remaining)) if data and self.statuscode != 407: if self.defer_data: self.defer_data = False self.client.server_response(self, self.response, self.statuscode, self.headers) if not self.client: return self.client.server_content(data) if is_closed or self.bytes_remaining == 0: # either we ran out of bytes, or the decoder says we're done self.state = 'recycle'
|
wc.log.debug(wc.LOG_PROXY, "%s write SSL tunneled data to client %s", self, self.client) self.client.write(self.read())
|
data = self.read() if data: wc.log.debug(wc.LOG_PROXY, "%s send %d bytes SSL tunneled data to client %s", self, len(data), self.client) self.client.write(data)
|
def process_client (self): """gets called on SSL tunneled connections, delegates server data directly to the client without filtering""" if not self.client: # delay return wc.log.debug(wc.LOG_PROXY, "%s write SSL tunneled data to client %s", self, self.client) self.client.write(self.read())
|
if not fuzzy and str:
|
if not fuzzy and s:
|
def __add (self, id, s, fuzzy): "Add a non-fuzzy translation to the dictionary." if not fuzzy and str: # check for multi-line values and munge them appropriately if '\n' in s: lines = s.rstrip().split('\n') s = NLSTR.join(lines) self.catalog[id] = s
|
lno += True
|
lno += 1
|
def _loadFile (self): # shamelessly cribbed from Python's Tools/i18n/msgfmt.py # 25-Mar-2003 Nathan R. Yergler ([email protected]) # 14-Apr-2003 Hacked by Barry Warsaw ([email protected])
|
print >> outfile, pot_header % {'time': time.ctime(), 'version': __version__}
|
pass
|
def write(self, s): pass
|
if hasattr(self, "addr") and self.addr and self.addr[1] != 80: portstr = ':%d' % self.addr[1] else: portstr = "" extra += '%s%s%s' % (self.hostname or self.addr[0], portstr, self.document)
|
hasaddr = hasattr(self, "addr") and self.addr if hasattr(self, "hostname"): extra += self.hostname elif hasaddr: extra += self.addr[0] if hasaddr and self.addr[1] != 80: extra += ':%d' % self.addr[1] if hasattr(self, "document"): extra += self.document
|
def __repr__ (self): """ Object description. """ extra = "" if hasattr(self, "persistent") and self.persistent: extra += "persistent " if hasattr(self, "addr") and self.addr and self.addr[1] != 80: portstr = ':%d' % self.addr[1] else: portstr = "" extra += '%s%s%s' % (self.hostname or self.addr[0], portstr, self.document) if hasattr(self, "client") and self.client: extra += " client" #if len(extra) > 46: extra = extra[:43] + '...' return '<%s:%-8s %s>' % ('server', self.state, extra)
|
self.method, self.url, protocol = self.request.split()
|
self.method, self.url, self.protocol = self.request.split()
|
def __init__ (self, client, request, headers, content, mime=None): self.client = client self.request = request self.headers = headers self.content = content self.mime = mime self.state = 'dns' self.method, self.url, protocol = self.request.split() # 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 = client.hostname self.port = client.port self.document = document_quote(client.document) assert self.hostname # start DNS lookup dns_lookups.background_lookup(self.hostname, self.handle_dns)
|
self.headers.append("%s: %s\r" % (name, value))
|
self.headers.append("%s: %s\r\n" % (name, value))
|
def addheader (self, name, value): """add given header name and value to the end of the header list. Multiple headers with the same name are supported""" self.headers.append("%s: %s\r" % (name, value))
|
wc.proxy.decoders.UnchunkStream.UnchunkStream())
|
wc.proxy.decoder.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.decoders.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'
|
self.assertEqual("blink", check_spelling("blink")) self.assertEqual("blink", check_spelling("bllnk")) self.assertEqual("html", check_spelling("htmm")) self.assertEqual("hr", check_spelling("hu")) self.assertEqual("xmlns:a", check_spelling("xmlns:a")) self.assertEqual("heisead", check_spelling("heisead"))
|
url = "unknown" self.assertEqual("blink", check_spelling("blink", url)) self.assertEqual("blink", check_spelling("bllnk", url)) self.assertEqual("html", check_spelling("htmm", url)) self.assertEqual("hr", check_spelling("hrr", url)) self.assertEqual("xmlns:a", check_spelling("xmlns:a", url)) self.assertEqual("heisead", check_spelling("heisead", url))
|
def test_htmltags (self): self.assertEqual("blink", check_spelling("blink")) self.assertEqual("blink", check_spelling("bllnk")) self.assertEqual("html", check_spelling("htmm")) self.assertEqual("hr", check_spelling("hu")) self.assertEqual("xmlns:a", check_spelling("xmlns:a")) self.assertEqual("heisead", check_spelling("heisead"))
|
config['proxyuser'] = ''
|
config['proxyuser'] = u''
|
def _exec_form (form, lang): # reset info/error global filterenabled, filterdisabled filterenabled = u"" filterdisabled = u"" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) elif config['port']!=8080: _form_proxyport(8080) # ssl server port if form.has_key('sslport'): _form_sslport(_getval(form, 'sslport')) elif config['sslport']!=8443: _form_sslport(8443) # ssl gateway if form.has_key('sslgateway'): _form_sslgateway(1) else: _form_sslgateway(0) # admin user if form.has_key('adminuser'): _form_adminuser(_getval(form, 'adminuser').strip(), res) elif config['adminuser']: config['adminuser'] = u'' config.write_proxyconf() info['adminuser'] = True # admin pass if form.has_key('adminpass'): val = _getval(form, 'adminpass') # ignore dummy values if val!=u'__dummy__': _form_adminpass(base64.encodestring(val).strip(), res) elif config['adminpass']: config['adminpass'] =u '' config.write_proxyconf() info['adminpass'] = True if config['adminuser']: res[0] = 401 # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) elif config['proxyuser']: config['proxyuser'] = '' config.write_proxyconf() info['proxyuser'] = True # proxy pass if form.has_key('proxypass'): val = _getval(form, 'proxypass') # ignore dummy values if val!=u'__dummy__': _form_proxypass(base64.encodestring(val).strip(), res) elif config['proxypass']: config['proxypass'] = '' config.write_proxyconf() info['proxypass'] = True # ntlm authentication if form.has_key('auth_ntlm'): if not config['auth_ntlm']: config['auth_ntlm'] = 1 config.write_proxyconf() info['auth_ntlm'] = True elif config['auth_ntlm']: config['auth_ntlm'] = 0 config.write_proxyconf() info['auth_ntlm'] = True # use google cache if form.has_key('try_google'): if not config['try_google']: config['try_google'] = 1 config.write_proxyconf() info['try_google'] = True elif config['try_google']: config['try_google'] = 0 config.write_proxyconf() info['try_google'] = True # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) elif config['parentproxy']: config['parentproxy'] = '' config.write_proxyconf() info['parentproxy'] = True # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) elif config['parentproxyport'] != 3128: config['parentproxyport'] = 3128 config.write_proxyconf() info['parentproxyport'] = True # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) elif config['parentproxyuser']: config['parentproxyuser'] = '' config.write_proxyconf() info['parentproxyuser'] = True # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') # ignore dummy values if val!=u'__dummy__': _form_parentproxypass(base64.encodestring(val).strip()) elif config['parentproxypass']: config['parentproxypass'] = '' config.write_proxyconf() info['parentproxypass'] = True # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) elif config['timeout']!=30: config['timeout'] = 30 config.write_proxyconf() info['timeout'] = True # filter modules _form_filtermodules(form) # allowed hosts if form.has_key('addallowed') and form.has_key('newallowed'): _form_addallowed(_getval(form, 'newallowed').strip()) elif form.has_key('delallowed') and form.has_key('allowedhosts'): _form_delallowed(form) # no filter hosts if form.has_key('addnofilter') and form.has_key('newnofilter'): _form_addnofilter(_getval(form, 'newnofilter').strip()) elif form.has_key('delnofilter') and form.has_key('nofilterhosts'): _form_delnofilter(form) return res[0]
|
config['proxypass'] = ''
|
config['proxypass'] = u''
|
def _exec_form (form, lang): # reset info/error global filterenabled, filterdisabled filterenabled = u"" filterdisabled = u"" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) elif config['port']!=8080: _form_proxyport(8080) # ssl server port if form.has_key('sslport'): _form_sslport(_getval(form, 'sslport')) elif config['sslport']!=8443: _form_sslport(8443) # ssl gateway if form.has_key('sslgateway'): _form_sslgateway(1) else: _form_sslgateway(0) # admin user if form.has_key('adminuser'): _form_adminuser(_getval(form, 'adminuser').strip(), res) elif config['adminuser']: config['adminuser'] = u'' config.write_proxyconf() info['adminuser'] = True # admin pass if form.has_key('adminpass'): val = _getval(form, 'adminpass') # ignore dummy values if val!=u'__dummy__': _form_adminpass(base64.encodestring(val).strip(), res) elif config['adminpass']: config['adminpass'] =u '' config.write_proxyconf() info['adminpass'] = True if config['adminuser']: res[0] = 401 # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) elif config['proxyuser']: config['proxyuser'] = '' config.write_proxyconf() info['proxyuser'] = True # proxy pass if form.has_key('proxypass'): val = _getval(form, 'proxypass') # ignore dummy values if val!=u'__dummy__': _form_proxypass(base64.encodestring(val).strip(), res) elif config['proxypass']: config['proxypass'] = '' config.write_proxyconf() info['proxypass'] = True # ntlm authentication if form.has_key('auth_ntlm'): if not config['auth_ntlm']: config['auth_ntlm'] = 1 config.write_proxyconf() info['auth_ntlm'] = True elif config['auth_ntlm']: config['auth_ntlm'] = 0 config.write_proxyconf() info['auth_ntlm'] = True # use google cache if form.has_key('try_google'): if not config['try_google']: config['try_google'] = 1 config.write_proxyconf() info['try_google'] = True elif config['try_google']: config['try_google'] = 0 config.write_proxyconf() info['try_google'] = True # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) elif config['parentproxy']: config['parentproxy'] = '' config.write_proxyconf() info['parentproxy'] = True # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) elif config['parentproxyport'] != 3128: config['parentproxyport'] = 3128 config.write_proxyconf() info['parentproxyport'] = True # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) elif config['parentproxyuser']: config['parentproxyuser'] = '' config.write_proxyconf() info['parentproxyuser'] = True # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') # ignore dummy values if val!=u'__dummy__': _form_parentproxypass(base64.encodestring(val).strip()) elif config['parentproxypass']: config['parentproxypass'] = '' config.write_proxyconf() info['parentproxypass'] = True # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) elif config['timeout']!=30: config['timeout'] = 30 config.write_proxyconf() info['timeout'] = True # filter modules _form_filtermodules(form) # allowed hosts if form.has_key('addallowed') and form.has_key('newallowed'): _form_addallowed(_getval(form, 'newallowed').strip()) elif form.has_key('delallowed') and form.has_key('allowedhosts'): _form_delallowed(form) # no filter hosts if form.has_key('addnofilter') and form.has_key('newnofilter'): _form_addnofilter(_getval(form, 'newnofilter').strip()) elif form.has_key('delnofilter') and form.has_key('nofilterhosts'): _form_delnofilter(form) return res[0]
|
config['parentproxy'] = ''
|
config['parentproxy'] = u''
|
def _exec_form (form, lang): # reset info/error global filterenabled, filterdisabled filterenabled = u"" filterdisabled = u"" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) elif config['port']!=8080: _form_proxyport(8080) # ssl server port if form.has_key('sslport'): _form_sslport(_getval(form, 'sslport')) elif config['sslport']!=8443: _form_sslport(8443) # ssl gateway if form.has_key('sslgateway'): _form_sslgateway(1) else: _form_sslgateway(0) # admin user if form.has_key('adminuser'): _form_adminuser(_getval(form, 'adminuser').strip(), res) elif config['adminuser']: config['adminuser'] = u'' config.write_proxyconf() info['adminuser'] = True # admin pass if form.has_key('adminpass'): val = _getval(form, 'adminpass') # ignore dummy values if val!=u'__dummy__': _form_adminpass(base64.encodestring(val).strip(), res) elif config['adminpass']: config['adminpass'] =u '' config.write_proxyconf() info['adminpass'] = True if config['adminuser']: res[0] = 401 # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) elif config['proxyuser']: config['proxyuser'] = '' config.write_proxyconf() info['proxyuser'] = True # proxy pass if form.has_key('proxypass'): val = _getval(form, 'proxypass') # ignore dummy values if val!=u'__dummy__': _form_proxypass(base64.encodestring(val).strip(), res) elif config['proxypass']: config['proxypass'] = '' config.write_proxyconf() info['proxypass'] = True # ntlm authentication if form.has_key('auth_ntlm'): if not config['auth_ntlm']: config['auth_ntlm'] = 1 config.write_proxyconf() info['auth_ntlm'] = True elif config['auth_ntlm']: config['auth_ntlm'] = 0 config.write_proxyconf() info['auth_ntlm'] = True # use google cache if form.has_key('try_google'): if not config['try_google']: config['try_google'] = 1 config.write_proxyconf() info['try_google'] = True elif config['try_google']: config['try_google'] = 0 config.write_proxyconf() info['try_google'] = True # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) elif config['parentproxy']: config['parentproxy'] = '' config.write_proxyconf() info['parentproxy'] = True # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) elif config['parentproxyport'] != 3128: config['parentproxyport'] = 3128 config.write_proxyconf() info['parentproxyport'] = True # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) elif config['parentproxyuser']: config['parentproxyuser'] = '' config.write_proxyconf() info['parentproxyuser'] = True # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') # ignore dummy values if val!=u'__dummy__': _form_parentproxypass(base64.encodestring(val).strip()) elif config['parentproxypass']: config['parentproxypass'] = '' config.write_proxyconf() info['parentproxypass'] = True # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) elif config['timeout']!=30: config['timeout'] = 30 config.write_proxyconf() info['timeout'] = True # filter modules _form_filtermodules(form) # allowed hosts if form.has_key('addallowed') and form.has_key('newallowed'): _form_addallowed(_getval(form, 'newallowed').strip()) elif form.has_key('delallowed') and form.has_key('allowedhosts'): _form_delallowed(form) # no filter hosts if form.has_key('addnofilter') and form.has_key('newnofilter'): _form_addnofilter(_getval(form, 'newnofilter').strip()) elif form.has_key('delnofilter') and form.has_key('nofilterhosts'): _form_delnofilter(form) return res[0]
|
config['parentproxyuser'] = ''
|
config['parentproxyuser'] = u''
|
def _exec_form (form, lang): # reset info/error global filterenabled, filterdisabled filterenabled = u"" filterdisabled = u"" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) elif config['port']!=8080: _form_proxyport(8080) # ssl server port if form.has_key('sslport'): _form_sslport(_getval(form, 'sslport')) elif config['sslport']!=8443: _form_sslport(8443) # ssl gateway if form.has_key('sslgateway'): _form_sslgateway(1) else: _form_sslgateway(0) # admin user if form.has_key('adminuser'): _form_adminuser(_getval(form, 'adminuser').strip(), res) elif config['adminuser']: config['adminuser'] = u'' config.write_proxyconf() info['adminuser'] = True # admin pass if form.has_key('adminpass'): val = _getval(form, 'adminpass') # ignore dummy values if val!=u'__dummy__': _form_adminpass(base64.encodestring(val).strip(), res) elif config['adminpass']: config['adminpass'] =u '' config.write_proxyconf() info['adminpass'] = True if config['adminuser']: res[0] = 401 # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) elif config['proxyuser']: config['proxyuser'] = '' config.write_proxyconf() info['proxyuser'] = True # proxy pass if form.has_key('proxypass'): val = _getval(form, 'proxypass') # ignore dummy values if val!=u'__dummy__': _form_proxypass(base64.encodestring(val).strip(), res) elif config['proxypass']: config['proxypass'] = '' config.write_proxyconf() info['proxypass'] = True # ntlm authentication if form.has_key('auth_ntlm'): if not config['auth_ntlm']: config['auth_ntlm'] = 1 config.write_proxyconf() info['auth_ntlm'] = True elif config['auth_ntlm']: config['auth_ntlm'] = 0 config.write_proxyconf() info['auth_ntlm'] = True # use google cache if form.has_key('try_google'): if not config['try_google']: config['try_google'] = 1 config.write_proxyconf() info['try_google'] = True elif config['try_google']: config['try_google'] = 0 config.write_proxyconf() info['try_google'] = True # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) elif config['parentproxy']: config['parentproxy'] = '' config.write_proxyconf() info['parentproxy'] = True # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) elif config['parentproxyport'] != 3128: config['parentproxyport'] = 3128 config.write_proxyconf() info['parentproxyport'] = True # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) elif config['parentproxyuser']: config['parentproxyuser'] = '' config.write_proxyconf() info['parentproxyuser'] = True # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') # ignore dummy values if val!=u'__dummy__': _form_parentproxypass(base64.encodestring(val).strip()) elif config['parentproxypass']: config['parentproxypass'] = '' config.write_proxyconf() info['parentproxypass'] = True # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) elif config['timeout']!=30: config['timeout'] = 30 config.write_proxyconf() info['timeout'] = True # filter modules _form_filtermodules(form) # allowed hosts if form.has_key('addallowed') and form.has_key('newallowed'): _form_addallowed(_getval(form, 'newallowed').strip()) elif form.has_key('delallowed') and form.has_key('allowedhosts'): _form_delallowed(form) # no filter hosts if form.has_key('addnofilter') and form.has_key('newnofilter'): _form_addnofilter(_getval(form, 'newnofilter').strip()) elif form.has_key('delnofilter') and form.has_key('nofilterhosts'): _form_delnofilter(form) return res[0]
|
config['parentproxypass'] = ''
|
config['parentproxypass'] = u''
|
def _exec_form (form, lang): # reset info/error global filterenabled, filterdisabled filterenabled = u"" filterdisabled = u"" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) elif config['port']!=8080: _form_proxyport(8080) # ssl server port if form.has_key('sslport'): _form_sslport(_getval(form, 'sslport')) elif config['sslport']!=8443: _form_sslport(8443) # ssl gateway if form.has_key('sslgateway'): _form_sslgateway(1) else: _form_sslgateway(0) # admin user if form.has_key('adminuser'): _form_adminuser(_getval(form, 'adminuser').strip(), res) elif config['adminuser']: config['adminuser'] = u'' config.write_proxyconf() info['adminuser'] = True # admin pass if form.has_key('adminpass'): val = _getval(form, 'adminpass') # ignore dummy values if val!=u'__dummy__': _form_adminpass(base64.encodestring(val).strip(), res) elif config['adminpass']: config['adminpass'] =u '' config.write_proxyconf() info['adminpass'] = True if config['adminuser']: res[0] = 401 # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) elif config['proxyuser']: config['proxyuser'] = '' config.write_proxyconf() info['proxyuser'] = True # proxy pass if form.has_key('proxypass'): val = _getval(form, 'proxypass') # ignore dummy values if val!=u'__dummy__': _form_proxypass(base64.encodestring(val).strip(), res) elif config['proxypass']: config['proxypass'] = '' config.write_proxyconf() info['proxypass'] = True # ntlm authentication if form.has_key('auth_ntlm'): if not config['auth_ntlm']: config['auth_ntlm'] = 1 config.write_proxyconf() info['auth_ntlm'] = True elif config['auth_ntlm']: config['auth_ntlm'] = 0 config.write_proxyconf() info['auth_ntlm'] = True # use google cache if form.has_key('try_google'): if not config['try_google']: config['try_google'] = 1 config.write_proxyconf() info['try_google'] = True elif config['try_google']: config['try_google'] = 0 config.write_proxyconf() info['try_google'] = True # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) elif config['parentproxy']: config['parentproxy'] = '' config.write_proxyconf() info['parentproxy'] = True # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) elif config['parentproxyport'] != 3128: config['parentproxyport'] = 3128 config.write_proxyconf() info['parentproxyport'] = True # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) elif config['parentproxyuser']: config['parentproxyuser'] = '' config.write_proxyconf() info['parentproxyuser'] = True # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') # ignore dummy values if val!=u'__dummy__': _form_parentproxypass(base64.encodestring(val).strip()) elif config['parentproxypass']: config['parentproxypass'] = '' config.write_proxyconf() info['parentproxypass'] = True # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) elif config['timeout']!=30: config['timeout'] = 30 config.write_proxyconf() info['timeout'] = True # filter modules _form_filtermodules(form) # allowed hosts if form.has_key('addallowed') and form.has_key('newallowed'): _form_addallowed(_getval(form, 'newallowed').strip()) elif form.has_key('delallowed') and form.has_key('allowedhosts'): _form_delallowed(form) # no filter hosts if form.has_key('addnofilter') and form.has_key('newnofilter'): _form_addnofilter(_getval(form, 'newnofilter').strip()) elif form.has_key('delnofilter') and form.has_key('nofilterhosts'): _form_delnofilter(form) return res[0]
|
assert self.server, "%s server_content had no server" % self
|
assert self.server, "%s server_content(%s) had no server" % \ (self, data)
|
def server_content (self, data): """The server received some content. Write it to the client.""" assert self.server, "%s server_content had no server" % self if data: self.write(data)
|
wc.proxy.make_timer(1, reload_config)
|
import wc.proxy.timer wc.proxy.timer.make_timer(1, reload_config)
|
def sighup_reload_config (signum, frame): """ Support reload on posix systems. Store timer for reloading configuration data. """ global pending_reload if not pending_reload: pending_reload = True wc.proxy.make_timer(1, reload_config)
|
bk.log.error(wc.LOG_FILTER, "Empty image data found at %r (%r)", url, buf.getvalue()) else: attrs['imgsize_blocked'] = \
|
return '' attrs['imgsize_blocked'] = \
|
def finish (self, data, **attrs): # note: if attrs['blocked'] is True, then the blockdata is # already sent out if not attrs.has_key('imgsize_buf'): # do not block this image return data if attrs['imgsize_blocked']: # block this image return '' buf = attrs['imgsize_buf'] if buf.closed: return data buf.write(data) url = attrs['url'] pos = buf.tell() if pos <= 0: bk.log.error(wc.LOG_FILTER, "Empty image data found at %r (%r)", url, buf.getvalue()) else: attrs['imgsize_blocked'] = \ not self.check_sizes(buf, attrs['imgsize_sizes'], url, finish=True) data = buf.getvalue() buf.close() if attrs['imgsize_blocked']: return self.blockdata return data
|
if self.state in ('connect', 'client') and (method!='CONNECT'):
|
if self.state in ('connect', 'client') and \ (self.client and self.client.method!='CONNECT'):
|
def process_read (self): if self.state in ('connect', 'client') and (method!='CONNECT'): # with http pipelining the client could send more data after # the initial request error(PROXY, 'server received data in %s state', self.state) error(PROXY, '%r', self.read()) return
|
self.base_url = strip_quotes(attrs['href'])
|
self.base_url = attrs['href'] if not urllib.splittype(self.base_url)[0]: self.base_url = "%s://%s" % \ (urllib.splittype(self.url)[0], self.base_url)
|
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 %r", tag) tag = check_spelling(tag, self.url) if self.stackcount: if self.stackcount[-1][0]==tag: self.stackcount[-1][1] += 1 if self.state[0]=='wait': self.waitbuf.append([STARTTAG, tag, attrs]) return if tag=="meta": if attrs.get('http-equiv', '').lower() =='content-rating': rating = resolve_html_entities(attrs.get('content', '')) # note: always put this in the cache, since this overrides # any http header setting, and page content changes more # often rating_add(self.url, rating_parse(rating)) elif tag=="body": if self.ratings: # headers finished, check rating data for rule in self.ratings: msg = rating_allow(self.url, rule) if msg: raise FilterRating(msg) self.ratings = [] elif tag=="base" and attrs.has_key('href'): self.base_url = strip_quotes(attrs['href']) self._debug("using base url %r", self.base_url) # search for and prevent known security flaws in HTML self.security.scan_start_tag(tag, attrs, self) # look for filter rules which apply self.filterStartElement(tag, attrs) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.javascript: self.buf2data()
|
host = stripsite(url)[0]
|
def jsScriptSrc (self, url, language): """Start a background download for <script src=""> tags""" assert self.state[0]=='parse', "non-parse state %s" % self.state ver = get_js_ver(language) if self.base_url: url = urlparse.urljoin(self.base_url, url) else: url = urlparse.urljoin(self.url, url) # unquote and norm url = url_norm(url) self.state = ('wait', url) self.waited = 1 self.js_src = True self.js_client = HttpProxyClient(self.jsScriptData, (url, ver)) host = stripsite(url)[0] headers = get_wc_client_headers(host) # note: some javascript servers do not specify content encoding # so only accept non-encoded content here headers['Accept-Encoding'] = 'identity\r' ClientServerMatchmaker(self.js_client, "GET %s HTTP/1.0" % url_quote(url), # request headers, '', # content mime="application/x-javascript", )
|
|
<description>bla </description>
|
<description><![CDATA[bla ]]></description>
|
def testRdfDescription (self): self.filt("""<?xml version="1.0" encoding="ISO-8859-1"?>
|
<description>bla </description>
|
<description><![CDATA[bla ]]></description>
|
def testRdfDescription2 (self): self.filt("""<?xml version="1.0" encoding="ISO-8859-1"?>
|
<description>bla <img></description>
|
<description><![CDATA[bla <img>]]></description>
|
def testRdfDescription3 (self): self.filt("""<?xml version="1.0" encoding="ISO-8859-1"?>
|
addr = (socket.gethostbyname('localhost'), port)
|
def proxyrequest2 (url, port): """raw request with PyOpenSSL""" from wc.proxy.Dispatcher import create_socket from wc.proxy.ssl import get_clientctx parts = urlparse.urlsplit(url) host = parts[1] #path = urlparse.urlunsplit(('', '', parts[2], parts[3], parts[4])) sock = create_socket(socket.AF_INET, socket.SOCK_STREAM) sslctx = get_clientctx('localconfig') import OpenSSL.SSL sock = OpenSSL.SSL.Connection(sslctx, sock) addr = (socket.gethostbyname('localhost'), port) sock.set_connect_state() sock.connect(addr) sock.do_handshake() sock.write('GET %s HTTP/1.1\r\n' % url) sock.write('Host: %s\r\n' % host) sock.write('\r\n') while True: try: print repr(sock.read(80)) except SSL.ZeroReturnError: # finished break sock.shutdown() sock.close()
|
|
sock.connect(addr) sock.do_handshake() sock.write('GET %s HTTP/1.1\r\n' % url) sock.write('Host: %s\r\n' % host) sock.write('\r\n') while True: try: print repr(sock.read(80)) except SSL.ZeroReturnError:
|
while True: try: sock.do_handshake() break except OpenSSL.SSL.WantReadError: time.sleep(0.2) except OpenSSL.SSL.WantWriteError: time.sleep(0.2) sock_write(sock, 'GET %s HTTP/1.1\r\n' % url) sock_write(sock, 'Host: %s\r\n' % host) sock_write(sock, '\r\n') while True: try: want_read(sock) except OpenSSL.SSL.ZeroReturnError:
|
def proxyrequest2 (url, port): """raw request with PyOpenSSL""" from wc.proxy.Dispatcher import create_socket from wc.proxy.ssl import get_clientctx parts = urlparse.urlsplit(url) host = parts[1] #path = urlparse.urlunsplit(('', '', parts[2], parts[3], parts[4])) sock = create_socket(socket.AF_INET, socket.SOCK_STREAM) sslctx = get_clientctx('localconfig') import OpenSSL.SSL sock = OpenSSL.SSL.Connection(sslctx, sock) addr = (socket.gethostbyname('localhost'), port) sock.set_connect_state() sock.connect(addr) sock.do_handshake() sock.write('GET %s HTTP/1.1\r\n' % url) sock.write('Host: %s\r\n' % host) sock.write('\r\n') while True: try: print repr(sock.read(80)) except SSL.ZeroReturnError: # finished break sock.shutdown() sock.close()
|
port = wc.configuration.config['port'] sslport = wc.configuration.config['sslport']
|
sslport = 443 print "Get %s (port %d)" % (sys.argv[1], sslport)
|
def _main (): """ USAGE: test/run.sh test/getssl.py <https url> """ if len(sys.argv) != 2: print _main.__doc__.strip() sys.exit(1) #request1(sys.argv[1]) import wc.configuration wc.configuration.config = wc.configuration.init("localconfig") port = wc.configuration.config['port'] sslport = wc.configuration.config['sslport'] #print "Get %s from localhost:%d" % (sys.argv[1], sslport) #proxyrequest1(sys.argv[1], sslport) #proxyrequest2(sys.argv[1], sslport) #proxyrequest3(sys.argv[1], sslport) print "Get %s from localhost:%d" % (sys.argv[1], port) proxyrequest4(sys.argv[1], port)
|
proxyrequest2(sys.argv[1], sslport)
|
def _main (): """ USAGE: test/run.sh test/getssl.py <https url> """ if len(sys.argv) != 2: print _main.__doc__.strip() sys.exit(1) #request1(sys.argv[1]) import wc.configuration wc.configuration.config = wc.configuration.init("localconfig") port = wc.configuration.config['port'] sslport = wc.configuration.config['sslport'] #print "Get %s from localhost:%d" % (sys.argv[1], sslport) #proxyrequest1(sys.argv[1], sslport) #proxyrequest2(sys.argv[1], sslport) #proxyrequest3(sys.argv[1], sslport) print "Get %s from localhost:%d" % (sys.argv[1], port) proxyrequest4(sys.argv[1], port)
|
|
print "Get %s from localhost:%d" % (sys.argv[1], port) proxyrequest4(sys.argv[1], port)
|
def _main (): """ USAGE: test/run.sh test/getssl.py <https url> """ if len(sys.argv) != 2: print _main.__doc__.strip() sys.exit(1) #request1(sys.argv[1]) import wc.configuration wc.configuration.config = wc.configuration.init("localconfig") port = wc.configuration.config['port'] sslport = wc.configuration.config['sslport'] #print "Get %s from localhost:%d" % (sys.argv[1], sslport) #proxyrequest1(sys.argv[1], sslport) #proxyrequest2(sys.argv[1], sslport) #proxyrequest3(sys.argv[1], sslport) print "Get %s from localhost:%d" % (sys.argv[1], port) proxyrequest4(sys.argv[1], port)
|
|
p = wc.configuration.ZapperParser(fullname, wconfig, compile_data=False)
|
p = wc.configuration.ZapperParser(fullname, compile_data=False)
|
def update_filter (wconfig, dryrun=False, log=None): """Update the given configuration object with .zap files found at baseurl. If dryrun is True, only print out the changes but do nothing throws IOError on error """ print >> log, _("updating filters"), "..." chg = False baseurl = wconfig['baseurl']+"filter/" url = baseurl+"filter-md5sums.txt" try: page = open_url(url) except IOError, msg: print >> log, _("error fetching %s") % url, msg print >> log, "...", _("done") return chg # remember all local config files filemap = {} for filename in wc.configuration.filterconf_files(wconfig.filterdir): filemap[os.path.basename(filename)] = filename # read md5sums for line in page.read().splitlines(): if "<" in line: print >> log, _("error fetching %s") % url print >> log, "...", _("done") return chg if not line: continue md5sum, filename = line.split() assert filename.endswith('.zap') fullname = os.path.join(wconfig.configdir, filename) # compare checksums if filemap.has_key(filename): f = file(fullname) data = f.read() digest = list(md5.new(data).digest()) f.close() digest = "".join([ "%0.2x"%ord(c) for c in digest ]) if digest == md5sum: print >> log, \ _("filter %s not changed, ignoring") % filename continue print >> log, _("updating filter %s") % filename else: print >> log, _("adding new filter %s") % filename # parse new filter url = baseurl+filename page = open_url(url) p = wc.configuration.ZapperParser(fullname, wconfig, compile_data=False) p.parse(fp=page) page.close() if wconfig.merge_folder(p.folder, dryrun=dryrun, log=log): chg = True url = baseurl+"extern-md5sums.txt" try: page = open_url(url) except IOError, msg: print >> log, _("error fetching %s:") % url, msg print >> log, "...", _("done") return chg lines = page.read().splitlines() page.close() for line in lines: if "<" in line: print >> log, _("error fetching %s:") % url, \ _("invalid content") print >> log, "...", _("done") return chg if not line: continue md5sum, filename = line.split() # XXX UNIX-generated md5sum filenames with subdirs are not portable fullname = os.path.join(wconfig.configdir, filename) # compare checksums if os.path.exists(fullname): f = file(fullname) data = f.read() digest = list(md5.new(data).digest()) f.close() digest = "".join([ "%0.2x"%ord(c) for c in digest ]) if digest == md5sum: print >> log, \ _("extern filter %s not changed, ignoring")%filename continue print >> log, _("updating extern filter %s") % filename else: print >> log, _("adding new extern filter %s") % filename chg = True if not dryrun: url = baseurl+filename try: page = open_url(url) except IOError, msg: print >> log, _("error fetching %s:") % url, msg continue data = page.read() if not data: print >> log, _("error fetching %s:") % url, \ _("got no data") continue f = file(fullname, 'wb') f.write(data) f.close() print >> log, "...", _("done") return chg
|
self.config['nofilterhosts'] = ip.strhosts2map(strhosts)
|
self.config['nofilterhosts'] = strhosts.split(",")
|
def start_element (self, name, attrs): if name=='webcleaner': for key,val in attrs.items(): self.config[key] = val for key in ('port', 'sslport', 'parentproxyport', 'timeout', 'auth_ntlm', 'colorize', 'development', 'try_google', 'sslgateway',): self.config[key] = int(self.config[key]) if self.config['nofilterhosts'] is not None: strhosts = self.config['nofilterhosts'] self.config['nofilterhosts'] = ip.strhosts2map(strhosts) else: self.config['nofilterhosts'] = [Set(), []] if self.config['allowedhosts'] is not None: strhosts = self.config['allowedhosts'] self.config['allowedhosts'] = ip.strhosts2map(strhosts) else: self.config['allowedhosts'] = [Set(), []] elif name=='filter': debug(FILTER, "enable filter module %s", attrs['name']) self.config['filters'].append(attrs['name'])
|
self.config['nofilterhosts'] = [Set(), []]
|
self.config['nofilterhosts'] = []
|
def start_element (self, name, attrs): if name=='webcleaner': for key,val in attrs.items(): self.config[key] = val for key in ('port', 'sslport', 'parentproxyport', 'timeout', 'auth_ntlm', 'colorize', 'development', 'try_google', 'sslgateway',): self.config[key] = int(self.config[key]) if self.config['nofilterhosts'] is not None: strhosts = self.config['nofilterhosts'] self.config['nofilterhosts'] = ip.strhosts2map(strhosts) else: self.config['nofilterhosts'] = [Set(), []] if self.config['allowedhosts'] is not None: strhosts = self.config['allowedhosts'] self.config['allowedhosts'] = ip.strhosts2map(strhosts) else: self.config['allowedhosts'] = [Set(), []] elif name=='filter': debug(FILTER, "enable filter module %s", attrs['name']) self.config['filters'].append(attrs['name'])
|
auth = ", ".join(get_challenges())
|
auth = ", ".join(wc.proxy.auth.get_challenges())
|
def handle_local (self, is_public_doc=False): """handle local request by delegating it to the web configuration""" assert self.state=='receive' debug(PROXY, '%s handle_local', self) # reject invalid methods if self.method not in ['GET', 'POST', 'HEAD']: self.error(403, wc.i18n._("Invalid Method")) return # check admin pass if not is_public_doc and wc.config["adminuser"]: creds = wc.proxy.auth.get_header_credentials(self.headers, 'Authorization') if not creds: auth = ", ".join(wc.proxy.auth.get_challenges()) self.error(401, wc.i18n._("Authentication Required"), auth=auth) return if 'NTLM' in creds: if creds['NTLM'][0]['type']==wc.proxy.auth.ntlm.NTLMSSP_NEGOTIATE: auth = ",".join(creds['NTLM'][0]) self.error(401, wc.i18n._("Authentication Required"), auth=auth) return # XXX the data=None argument should hold POST data if not wc.proxy.auth.check_credentials(creds, username=wc.config['adminuser'], password_b64=wc.config['adminpass'], uri=wc.proxy.auth.get_auth_uri(self.url), method=self.method, data=None): warn(AUTH, "Bad authentication from %s", self.addr[0]) auth = ", ".join(get_challenges()) self.error(401, wc.i18n._("Authentication Required"), auth=auth) return # get cgi form data form = self.get_form_data() # this object will call server_connected at some point wc.webgui.WebConfig(self, self.url, form, self.protocol, self.headers)
|
p.feed(data) except xml.sax.SAXException, msg:
|
p.feed(data2) except xml.sax.SAXException: evalue = sys.exc_info()[1]
|
def filter (self, data, attrs): """ Feed data to XML parser. """ if 'xmlrewriter_parser' not in attrs: return data p = attrs['xmlrewriter_parser'] f = attrs['xmlrewriter_filter'] try: p.feed(data) except xml.sax.SAXException, msg: wc.log.error(wc.LOG_FILTER, "XML filter error at %s: %s", attrs['url'], str(msg)) return data return f.getoutput()
|
attrs['url'], str(msg))
|
attrs['url'], str(evalue))
|
def filter (self, data, attrs): """ Feed data to XML parser. """ if 'xmlrewriter_parser' not in attrs: return data p = attrs['xmlrewriter_parser'] f = attrs['xmlrewriter_filter'] try: p.feed(data) except xml.sax.SAXException, msg: wc.log.error(wc.LOG_FILTER, "XML filter error at %s: %s", attrs['url'], str(msg)) return data return f.getoutput()
|
wait => Fetching additionally data in the background. Feeding new data in wait state raises a FilterException. When finished, the buffers look like data [---------|--------][-------][----------]
|
wait => this filter (or a recursive HtmlFilter used by javascript) is fetching additionally data in the background. Flushing data in wait state raises a FilterException. When finished for <script src="">, the buffers look like fed data chunks (example): [---------|--------][-------][----------][--...
|
def getAttrs (self, headers, url): """We need a separate filter instance for stateful filtering""" rewrites = [] opts = {'comments': 1, 'javascript': 0} for rule in self.rules: if not rule.appliesTo(url): continue if rule.get_name()=='rewrite': rewrites.append(rule) elif rule.get_name()=='nocomments': opts['comments'] = 0 elif rule.get_name()=='javascript': opts['javascript'] = 1 # generate the HTML filter return {'filter': HtmlFilter(rewrites, url, **opts)}
|
waitbuf [--------] inbuf [-------------- ...
|
waitbuf: [--------] inbuf: [-------------- ... When finished with script data, the buffers look like XXX
|
def getAttrs (self, headers, url): """We need a separate filter instance for stateful filtering""" rewrites = [] opts = {'comments': 1, 'javascript': 0} for rule in self.rules: if not rule.appliesTo(url): continue if rule.get_name()=='rewrite': rewrites.append(rule) elif rule.get_name()=='nocomments': opts['comments'] = 0 elif rule.get_name()=='javascript': opts['javascript'] = 1 # generate the HTML filter return {'filter': HtmlFilter(rewrites, url, **opts)}
|
self.javascript = opts['javascript']
|
self.level = opts.get('level', 0) self.state = 'parse' self.waited = 0 self.rulestack = []
|
def __init__ (self, rules, url, **opts): if wc.config['showerrors']: self.error = self._error self.warning = self._warning self.fatalError = self._fatalError HtmlParser.__init__(self) self.rules = rules self.comments = opts['comments'] self.javascript = opts['javascript'] self.outbuf = StringIO() self.inbuf = StringIO() self.waitbuf = [] self.state = 'parse' self.script = '' self.waited = 0 self.rulestack = [] self.buf = [] self.url = url or "unknown" if self.javascript: self.jsEnv = jslib.new_jsenv() self.output_counter = 0 self.popup_counter = 0
|
self.state = 'parse' self.script = '' self.waited = 0 self.rulestack = []
|
def __init__ (self, rules, url, **opts): if wc.config['showerrors']: self.error = self._error self.warning = self._warning self.fatalError = self._fatalError HtmlParser.__init__(self) self.rules = rules self.comments = opts['comments'] self.javascript = opts['javascript'] self.outbuf = StringIO() self.inbuf = StringIO() self.waitbuf = [] self.state = 'parse' self.script = '' self.waited = 0 self.rulestack = [] self.buf = [] self.url = url or "unknown" if self.javascript: self.jsEnv = jslib.new_jsenv() self.output_counter = 0 self.popup_counter = 0
|
|
if self.javascript: self.jsEnv = jslib.new_jsenv() self.output_counter = 0 self.popup_counter = 0
|
self.js_filter = opts['javascript'] self.js_html = None self.js_src = 0 self.js_script = '' if self.js_filter: self.js_env = jslib.new_jsenv() self.js_output = 0 self.js_popup = 0
|
def __init__ (self, rules, url, **opts): if wc.config['showerrors']: self.error = self._error self.warning = self._warning self.fatalError = self._fatalError HtmlParser.__init__(self) self.rules = rules self.comments = opts['comments'] self.javascript = opts['javascript'] self.outbuf = StringIO() self.inbuf = StringIO() self.waitbuf = [] self.state = 'parse' self.script = '' self.waited = 0 self.rulestack = [] self.buf = [] self.url = url or "unknown" if self.javascript: self.jsEnv = jslib.new_jsenv() self.output_counter = 0 self.popup_counter = 0
|
return "<HtmlFilter with rulestack %s>" % self.rulestack
|
return "<HtmlFilter[%d] %s>" % (self.level, self.state) def _debug (self, level, *args): debug(level, "HtmlFilter[%d,%s]:"%(self.level,self.state), *args) def _debugbuf (self): """print debugging information about buffer status""" self._debug(NIGHTMARE, "self.buf", `self.buf`) self._debug(NIGHTMARE, "self.waitbuf", `self.waitbuf`) self._debug(NIGHTMARE, "self.inbuf", `self.inbuf.getvalue()`) self._debug(NIGHTMARE, "self.outbuf", `self.outbuf.getvalue()`)
|
def __repr__ (self): return "<HtmlFilter with rulestack %s>" % self.rulestack
|
debug(NIGHTMARE, "HtmlFilter: feed", `data`)
|
self._debug(NIGHTMARE, "feed", `data`)
|
def feed (self, data): if self.state=='parse': if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': return data = self.inbuf.getvalue() self.inbuf.close() self.inbuf = StringIO() if data: debug(NIGHTMARE, "HtmlFilter: feed", `data`) HtmlParser.feed(self, data) else: self.inbuf.write(data)
|
raise FilterException("HtmlFilter: still waiting for data")
|
raise FilterException("HtmlFilter[%d]: still waiting for data"%self.level)
|
def flush (self): if self.state=='wait': raise FilterException("HtmlFilter: still waiting for data") HtmlParser.flush(self)
|
self.characters(item[1])
|
self._data(item[1])
|
def replay (self, waitbuf): """call the handler functions again with buffer data""" for item in waitbuf: if item[0]==DATA: self.characters(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])
|
debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`))
|
self._debug(NIGHTMARE, "matched rule %s on tag %s" % (`rule.title`, `tag`))
|
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" # give'em a chance to replace more than one attribute if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item continue else: break else: debug(NIGHTMARE, "HtmlFilter: 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.javascript: # 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.javascript: self.buf2data()
|
debug(NIGHTMARE, "HtmlFilter: put on buffer")
|
self._debug(NIGHTMARE, "put on buffer")
|
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" # give'em a chance to replace more than one attribute if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item continue else: break else: debug(NIGHTMARE, "HtmlFilter: 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.javascript: # 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.javascript: self.buf2data()
|
elif self.javascript:
|
elif self.js_filter:
|
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" # give'em a chance to replace more than one attribute if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item continue else: break else: debug(NIGHTMARE, "HtmlFilter: 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.javascript: # 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.javascript: self.buf2data()
|
if not self.rulestack and not self.javascript:
|
if not self.rulestack and not self.js_filter:
|
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): debug(NIGHTMARE, "HtmlFilter: matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" # give'em a chance to replace more than one attribute if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item continue else: break else: debug(NIGHTMARE, "HtmlFilter: 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.javascript: # 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.javascript: self.buf2data()
|
if self.javascript and tag=='script': self.jsEndElement(item) else: self.buf.append(item)
|
if self.js_filter and tag=='script': return self.jsEndElement(item) self.buf.append(item)
|
def endElement (self, tag): """We know the following: if a rule matches, it must be the one on the top of the stack. So we look only at the top rule.
|
self.jsEnv.attachListener(self)
|
self.js_env.attachListener(self)
|
def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" val = resolve_html_entities(attrs[name]) if not val: return self.jsEnv.attachListener(self) try: self.jsEnv.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.jsEnv.detachListener(self) res = self.popup_counter self.popup_counter = 0 return res
|
self.jsEnv.executeScriptAsFunction(val, 0.0)
|
self.js_env.executeScriptAsFunction(val, 0.0)
|
def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" val = resolve_html_entities(attrs[name]) if not val: return self.jsEnv.attachListener(self) try: self.jsEnv.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.jsEnv.detachListener(self) res = self.popup_counter self.popup_counter = 0 return res
|
self.jsEnv.detachListener(self)
|
self.js_env.detachListener(self)
|
def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" val = resolve_html_entities(attrs[name]) if not val: return self.jsEnv.attachListener(self) try: self.jsEnv.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.jsEnv.detachListener(self) res = self.popup_counter self.popup_counter = 0 return res
|
debug(HURT_ME_PLENTY, "JS: jsForm", `name`, `action`, `target`) self.jsEnv.addForm(name, action, target)
|
self._debug(HURT_ME_PLENTY, "jsForm", `name`, `action`, `target`) self.js_env.addForm(name, action, target)
|
def jsForm (self, name, action, target): """when hitting a (named) form, notify the JS engine about that""" if not name: return debug(HURT_ME_PLENTY, "JS: jsForm", `name`, `action`, `target`) self.jsEnv.addForm(name, action, target)
|
if not self.script: print >> sys.stderr, "empty JS src", url
|
if not self.js_script: print >> sys.stderr, "HtmlFilter[%d]: empty JS src"%self.level, 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.script: print >> sys.stderr, "empty JS src", url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) self.buf.append([DATA, "<!--\n%s\n//-->"%self.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.state = 'parse' self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`) else: debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
|
self.buf.append([DATA, "<!--\n%s\n//-->"%self.script])
|
if self.js_script.find("<!--")==-1: script = "<!--\n%s\n//-->"%self.js_script else: script = self.js_script self.buf.append([DATA, script])
|
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.script: print >> sys.stderr, "empty JS src", url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) self.buf.append([DATA, "<!--\n%s\n//-->"%self.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.state = 'parse' self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`) else: debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
|
self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`)
|
self.js_script = '' self._debug(NIGHTMARE, "switching back to parse with") self._debugbuf()
|
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.script: print >> sys.stderr, "empty JS src", url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) self.buf.append([DATA, "<!--\n%s\n//-->"%self.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.state = 'parse' self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`) else: debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
|
debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
|
self._debug(HURT_ME_PLENTY, "JS read", 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.state=='wait' if data is None: if not self.script: print >> sys.stderr, "empty JS src", url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) self.buf.append([DATA, "<!--\n%s\n//-->"%self.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.state = 'parse' self.script = '' debug(NIGHTMARE, "HtmlFilter: switching back to parse with") debug(NIGHTMARE, "HtmlFilter: self.buf", `self.buf`) debug(NIGHTMARE, "HtmlFilter: self.waitbuf", `self.waitbuf`) debug(NIGHTMARE, "HtmlFilter: self.inbuf", `self.inbuf.getvalue()`) else: debug(HURT_ME_PLENTY, "JS: read", len(data), "<=", url) self.script += data
|
debug(HURT_ME_PLENTY, "JS: jsScriptSrc", url, ver)
|
self._debug(HURT_ME_PLENTY, "JS jsScriptSrc", url, ver)
|
def jsScriptSrc (self, url, language): """Start a background download for <script src=""> tags""" assert self.state=='parse' ver = 0.0 if language: mo = re.search(r'(?i)javascript(?P<num>\d\.\d)', language) if mo: ver = float(mo.group('num')) url = urlparse.urljoin(self.url, url) debug(HURT_ME_PLENTY, "JS: jsScriptSrc", url, ver) self.state = 'wait' client = HttpProxyClient(self.jsScriptData, (url, ver)) ClientServerMatchmaker(client, "GET %s HTTP/1.1" % url, #request {}, #headers '', #content {'nofilter': None}, 'identity', # compress ) self.waited = "True"
|
def jsScript (self, script, ver): """execute given script with javascript version ver return True if the script generates any output, else False""" self.output_counter = 0 self.jsEnv.attachListener(self) self.jsfilter = HtmlFilter(self.rules, self.url, comments=self.comments, javascript=self.javascript) self.jsEnv.executeScript(script, ver) self.jsEnv.detachListener(self) if self.output_counter: self.jsfilter.flush() self.outbuf.write(self.jsfilter.flushbuf()) self.buf[-2:-2] = self.jsfilter.buf self.rulestack += self.jsfilter.rulestack self.jsfilter = None return self.popup_counter + self.output_counter def processData (self, data):
|
def jsScript (self, script, ver, item): """execute given script with javascript version ver""" self._debug(NIGHTMARE, "JS: jsScript", ver, `script`) assert self.state == 'parse' assert len(self.buf) >= 2 self.js_output = 0 self.js_env.attachListener(self) self.js_html = HtmlFilter(self.rules, self.url, comments=self.comments, javascript=self.js_filter, level=self.level+1) self.js_env.executeScript(script, ver) self.js_env.detachListener(self) self.jsEndScript(item) def jsEndScript (self, item): self._debug(NIGHTMARE, "JS: endScript") assert len(self.buf) >= 2 if self.js_output: try: self.js_html.feed('') self.js_html.flush() except FilterException: self.state = 'wait' self.waited = "True" make_timer(0.1, lambda : HtmlFilter.jsEndScript(self, 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: del self.buf[-1] del self.buf[-1] else: self.buf.append(item) self._debug(NIGHTMARE, "JS: switching back to parse with") self._debugbuf() self.state = 'parse' def jsProcessData (self, data): """process data produced by document.write() JavaScript""" self._debug(NIGHTMARE, "JS: document.write", `data`) self.js_output += 1
|
def jsScript (self, script, ver): """execute given script with javascript version ver return True if the script generates any output, else False""" #debug(NIGHTMARE, "JS: jsScript", ver, `script`) self.output_counter = 0 self.jsEnv.attachListener(self) self.jsfilter = HtmlFilter(self.rules, self.url, comments=self.comments, javascript=self.javascript) self.jsEnv.executeScript(script, ver) self.jsEnv.detachListener(self) if self.output_counter: self.jsfilter.flush() self.outbuf.write(self.jsfilter.flushbuf()) self.buf[-2:-2] = self.jsfilter.buf self.rulestack += self.jsfilter.rulestack self.jsfilter = None return self.popup_counter + self.output_counter
|
self.output_counter += 1 self.jsfilter.feed(data) def processPopup (self): self.popup_counter += 1
|
self.js_html.feed(data) def jsProcessPopup (self): """process javascript popup""" self._debug(NIGHTMARE, "JS: popup") self.js_popup += 1
|
def processData (self, data): # parse recursively self.output_counter += 1 self.jsfilter.feed(data)
|
if self.buf[-1][0]!=DATA: return if not (self.buf[-2][0]==STARTTAG and \ self.buf[-2][1]=='script'):
|
if self.js_src: del self.buf[-1] if self.buf[-3][0]==STARTTAG and self.buf[-3][1]=='script': del self.buf[-1] if len(self.buf)<2 or self.buf[-1][0]==DATA or \ self.buf[-2][0]!=STARTTAG or self.buf[-2][1]!='script':
|
def jsEndElement (self, item): """parse generated html for scripts return True if the script generates any output, else False""" if len(self.buf)<2: return #assert len(self.buf)>=2 if self.buf[-1][0]!=DATA: # no data means we had <script></script> return if not (self.buf[-2][0]==STARTTAG and \ self.buf[-2][1]=='script'): # there was a <script src="..."> already return # get script data script = self.buf[-1][1].strip() # remove html comments if script.startswith("<!--"): i = script.find('\n') if i==-1: script = script[4:] else: script = script[(i+1):] if script.endswith("-->"): script = script[:-3] if not script: # again, ignore an empty script del self.buf[-1] del self.buf[-1] return if self.jsScript(script, 0.0): del self.buf[-1] del self.buf[-1] return self.buf.append(item)
|
return if self.jsScript(script, 0.0): del self.buf[-1] del self.buf[-1] return self.buf.append(item)
|
else: self.jsScript(script, 0.0, item)
|
def jsEndElement (self, item): """parse generated html for scripts return True if the script generates any output, else False""" if len(self.buf)<2: return #assert len(self.buf)>=2 if self.buf[-1][0]!=DATA: # no data means we had <script></script> return if not (self.buf[-2][0]==STARTTAG and \ self.buf[-2][1]=='script'): # there was a <script src="..."> already return # get script data script = self.buf[-1][1].strip() # remove html comments if script.startswith("<!--"): i = script.find('\n') if i==-1: script = script[4:] else: script = script[(i+1):] if script.endswith("-->"): script = script[:-3] if not script: # again, ignore an empty script del self.buf[-1] del self.buf[-1] return if self.jsScript(script, 0.0): del self.buf[-1] del self.buf[-1] return self.buf.append(item)
|
values[category.name] = {}
|
def _reset_values (): for category in categories: values[category.name] = {} if category.iterable: for value in category.values: values[category.name][value] = False else: values[category.name] = None rating_modified.clear()
|
|
values[category.name][value] = False
|
values[category.name][value] = value=='none'
|
def _reset_values (): for category in categories: values[category.name] = {} if category.iterable: for value in category.values: values[category.name][value] = False else: values[category.name] = None rating_modified.clear()
|
values[category.name] = None
|
values[category.name] = ""
|
def _reset_values (): for category in categories: values[category.name] = {} if category.iterable: for value in category.values: values[category.name][value] = False else: values[category.name] = None rating_modified.clear()
|
for key, value in _get_prefix_vals(form, 'category_'): category = _get_category(key)
|
for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname)
|
def _form_ratings (form): """Check category value validity""" for key, value in _get_prefix_vals(form, 'category_'): category = _get_category(key) if category is None: # unknown category error['categoryvalue'] = True return False if not category.is_valid_value(value): error['categoryvalue'] = True return False values[key] = value return True
|
if not category.is_valid_value(value):
|
if not category.valid_value(value):
|
def _form_ratings (form): """Check category value validity""" for key, value in _get_prefix_vals(form, 'category_'): category = _get_category(key) if category is None: # unknown category error['categoryvalue'] = True return False if not category.is_valid_value(value): error['categoryvalue'] = True return False values[key] = value return True
|
values[key] = value
|
if category.iterable: values[catname]['none'] = False values[catname][value] = True else: values[catname] = value
|
def _form_ratings (form): """Check category value validity""" for key, value in _get_prefix_vals(form, 'category_'): category = _get_category(key) if category is None: # unknown category error['categoryvalue'] = True return False if not category.is_valid_value(value): error['categoryvalue'] = True return False values[key] = value return True
|
logfile = os.path.join(confdir, "logging.conf")
|
logfile = os.path.join(wc.ConfigDir, "logging.conf")
|
def do_install (): """ Install shortcuts and NT service. """ fix_configdata() import wc # initialize logging logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name) install_shortcuts() install_certificates() install_service() stop_service() install_adminpassword() start_service() open_browser_config()
|
logfile = os.path.join(confdir, "logging.conf")
|
logfile = os.path.join(wc.ConfigDir, "logging.conf")
|
def do_remove (): """ Stop and remove the installed NT service. """ import wc # initialize logging logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name) stop_service() remove_service() remove_certificates() remove_tempfiles() purge_tempfiles() # make sure empty directories are removed remove_empty_directories(wc.ConfigDir)
|
exception(GUI, "Wrong path %r", url)
|
wc.log.exception(GUI, "Wrong path %r", url)
|
def __init__ (self, client, url, form, protocol, clientheaders, status=200, msg=wc.i18n._('Ok'), localcontext=None, auth=''): """load a web configuration template and return response""" wc.log.debug(wc.LOG_GUI, "WebConfig %s %s", url, form) self.client = client # we pretend to be the server self.connected = True headers = wc.proxy.Headers.WcMessage() headers['Server'] = 'Proxy\r' if auth: if status==407: headers['Proxy-Authenticate'] = "%s\r"%auth elif status==401: headers['WWW-Authenticate'] = "%s\r"%auth else: error(GUI, "Authentication with wrong status %d", status) if status in [301,302]: headers['Location'] = clientheaders['Location'] gm = mimetypes.guess_type(url, None) if gm[0] is not None: ctype = gm[0] else: # note: index.html is appended to directories ctype = 'text/html' if ctype=='text/html': ctype += "; charset=iso-8859-1" headers['Content-Type'] = "%s\r"%ctype try: lang = wc.i18n.get_headers_lang(clientheaders) # get the template filename path, dirs, lang = get_template_url(url, lang) if path.endswith('.html'): fp = file(path) # get TAL context context, newstatus = \ get_context(dirs, form, localcontext, lang) if newstatus==401 and status!=newstatus: client.error(401, wc.i18n._("Authentication Required"), auth=wc.proxy.auth.get_challenges()) return # get translator translator = gettext.translation(wc.Name, wc.LocaleDir, [lang], fallback=True) #wc.log.debug(wc.LOG_GUI, "Using translator %s", translator.info()) # expand template data = expand_template(fp, context, translator=translator) else: fp = file(path, 'rb') data = fp.read() fp.close() except IOError: exception(GUI, "Wrong path %r", url) # XXX this can actually lead to a maximum recursion # error when client.error caused the exception client.error(404, wc.i18n._("Not Found")) return except StandardError: # catch standard exceptions and report internal error exception(GUI, "Template error") client.error(500, wc.i18n._("Internal Error")) return # not catched builtin exceptions are: # SystemExit, StopIteration and all warnings
|
exception(GUI, "Template error")
|
wc.log.exception(GUI, "Template error")
|
def __init__ (self, client, url, form, protocol, clientheaders, status=200, msg=wc.i18n._('Ok'), localcontext=None, auth=''): """load a web configuration template and return response""" wc.log.debug(wc.LOG_GUI, "WebConfig %s %s", url, form) self.client = client # we pretend to be the server self.connected = True headers = wc.proxy.Headers.WcMessage() headers['Server'] = 'Proxy\r' if auth: if status==407: headers['Proxy-Authenticate'] = "%s\r"%auth elif status==401: headers['WWW-Authenticate'] = "%s\r"%auth else: error(GUI, "Authentication with wrong status %d", status) if status in [301,302]: headers['Location'] = clientheaders['Location'] gm = mimetypes.guess_type(url, None) if gm[0] is not None: ctype = gm[0] else: # note: index.html is appended to directories ctype = 'text/html' if ctype=='text/html': ctype += "; charset=iso-8859-1" headers['Content-Type'] = "%s\r"%ctype try: lang = wc.i18n.get_headers_lang(clientheaders) # get the template filename path, dirs, lang = get_template_url(url, lang) if path.endswith('.html'): fp = file(path) # get TAL context context, newstatus = \ get_context(dirs, form, localcontext, lang) if newstatus==401 and status!=newstatus: client.error(401, wc.i18n._("Authentication Required"), auth=wc.proxy.auth.get_challenges()) return # get translator translator = gettext.translation(wc.Name, wc.LocaleDir, [lang], fallback=True) #wc.log.debug(wc.LOG_GUI, "Using translator %s", translator.info()) # expand template data = expand_template(fp, context, translator=translator) else: fp = file(path, 'rb') data = fp.read() fp.close() except IOError: exception(GUI, "Wrong path %r", url) # XXX this can actually lead to a maximum recursion # error when client.error caused the exception client.error(404, wc.i18n._("Not Found")) return except StandardError: # catch standard exceptions and report internal error exception(GUI, "Template error") client.error(500, wc.i18n._("Internal Error")) return # not catched builtin exceptions are: # SystemExit, StopIteration and all warnings
|
if ro.match(self.headers.getheader('content-type')):
|
if ro.match(self.headers.getheader('content-type') or ""):
|
def process_headers (self): # Headers are terminated by a blank line .. now in the regexp, # we want to say it's either a newline at the beginning of # the document, or it's a lot of headers followed by two newlines. # The cleaner alternative would be to read one line at a time # until we get to a blank line... m = re.match(r'^((?:[^\r\n]+\r?\n)*\r?\n)', self.recv_buffer) if not m: return
|
getattr(self, fun)(htmlfilter)
|
getattr(self, fun)()
|
def scan_end_tag (self, tag): fun = "%s_end"%tag if hasattr(self, fun): getattr(self, fun)(htmlfilter)
|
def object_end (self, htmlfilter):
|
def object_end (self):
|
def object_end (self, htmlfilter): if self.in_winhelp: self.in_winhelp = False
|
mime = mime_types[0]
|
def server_set_content_headers (headers, mime_types, url): """add missing content-type headers""" origmime = headers.get('Content-Type', None) if not origmime: wc.log.warn(wc.LOG_PROXY, _("Missing content type in %r"), url) if not mime_types: return matching_mimes = [m for m in mime_types if origmime.startswith(m)] if len(matching_mimes) > 0: return # we have a mime type override if origmime: wc.log.warn(wc.LOG_PROXY, _("Change content type of %r from %r to %r"), url, origmime, mime) else: wc.log.warn(wc.LOG_PROXY, _("Set content type of %r to %r"), url, mime) headers['Content-Type'] = "%s\r" % mime
|
|
self.log.debug ("Evaluating %s" % expr)
|
self.log.debug ("Evaluating %s ...", expr)
|
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[5:].lstrip ())
|
res = self.evaluatePath (expr[5:].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.evaluateExists (expr[7:].lstrip())
|
res = self.evaluateExists (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.evaluateNoCall (expr[7:].lstrip())
|
res = self.evaluateNoCall (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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.