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.... |
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(item... |
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 = clie... |
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 templat... |
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 templat... |
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 = ... |
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 = ... |
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.... |
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... |
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 adr... |
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... |
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, he... | 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'r... |
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'r... |
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 (nathan@zope.org) # 14-Apr-2003 Hacked by Barry Warsaw (barry@zope.com) |
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.docume... |
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['p... |
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) #... |
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",... | 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(... |
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.ha... |
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.ha... |
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.ha... |
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.ha... |
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.ha... |
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 =... |
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] +=... |
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 = ... | |
<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)... | |
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.ZeroReturnErr... | 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)... |
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['sslpo... |
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['sslpo... | |
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['sslpo... | |
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 = bas... |
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'] i... |
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'] i... |
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 ... |
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 ... |
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 ... |
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'] ... |
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'] ... |
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.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(... | |
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(... |
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",... | 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, ... |
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 ... |
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 ... |
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 ... |
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 ... |
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.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.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... |
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]) | 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.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... |
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... |
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"... |
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.exe... | 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.c... | 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.comm... |
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'... |
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'... |
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[k... |
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[k... |
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[k... |
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_confi... |
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_empt... |
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 header... |
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 header... |
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.... |
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 ... | |
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 ()) | 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.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.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:')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.