bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def _log (fun, msg, args, tb=False): """ Log a message with given function and an optional traceback. @return: None """ fun(msg, *args) if tb: # note: get rid of last parts of the stack s = _stack_format(inspect.stack()[2:]) fun(s)
def _log (fun, msg, args, tb=False): """ Log a message with given function and an optional traceback. @return: None """ fun(msg, *args) if tb: # note: get rid of last parts of the stack fun(_stack_format(inspect.stack()[2:]))
15,500
def debug (log, msg, *args, **kwargs): """ Log a debug message. return: None """ _log(logging.getLogger(log).debug, msg, args, tb=kwargs.get("tb"))
def debug (logname, msg, *args, **kwargs): """ Log a debug message. return: None """ _log(logging.getLogger(log).debug, msg, args, tb=kwargs.get("tb"))
15,501
def debug (log, msg, *args, **kwargs): """ Log a debug message. return: None """ _log(logging.getLogger(log).debug, msg, args, tb=kwargs.get("tb"))
def debug (log, 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"))
15,502
def info (log, msg, *args, **kwargs): """ Log an informational message. return: None """ _log(logging.getLogger(log).info, msg, args, tb=kwargs.get("tb"))
def info (logname, msg, *args, **kwargs): """ Log an informational message. return: None """ _log(logging.getLogger(log).info, msg, args, tb=kwargs.get("tb"))
15,503
def info (log, msg, *args, **kwargs): """ Log an informational message. return: None """ _log(logging.getLogger(log).info, msg, args, tb=kwargs.get("tb"))
def info (log, msg, *args, **kwargs): """ Log an informational message. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.INFO): _log(log.info, msg, args, tb=kwargs.get("tb"))
15,504
def warn (log, msg, *args, **kwargs): """ Log a warning. return: None """ _log(logging.getLogger(log).warn, msg, args, tb=kwargs.get("tb"))
def warn (logname, msg, *args, **kwargs): """ Log a warning. return: None """ _log(logging.getLogger(log).warn, msg, args, tb=kwargs.get("tb"))
15,505
def warn (log, msg, *args, **kwargs): """ Log a warning. return: None """ _log(logging.getLogger(log).warn, msg, args, tb=kwargs.get("tb"))
def warn (log, msg, *args, **kwargs): """ Log a warning. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.WARN): _log(log.warn, msg, args, tb=kwargs.get("tb"))
15,506
def error (log, msg, *args, **kwargs): """ Log an error. return: None """ _log(logging.getLogger(log).error, msg, args, tb=kwargs.get("tb"))
def error (logname, msg, *args, **kwargs): """ Log an error. return: None """ _log(logging.getLogger(log).error, msg, args, tb=kwargs.get("tb"))
15,507
def error (log, msg, *args, **kwargs): """ Log an error. return: None """ _log(logging.getLogger(log).error, msg, args, tb=kwargs.get("tb"))
def error (log, msg, *args, **kwargs): """ Log an error. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.ERROR): _log(log.error, msg, args, tb=kwargs.get("tb"))
15,508
def critical (log, msg, *args, **kwargs): """ Log a critical error. return: None """ _log(logging.getLogger(log).critical, msg, args, tb=kwargs.get("tb"))
def critical (logname, msg, *args, **kwargs): """ Log a critical error. return: None """ _log(logging.getLogger(log).critical, msg, args, tb=kwargs.get("tb"))
15,509
def critical (log, msg, *args, **kwargs): """ Log a critical error. return: None """ _log(logging.getLogger(log).critical, msg, args, tb=kwargs.get("tb"))
def critical (log, msg, *args, **kwargs): """ Log a critical error. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.CRITICAL): _log(log.critical, msg, args, tb=kwargs.get("tb"))
15,510
def exception (log, msg, *args, **kwargs): """ Log an exception. return: None """ _log(logging.getLogger(log).exception, msg, args, tb=kwargs.get("tb"))
def exception (logname, msg, *args, **kwargs): """ Log an exception. return: None """ _log(logging.getLogger(log).exception, msg, args, tb=kwargs.get("tb"))
15,511
def exception (log, msg, *args, **kwargs): """ Log an exception. return: None """ _log(logging.getLogger(log).exception, msg, args, tb=kwargs.get("tb"))
def exception (log, msg, *args, **kwargs): """ Log an exception. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.EXCEPTION): _log(log.exception, msg, args, tb=kwargs.get("tb"))
15,512
def init_dns_resolver_nt (): import winreg key = None try: key = winreg.key_handle(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters") except EnvironmentError: try: # for Windows ME key = winreg.key_handle(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\VxD\MSTCP") except EnvironmentError: pass if key: for server in winreg.stringdisplay(key.get("NameServer", "")): if server: DnsConfig.nameservers.append(str(server)) for item in winreg.stringdisplay(key.get("SearchList", "")): if item: DnsConfig.search_domains.append(str(item)) if not DnsConfig.nameservers: # XXX the proper way to test this is to search for # the "EnableDhcp" key in the interface adapters... for server in winreg.stringdisplay(key.get("DhcpNameServer", "")): if server: DnsConfig.nameservers.append(str(server)) for item in winreg.stringdisplay(key.get("DhcpDomain", "")): if item: DnsConfig.search_domains.append(str(item)) try: # search adapters key = winreg.key_handle(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DNSRegisteredAdapters") for subkey in key.subkeys(): count, counttype = subkey['DNSServerAddressCount'] values, valuestype = subkey['DNSServerAddresses'] for server in winreg.binipdisplay(values): if server: DnsConfig.nameservers.append(server) except EnvironmentError: pass try: # search interfaces key = winreg.key_handle(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces") for subkey in key.subkeys(): for server in winreg.stringdisplay(subkey.get('NameServer', '')): if server: DnsConfig.nameservers.append(server) except EnvironmentError: pass
def init_dns_resolver_nt (): import winreg key = None try: key = winreg.key_handle(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters") except EnvironmentError: try: # for Windows ME key = winreg.key_handle(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\VxD\MSTCP") except EnvironmentError: pass if key: for server in winreg.stringdisplay(key.get("NameServer", "")): if server: DnsConfig.nameservers.append(str(server)) for item in winreg.stringdisplay(key.get("SearchList", "")): if item: DnsConfig.search_domains.append(str(item)) if not DnsConfig.nameservers: # XXX the proper way to test this is to search for # the "EnableDhcp" key in the interface adapters... for server in winreg.stringdisplay(key.get("DhcpNameServer", "")): if server: DnsConfig.nameservers.append(str(server)) for item in winreg.stringdisplay(key.get("DhcpDomain", "")): if item: DnsConfig.search_domains.append(str(item)) try: # search adapters key = winreg.key_handle(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DNSRegisteredAdapters") for subkey in key.subkeys(): values = subkey.get('DNSServerAddresses', "") for server in winreg.binipdisplay(values): if server: DnsConfig.nameservers.append(server) except EnvironmentError: pass try: # search interfaces key = winreg.key_handle(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces") for subkey in key.subkeys(): for server in winreg.stringdisplay(subkey.get('NameServer', '')): if server: DnsConfig.nameservers.append(server) except EnvironmentError: pass
15,513
def _fatalError (self, msg): """signal a fatal filter/parser error""" self._errorfun(msg, "fatalError")
def _fatalError (self, msg): """signal a fatal filter/parser error""" self._errorfun(msg, "fatalError")
15,514
def _debugbuf (self): """print debugging information about data 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_debugbuf(self):"""printdebugginginformationaboutdatabufferstatus"""#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()`)
15,515
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self._debug(ALWAYS, "self.inbuf", `self.inbuf.getvalue()`) return data = self.inbuf.getvalue() self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data #self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: #self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer #self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self._debug(ALWAYS, "self.inbuf", `self.inbuf.getvalue()`) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data #self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: #self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer #self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
15,516
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) # start recursive html filter (used by jsProcessData) self.js_html = FilterHtmlParser(self.rules, self.url, comments=self.comments, javascript=self.js_filter, level=self.level+1) # execute self.js_env.executeScript(unescape_js(script), ver) self.js_env.detachListener(self) # wait for recursive filter to finish self.jsEndScript(item)
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) # start recursive html filter (used by jsProcessData) self.js_html = FilterHtmlParser(self.rules, self.pics, self.url, comments=self.comments, javascript=self.js_filter, level=self.level+1) # execute self.js_env.executeScript(unescape_js(script), ver) self.js_env.detachListener(self) # wait for recursive filter to finish self.jsEndScript(item)
15,517
def _broken (): p = HtmlPrinter() p.feed("<img bo\\\nrder=0>") p.flush()
def _broken (): p = HtmlPrinter() p.debug(1) for c in """</td <td a="b" >""": p.feed(c) p.flush()
15,518
def __init__ (self): Htmlparser.__init__(self) if wc.config['showerrors']: self.error = self._error self.warning = self._warning self.fatalError = self._fatalError self.outbuf = StringIO() self.buf = []
def __init__ (self): HtmlParser.__init__(self) if wc.config['showerrors']: self.error = self._error self.warning = self._warning self.fatalError = self._fatalError self.outbuf = StringIO() self.buf = []
15,519
def filter (self, data, **attrs): if not attrs.has_key('buffer'): # we do not block this image # or we do not have enough buffer data return data buf = attrs['buffer'] buf.write(data) if buf.tell() > self.min_bufsize: if self.check_sizes(buf): # size is ok data = buf.getvalue() buf.close() del attrs['buffer'] return return ''
def filter (self, data, **attrs): if attrs['buffer'].closed: # we do not block this image # or we do not have enough buffer data return data buf = attrs['buffer'] buf.write(data) if buf.tell() > self.min_bufsize: if self.check_sizes(buf): # size is ok data = buf.getvalue() buf.close() del attrs['buffer'] return return ''
15,520
def filter (self, data, **attrs): if not attrs.has_key('buffer'): # we do not block this image # or we do not have enough buffer data return data buf = attrs['buffer'] buf.write(data) if buf.tell() > self.min_bufsize: if self.check_sizes(buf): # size is ok data = buf.getvalue() buf.close() del attrs['buffer'] return return ''
def filter (self, data, **attrs): if not attrs.has_key('buffer'): # we do not block this image # or we do not have enough buffer data return data buf = attrs['buffer'] buf.write(data) if buf.tell() > self.min_bufsize: if self.check_sizes(buf): # size is ok data = buf.getvalue() buf.close() return data return ''
15,521
def check_sizes (self, buf): try: img = Image.open(buf) for size, formats in sizes: if size==img.size: # size matches, look for format restriction if not formats: return False elif img.format.lower() in formats: return False except IOError: # XXX print error pass return True
def check_sizes (self, buf): try: img = Image.open(buf, 'r') for size, formats in sizes: if size==img.size: # size matches, look for format restriction if not formats: return False elif img.format.lower() in formats: return False except IOError: # XXX print error pass return True
15,522
def testUrl (self): url = "http://server/..%5c..%5c..%5c..%5c..%5c..%5..%5c..%5ccskin.zip" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEquals(nurl, "http://server/cskin.zip") url = "http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=3845B54D.E546F9BD%40monmouth.com&rnum=2&prev=/groups%3Fq%3Dlogitech%2Bwingman%2Bextreme%2Bdigital%2B3d%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D3845B54D.E546F9BD%2540monmouth.com%26rnum%3D2" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEqual(url, nurl)
def testUrlPathAttack (self): url = "http://server/..%5c..%5c..%5c..%5c..%5c..%5..%5c..%5ccskin.zip" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEquals(nurl, "http://server/cskin.zip") url = "http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=3845B54D.E546F9BD%40monmouth.com&rnum=2&prev=/groups%3Fq%3Dlogitech%2Bwingman%2Bextreme%2Bdigital%2B3d%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D3845B54D.E546F9BD%2540monmouth.com%26rnum%3D2" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEqual(url, nurl)
15,523
def testUrl (self): url = "http://server/..%5c..%5c..%5c..%5c..%5c..%5..%5c..%5ccskin.zip" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEquals(nurl, "http://server/cskin.zip") url = "http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=3845B54D.E546F9BD%40monmouth.com&rnum=2&prev=/groups%3Fq%3Dlogitech%2Bwingman%2Bextreme%2Bdigital%2B3d%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D3845B54D.E546F9BD%2540monmouth.com%26rnum%3D2" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEqual(url, nurl)
def testUrl (self): url = "http://server/..%5c..%5c..%5c..%5c..%5c..%5..%5c..%5ccskin.zip" nurl = "http://server/cskin.zip" self.assertEquals(wc.url.url_quote(wc.url.url_norm(url)), nurl) def testUrlQuoting (self): url = "http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=3845B54D.E546F9BD%40monmouth.com&rnum=2&prev=/groups%3Fq%3Dlogitech%2Bwingman%2Bextreme%2Bdigital%2B3d%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D3845B54D.E546F9BD%2540monmouth.com%26rnum%3D2" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEqual(url, nurl)
15,524
def testUrl (self): url = "http://server/..%5c..%5c..%5c..%5c..%5c..%5..%5c..%5ccskin.zip" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEquals(nurl, "http://server/cskin.zip") url = "http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=3845B54D.E546F9BD%40monmouth.com&rnum=2&prev=/groups%3Fq%3Dlogitech%2Bwingman%2Bextreme%2Bdigital%2B3d%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D3845B54D.E546F9BD%2540monmouth.com%26rnum%3D2" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEqual(url, nurl)
def testUrl (self): url = "http://server/..%5c..%5c..%5c..%5c..%5c..%5..%5c..%5ccskin.zip" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEquals(nurl, "http://server/cskin.zip") url = "http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=3845B54D.E546F9BD%40monmouth.com&rnum=2&prev=/groups%3Fq%3Dlogitech%2Bwingman%2Bextreme%2Bdigital%2B3d%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D3845B54D.E546F9BD%2540monmouth.com%26rnum%3D2" nurl = wc.url.url_quote(wc.url.url_norm(url)) self.assertEqual(url, nurl)
15,525
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.htmlparser.state[0] == 'wait', "non-wait state" wc.log.debug(wc.LOG_JS, "%s jsScriptData %r", self, data) if data is None: if not self.js_script: wc.log.warn(wc.LOG_JS, "empty JavaScript src %s", url) self.js_script = u"// "+\ _("error fetching script from %r") % url self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.STARTTAG, "script", {'type': 'text/javascript'}]) # norm html comments script = wc.js.remove_html_comments(self.js_script) script = u"\n<!--\n%s\n//-->\n" % wc.js.escape_js(script) self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.ENDTAG, u"script"]) self.js_script = u'' self.htmlparser.state = ('parse',) wc.log.debug(wc.LOG_JS, "%s switching back to parse with", self) self.htmlparser.debugbuf(wc.LOG_JS) else: wc.log.debug(wc.LOG_JS, "JS read %d <= %s", len(data), url) self.js_script += data
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.htmlparser.state[0] == 'wait', "non-wait state" wc.log.debug(wc.LOG_JS, "%s jsScriptData %r", self, data) if data is None: if not self.js_script: wc.log.warn(wc.LOG_JS, "empty JavaScript src %s", url) self.js_script = u"// "+\ _("error fetching script from %r") % url self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.STARTTAG, u"script", {'type': 'text/javascript'}]) # norm html comments script = wc.js.remove_html_comments(self.js_script) script = u"\n<!--\n%s\n//-->\n" % wc.js.escape_js(script) self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.htmlparser.tagbuf.append( [wc.filter.rules.RewriteRule.ENDTAG, u"script"]) self.js_script = u'' self.htmlparser.state = ('parse',) wc.log.debug(wc.LOG_JS, "%s switching back to parse with", self) self.htmlparser.debugbuf(wc.LOG_JS) else: wc.log.debug(wc.LOG_JS, "JS read %d <= %s", len(data), url) self.js_script += data
15,526
def new_instance (self, **opts): """generate new JSFilter instance""" return JSFilter(self.url, opts)
def new_instance (self, **opts): """generate new JSFilter instance""" return JSFilter(self.url, opts)
15,527
def handle_read (self): """read data from SSL connection, put it into recv_buffer and call process_read""" assert self.connected debug(PROXY, '%s Connection.handle_read', self)
def handle_read (self): """read data from SSL connection, put it into recv_buffer and call process_read""" assert self.connected debug(PROXY, '%s Connection.handle_read', self)
15,528
def fill_attrs (self, attrs, name): if name=='service': self._service = unxmlify(attrs.get('name')).encode('iso8859-1') self.ratings[self._service] = {} elif name=='category': assert self._service self._category = unxmlify(attrs.get('name')).encode('iso8859-1') elif name=='url': pass elif name=='pics': UrlRule.fill_attrs(self, attrs, name) else: raise ValueError(i18n._("Invalid pics rule tag name `%s',"+\ " check your configuration")%name)
def fill_attrs (self, attrs, name): if name=='service': self._service = unxmlify(attrs.get('name')).encode('iso8859-1') self.ratings[self._service] = {} elif name=='category': assert self._service self._category = unxmlify(attrs.get('name')).encode('iso8859-1') elif name=='url': pass elif name=='pics': UrlRule.fill_attrs(self, attrs, name) else: raise ValueError(i18n._("Invalid pics rule tag name `%s',"+\ " check your configuration")%name)
15,529
def _form_apply_rating (form): # rating categories for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname) if category is None: # unknown category error['categoryvalue'] = True return False if category.iterable: realvalue = value else: realvalue = _intrange_from_string(value) if not category.valid_value(realvalue): error['categoryvalue'] = True return False if catname not in currule.ratings: currule.ratings[catname] = value info['rulecategory'] = True elif currule.ratings[catname] != value: currule.ratings[catname] = value info['rulecategory'] = True elif catname in currule.ratings: info['rulecategory'] = True del currule.ratings[catname]
def _form_apply_rating (form): # rating categories for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname) if category is None: # unknown category error['categoryvalue'] = True return if category.iterable: realvalue = value else: realvalue = _intrange_from_string(value) if not category.valid_value(realvalue): error['categoryvalue'] = True return if catname not in currule.ratings: currule.ratings[catname] = value info['rulecategory'] = True elif currule.ratings[catname] != value: currule.ratings[catname] = value info['rulecategory'] = True elif catname in currule.ratings: info['rulecategory'] = True del currule.ratings[catname]
15,530
def _form_apply_rating (form): # rating categories for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname) if category is None: # unknown category error['categoryvalue'] = True return False if category.iterable: realvalue = value else: realvalue = _intrange_from_string(value) if not category.valid_value(realvalue): error['categoryvalue'] = True return False if catname not in currule.ratings: currule.ratings[catname] = value info['rulecategory'] = True elif currule.ratings[catname] != value: currule.ratings[catname] = value info['rulecategory'] = True elif catname in currule.ratings: info['rulecategory'] = True del currule.ratings[catname]
def _form_apply_rating (form): # rating categories for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname) if category is None: # unknown category error['categoryvalue'] = True return False if category.iterable: realvalue = value else: realvalue = _intrange_from_string(value) if not category.valid_value(realvalue): error['categoryvalue'] = True return if currule.ratings[catname] != value: currule.ratings[catname] = value currule.compile_values() info['rulecategory'] = True del currule.ratings[catname]
15,531
def _form_apply_rating (form): # rating categories for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname) if category is None: # unknown category error['categoryvalue'] = True return False if category.iterable: realvalue = value else: realvalue = _intrange_from_string(value) if not category.valid_value(realvalue): error['categoryvalue'] = True return False if catname not in currule.ratings: currule.ratings[catname] = value info['rulecategory'] = True elif currule.ratings[catname] != value: currule.ratings[catname] = value info['rulecategory'] = True elif catname in currule.ratings: info['rulecategory'] = True del currule.ratings[catname]
def _form_apply_rating (form): # rating categories for catname, value in _get_prefix_vals(form, 'category_'): category = _get_category(catname) if category is None: # unknown category error['categoryvalue'] = True return False if category.iterable: realvalue = value else: realvalue = _intrange_from_string(value) if not category.valid_value(realvalue): error['categoryvalue'] = True return False if catname not in currule.ratings: currule.ratings[catname] = value info['rulecategory'] = True elif currule.ratings[catname] != value: currule.ratings[catname] = value info['rulecategory'] = True elif catname in currule.ratings: info['rulecategory'] = True
15,532
def proxy_poll (timeout=0.0): """ Look for sockets with pending data and call the appropriate connection handlers. """ handlerCount = 0 if wc.proxy.Dispatcher.socket_map: e = wc.proxy.Dispatcher.socket_map.values() r = [x for x in e if x.readable()] w = [x for x in e if x.writable()] assert wc.log.debug(wc.LOG_PROXY, "select with %f timeout", timeout) try: (r, w, e) = select.select(r, w, e, timeout) except select.error, why: if why.args == (4, 'Interrupted system call'): # this occurs on UNIX systems with a sighup signal return else: raise assert wc.log.debug(wc.LOG_PROXY, "poll result %s", (r, w, e)) # Make sure we only process one type of event at a time, # because if something needs to close the connection we # don't want to call another handle_* on it for x in e: assert wc.log.debug(wc.LOG_PROXY, "%s poll handle exception", x) x.handle_expt_event() handlerCount += 1 for x in w: assert wc.log.debug(wc.LOG_PROXY, "poll handle write %s", x) # note: do not put the following "if" in a list filter if not x.writable(): assert wc.log.debug(wc.LOG_PROXY, "not writable %s", x) continue x.handle_write_event() handlerCount += 1 for x in r: assert wc.log.debug(wc.LOG_PROXY, "poll handle read %s", x) # note: do not put the following "if" in a list filter if not x.readable(): assert wc.log.debug(wc.LOG_PROXY, "not readable %s", x) continue x.handle_read_event() handlerCount += 1 return handlerCount
def proxy_poll (timeout=0.0): """ Look for sockets with pending data and call the appropriate connection handlers. """ handlerCount = 0 if wc.proxy.Dispatcher.socket_map: e = wc.proxy.Dispatcher.socket_map.values() r = [x for x in e if x.readable()] w = [x for x in e if x.writable()] assert wc.log.debug(wc.LOG_PROXY, "select with %f timeout", timeout) try: (r, w, e) = select.select(r, w, e, timeout) except select.error, why: if why.args == (4, 'Interrupted system call'): # this occurs on UNIX systems with a sighup signal return else: raise assert wc.log.debug(wc.LOG_PROXY, "poll result %s", (r, w, e)) # Make sure we only process one type of event at a time, # because if something needs to close the connection we # don't want to call another handle_* on it for x in e: assert wc.log.debug(wc.LOG_PROXY, "poll handle exception %s", x) x.handle_expt_event() handlerCount += 1 for x in w: assert wc.log.debug(wc.LOG_PROXY, "poll handle write %s", x) # note: do not put the following "if" in a list filter if not x.writable(): assert wc.log.debug(wc.LOG_PROXY, "not writable %s", x) continue x.handle_write_event() handlerCount += 1 for x in r: assert wc.log.debug(wc.LOG_PROXY, "poll handle read %s", x) # note: do not put the following "if" in a list filter if not x.readable(): assert wc.log.debug(wc.LOG_PROXY, "not readable %s", x) continue x.handle_read_event() handlerCount += 1 return handlerCount
15,533
def _exec_form (form): # reset info/error global filterenabled, filterdisabled filterenabled = "" filterdisabled = "" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) else: config['proxyuser'] = '' # proxy pass if form.has_key('proxypass'): _form_proxypass(base64.encodestring(_getval(form, 'proxypass').strip()), res) else: if config['proxypass']: res[0] = 407 config['proxypass'] = '' # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) else: config['parentproxy'] = '' # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) else: config['parentproxyport'] = 3128 # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) else: config['parentproxyuser'] = '' # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') if val=='__dummy__': # ignore the dummy value val = "" _form_parentproxypass(base64.encodestring(val)) else: config['parentproxypass'] = '' # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) else: config['timeout'] = 0 # 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) if info: # write changed config config.write_proxyconf() _daemon.reload() return res[0]
def _exec_form (form): # reset info/error global filterenabled, filterdisabled filterenabled = "" filterdisabled = "" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) else: config['proxyuser'] = '' # proxy pass if form.has_key('proxypass'): val = _getval(form, 'proxypass') if val=='__dummy__': val = "" _form_proxypass(base64.encodestring(val).strip(), res) else: config['proxypass'] = '' if config['proxypass'] and config['proxyuser']: res[0] = 407 config['proxypass'] = '' # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) else: config['parentproxy'] = '' # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) else: config['parentproxyport'] = 3128 # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) else: config['parentproxyuser'] = '' # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') if val=='__dummy__': # ignore the dummy value val = "" _form_parentproxypass(base64.encodestring(val)) else: config['parentproxypass'] = '' # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) else: config['timeout'] = 0 # 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) if info: # write changed config config.write_proxyconf() _daemon.reload() return res[0]
15,534
def _exec_form (form): # reset info/error global filterenabled, filterdisabled filterenabled = "" filterdisabled = "" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) else: config['proxyuser'] = '' # proxy pass if form.has_key('proxypass'): _form_proxypass(base64.encodestring(_getval(form, 'proxypass').strip()), res) else: if config['proxypass']: res[0] = 407 config['proxypass'] = '' # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) else: config['parentproxy'] = '' # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) else: config['parentproxyport'] = 3128 # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) else: config['parentproxyuser'] = '' # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') if val=='__dummy__': # ignore the dummy value val = "" _form_parentproxypass(base64.encodestring(val)) else: config['parentproxypass'] = '' # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) else: config['timeout'] = 0 # 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) if info: # write changed config config.write_proxyconf() _daemon.reload() return res[0]
def _exec_form (form): # reset info/error global filterenabled, filterdisabled filterenabled = "" filterdisabled = "" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) else: config['proxyuser'] = '' # proxy pass if form.has_key('proxypass'): _form_proxypass(base64.encodestring(_getval(form, 'proxypass').strip()), res) else: if config['proxypass']: res[0] = 407 # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) else: config['parentproxy'] = '' # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) else: config['parentproxyport'] = 3128 # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) else: config['parentproxyuser'] = '' # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') if val=='__dummy__': # ignore the dummy value val = "" _form_parentproxypass(base64.encodestring(val)) else: config['parentproxypass'] = '' # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) else: config['timeout'] = 0 # 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) if info: # write changed config config.write_proxyconf() _daemon.reload() return res[0]
15,535
def _exec_form (form): # reset info/error global filterenabled, filterdisabled filterenabled = "" filterdisabled = "" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) else: config['proxyuser'] = '' # proxy pass if form.has_key('proxypass'): _form_proxypass(base64.encodestring(_getval(form, 'proxypass').strip()), res) else: if config['proxypass']: res[0] = 407 config['proxypass'] = '' # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) else: config['parentproxy'] = '' # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) else: config['parentproxyport'] = 3128 # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) else: config['parentproxyuser'] = '' # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') if val=='__dummy__': # ignore the dummy value val = "" _form_parentproxypass(base64.encodestring(val)) else: config['parentproxypass'] = '' # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) else: config['timeout'] = 0 # 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) if info: # write changed config config.write_proxyconf() _daemon.reload() return res[0]
def _exec_form (form): # reset info/error global filterenabled, filterdisabled filterenabled = "" filterdisabled = "" info.clear() error.clear() res = [None] # proxy port if form.has_key('port'): _form_proxyport(_getval(form, 'port')) # proxy user if form.has_key('proxyuser'): _form_proxyuser(_getval(form, 'proxyuser').strip(), res) else: config['proxyuser'] = '' # proxy pass if form.has_key('proxypass'): _form_proxypass(base64.encodestring(_getval(form, 'proxypass').strip()), res) else: if config['proxypass']: res[0] = 407 config['proxypass'] = '' # parent proxy host if form.has_key('parentproxy'): _form_parentproxy(_getval(form, 'parentproxy').strip()) else: config['parentproxy'] = '' # parent proxy port if form.has_key('parentproxyport'): _form_parentproxyport(_getval(form, 'parentproxyport')) else: config['parentproxyport'] = 3128 # parent proxy user if form.has_key('parentproxyuser'): _form_parentproxyuser(_getval(form, 'parentproxyuser').strip()) else: config['parentproxyuser'] = '' # parent proxy pass if form.has_key('parentproxypass'): val = _getval(form, 'parentproxypass') if val=='__dummy__': # ignore the dummy value val = "" _form_parentproxypass(base64.encodestring(val).strip()) else: config['parentproxypass'] = '' # timeout if form.has_key('timeout'): _form_timeout(_getval(form, 'timeout')) else: config['timeout'] = 0 # 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) if info: # write changed config config.write_proxyconf() _daemon.reload() return res[0]
15,536
def _form_proxyuser (proxyuser, res): if proxyuser != config['proxyuser']: res[0] = 407 config['proxyuser'] = proxyuser info['proxyuser'] = True
def _form_proxyuser (proxyuser, res): if proxyuser != config['proxyuser']: config['proxyuser'] = proxyuser info['proxyuser'] = True
15,537
def _form_proxypass (proxypass, res): if proxypass != config['proxypass'] and proxypass!='__dummy__': res[0] = 407 config['proxypass'] = base64.encodestring(proxypass) info['proxypass'] = True
def _form_proxypass (proxypass, res): if proxypass != config['proxypass']: config['proxypass'] = proxypass info['proxypass'] = True
15,538
def get_conf_filename (self, directory): return os.path.join(directory, "_%s_configdata.py"%self.get_name())
def get_conf_filename (self, directory): return os.path.join(directory, "_%s_configdata.py"%self.get_name())
15,539
def expire_servers (self): """expire server connection that have been unused for too long""" debug(PROXY, "expire servers") expire_time = time.time() - 300 # Unused for five minutes to_expire = [] for addr,set in self.smap.items(): for server,status in set.items(): if status[0] == 'available' and status[1] < expire_time: # It's old .. let's get rid of it to_expire.append((addr,server)) for addr,server in to_expire: debug(PROXY, "expire %s server %s", addr, server) server.close() if addr in self.smap: assert not self.smap[addr].has_key(server), "Not expired: %s"%str(self.smap[addr]) make_timer(60, self.expire_servers)
def expire_servers (self): """expire server connection that have been unused for too long""" debug(PROXY, "pool expire servers") expire_time = time.time() - 300 # Unused for five minutes to_expire = [] for addr,set in self.smap.items(): for server,status in set.items(): if status[0] == 'available' and status[1] < expire_time: # It's old .. let's get rid of it to_expire.append((addr,server)) for addr,server in to_expire: debug(PROXY, "expire %s server %s", addr, server) server.close() if addr in self.smap: assert not self.smap[addr].has_key(server), "Not expired: %s"%str(self.smap[addr]) make_timer(60, self.expire_servers)
15,540
def connect (self, addr): """ Connect to addr. """ self.socket = socket.socket() self.socket.connect(addr)
def connect (self, addr): """ Connect to given address. """ debug("Client connect to %s" % str(addr)) self.socket = socket.socket() self.socket.connect(addr)
15,541
def send_data (self, data): """ Send complete data to socket. """ self.socket.sendall(data)
def send_data (self, data): """ Send complete data to socket. """ self.socket.sendall(data)
15,542
def read_data (self): """ Read until no more data is available. """ data = "" while wc.proxy.readable_socket(self.socket): s = self.socket.recv(4096) if not s: break data += s return data
def read_data (self): """ Read until no more data is available. """ data = "" while wc.proxy.readable_socket(self.socket): s = self.socket.recv(4096) if not s: break data += s return data
15,543
def get_request (self): """ Get HttpRequest from internal data """ method = self.command uri = self.path vparts = self.request_version.split('/', 1)[1].split(".") version = (int(vparts[0]), int(vparts[1])) headers = [line[:-1] for line in self.headers.headers] if self.headers.has_key("Content-Length"): clen = int(self.headers["Content-Length"]) content = self.rfile.read(clen) else: content = "" return HttpRequest(method, uri, version, headers, content=content)
def get_request (self): """ Get HttpRequest from internal data """ method = self.command uri = self.path vparts = self.request_version.split('/', 1)[1].split(".") version = (int(vparts[0]), int(vparts[1])) headers = [line[:-1] for line in self.headers.headers] if self.headers.has_key("Content-Length"): clen = int(self.headers["Content-Length"]) data = self.rfile.read(clen) else: content = "" return HttpRequest(method, uri, version, headers, content=content)
15,544
def get_request (self): """ Get HttpRequest from internal data """ method = self.command uri = self.path vparts = self.request_version.split('/', 1)[1].split(".") version = (int(vparts[0]), int(vparts[1])) headers = [line[:-1] for line in self.headers.headers] if self.headers.has_key("Content-Length"): clen = int(self.headers["Content-Length"]) content = self.rfile.read(clen) else: content = "" return HttpRequest(method, uri, version, headers, content=content)
def get_request (self): """ Get HttpRequest from internal data """ method = self.command uri = self.path vparts = self.request_version.split('/', 1)[1].split(".") version = (int(vparts[0]), int(vparts[1])) headers = [line[:-1] for line in self.headers.headers] if self.headers.has_key("Content-Length"): clen = int(self.headers["Content-Length"]) content = self.rfile.read(clen) else: content = "" return HttpRequest(method, uri, version, headers, content=content)
15,545
def start_server (self): """ Start a HTTP server which is ready for use. @return: http server @rtype: BaseHTTPServer.HTTPServer """ port = 8000 server_address = ('', port) HandlerClass = HttpRequestHandler HandlerClass.protocol_version = "HTTP/1.1" ServerClass = BaseHTTPServer.HTTPServer httpd = ServerClass(server_address, HandlerClass) httpd.tester = self return httpd
def start_server (self): """ Start a HTTP server which is ready for use. @return: http server @rtype: BaseHTTPServer.HTTPServer """ port = 8000 server_address = ('', port) HandlerClass = HttpRequestHandler HandlerClass.protocol_version = "HTTP/1.1" ServerClass = HttpServer httpd = ServerClass(server_address, HandlerClass) httpd.tester = self return httpd
15,546
def construct_response_data (self, response): """ Construct valid HTTP response data string. """ lines = [] version = "HTTP/%d.%d" % response.version lines.append("%s %d %s" % (version, response.status, response.msg)) lines.extend(response.headers) # an empty line ends the headers lines.extend(("", "")) data = "\r\n".join(lines) if response.content: data += response.content return data
def construct_response_data (self, response): """ Construct a HTTP response data string. """ lines = [] version = "HTTP/%d.%d" % response.version lines.append("%s %d %s" % (version, response.status, response.msg)) lines.extend(response.headers) # an empty line ends the headers lines.extend(("", "")) data = "\r\n".join(lines) if response.content: data += response.content return data
15,547
def get_response_data (response, url): """parse a response status line into tokens (protocol, status, msg)""" parts = response.split(None, 2) if len(parts) == 2: wc.log.warn(wc.LOG_PROXY, "Empty response message from %r", url) parts += ['Bummer'] elif len(parts) != 3: wc.log.error(wc.LOG_PROXY, "Invalid response %r from %r", response, url) parts = ['HTTP/1.0', 200, 'Ok'] if not is_http_status(parts[1]): wc.log.error(wc.LOG_PROXY, "Invalid http statuscode %r from %r", parts[1], url) parts[1] = 200 parts[1] = int(parts[1]) return parts
def get_response_data (response, url): """parse a response status line into tokens (protocol, status, msg)""" parts = response.split(None, 2) if len(parts) == 2: wc.log.warn(wc.LOG_PROXY, "Empty response message from %r", url) parts += ['Bummer'] elif len(parts) != 3: wc.log.error(wc.LOG_PROXY, "Invalid response %r from %r", response, url) parts = ['HTTP/1.0', "200", 'Ok'] if not is_http_status(parts[1]): wc.log.error(wc.LOG_PROXY, "Invalid http statuscode %r from %r", parts[1], url) parts[1] = 200 parts[1] = int(parts[1]) return parts
15,548
def get_response_data (response, url): """parse a response status line into tokens (protocol, status, msg)""" parts = response.split(None, 2) if len(parts) == 2: wc.log.warn(wc.LOG_PROXY, "Empty response message from %r", url) parts += ['Bummer'] elif len(parts) != 3: wc.log.error(wc.LOG_PROXY, "Invalid response %r from %r", response, url) parts = ['HTTP/1.0', 200, 'Ok'] if not is_http_status(parts[1]): wc.log.error(wc.LOG_PROXY, "Invalid http statuscode %r from %r", parts[1], url) parts[1] = 200 parts[1] = int(parts[1]) return parts
def get_response_data (response, url): """parse a response status line into tokens (protocol, status, msg)""" parts = response.split(None, 2) if len(parts) == 2: wc.log.warn(wc.LOG_PROXY, "Empty response message from %r", url) parts += ['Bummer'] elif len(parts) != 3: wc.log.error(wc.LOG_PROXY, "Invalid response %r from %r", response, url) parts = ['HTTP/1.0', 200, 'Ok'] if not is_http_status(parts[1]): wc.log.error(wc.LOG_PROXY, "Invalid http statuscode %r from %r", parts[1], url) parts[1] = "200" parts[1] = int(parts[1]) return parts
15,549
def __str__ (self): """return rule data as string""" return super(HeaderRule, self).__str__() + \ ("\nname: %r\nvalue: %r" % (self.name, self.value))
def __str__ (self): """return rule data as string""" return super(HeaderRule, self).__str__() + \ ("\nname: %r\nvalue: %r" % (self.name, self.value))
15,550
def _main (): """USAGE: test/run.sh test/filterfile.py <config dir> <.html file>""" if len(sys.argv)!=3: print _main.__doc__ sys.exit(1) confdir = sys.argv[1] fname = sys.argv[2] if fname=="-": f = sys.stdin else: f = file(fname) logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name, filelogs=False) wc.config = wc.Configuration(confdir=confdir) wc.config.init_filter_modules() headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = "text/html" attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY], headers=headers, serverheaders=headers) filtered = "" data = f.read(2048) while data: print >>sys.stderr, "Test: data", len(data) try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs) except wc.filter.FilterException, msg: print >>sys.stderr, "Test: exception:", msg pass data = f.read(2048) print >>sys.stderr, "Test: finishing" i = 1 while True: print >>sys.stderr, "Test: finish", i try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs) break except wc.filter.FilterException, msg: print >>sys.stderr, "Test: finish: exception:", msg wc.proxy.proxy_poll(timeout=max(0, wc.proxy.run_timers())) i += 1 if i==200: # background downloading if javascript is too slow print >>sys.stderr, "Test: oooooops" break print "Filtered:", filtered
def _main (): """USAGE: test/run.sh test/filterfile.py <config dir> <.html file>""" if len(sys.argv)!=3: print _main.__doc__ sys.exit(1) confdir = sys.argv[1] fname = sys.argv[2] if fname=="-": f = sys.stdin else: f = file(fname) logfile = os.path.join(confdir, "logging.conf") wc.initlog(logfile, wc.Name, filelogs=False) wc.configuration.config = wc.configuration.Configuration(confdir=confdir) wc.configuration.config.init_filter_modules() wc.proxy.dns_lookups.init_resolver() headers = wc.proxy.Headers.WcMessage() headers['Content-Type'] = "text/html" attrs = wc.filter.get_filterattrs(fname, [wc.filter.FILTER_RESPONSE_MODIFY], headers=headers, serverheaders=headers) filtered = "" data = f.read(2048) while data: print >>sys.stderr, "Test: data", len(data) try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, data, 'filter', attrs) except wc.filter.FilterException, msg: print >>sys.stderr, "Test: exception:", msg pass data = f.read(2048) print >>sys.stderr, "Test: finishing" i = 1 while True: print >>sys.stderr, "Test: finish", i try: filtered += wc.filter.applyfilter(wc.filter.FILTER_RESPONSE_MODIFY, "", 'finish', attrs) break except wc.filter.FilterException, msg: print >>sys.stderr, "Test: finish: exception:", msg wc.proxy.proxy_poll(timeout=max(0, wc.proxy.run_timers())) i += 1 if i==200: # background downloading if javascript is too slow print >>sys.stderr, "Test: oooooops" break print "Filtered:", filtered
15,551
def jsProcessData (self, data): """process data produced by document.write() JavaScript""" self._debug(NIGHTMARE, "JS: document.write", `data`) self.js_output += 1 # parse recursively self.js_html.feed(data)
def jsProcessData (self, data): """process data produced by document.write() JavaScript""" self.js_output += 1 # parse recursively self.js_html.feed(data)
15,552
def jsProcessPopup (self): """process javascript popup""" self._debug(NIGHTMARE, "JS: popup") self.js_popup += 1
def jsProcessPopup (self): """process javascript popup""" self.js_popup += 1
15,553
def buf_append_data (self, data): """we have to make sure that we have no two following DATA things in the tag buffer. Why? To be 100% sure that an ENCLOSED match really matches enclosed data. """ self._debug(NIGHTMARE, "buf_append_data") if data[0]==DATA and self.buf and self.buf[-1][0]==DATA: self.buf[-1][1] += data[1] else: self.buf.append(data)
def buf_append_data (self, data): """we have to make sure that we have no two following DATA things in the tag buffer. Why? To be 100% sure that an ENCLOSED match really matches enclosed data. """ if data[0]==DATA and self.buf and self.buf[-1][0]==DATA: self.buf[-1][1] += data[1] else: self.buf.append(data)
15,554
def flushbuf (self): """clear and return the output buffer""" self._debug(NIGHTMARE, "flushbuf") data = self.outbuf.getvalue() self.outbuf.close() self.outbuf = StringIO() return data
def flushbuf (self): """clear and return the output buffer""" data = self.outbuf.getvalue() self.outbuf.close() self.outbuf = StringIO() return data
15,555
def _debugbuf (self): """print debugging information about data buffer status""" self._debug(NIGHTMARE, "self.outbuf", `self.outbuf.getvalue()`) self._debug(NIGHTMARE, "self.buf", `self.buf`) self._debug(NIGHTMARE, "self.waitbuf", `self.waitbuf`) self._debug(NIGHTMARE, "self.inbuf", `self.inbuf.getvalue()`)
def _debugbuf (self): """print debugging information about data buffer status""" self._debug(NIGHTMARE, "self.outbuf", `self.outbuf.getvalue()`) self._debug(NIGHTMARE, "self.buf", `self.buf`) self._debug(NIGHTMARE, "self.waitbuf", `self.waitbuf`) self._debug(NIGHTMARE, "self.inbuf", `self.inbuf.getvalue()`)
15,556
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data self.parser.feed(data) else: self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
15,557
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: pass else: # wait state --> put in input buffer self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
15,558
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer self._debug(NIGHTMARE, "wait") self.inbuf.write(data)
def feed (self, data): """feed some data to the parser""" if self.state=='parse': # look if we must replay something if self.waited: self.waited = 0 waitbuf, self.waitbuf = self.waitbuf, [] self.replay(waitbuf) if self.state!='parse': self.inbuf.write(data) return data = self.inbuf.getvalue() + data self.inbuf.close() self.inbuf = StringIO() if data: # only feed non-empty data self._debug(NIGHTMARE, "feed", `data`) self.parser.feed(data) else: self._debug(NIGHTMARE, "feed") pass else: # wait state --> put in input buffer self.inbuf.write(data)
15,559
def flush (self): self._debug(HURT_ME_PLENTY, "flush") # flushing in wait state raises a filter exception if self.state=='wait': raise FilterWait("HtmlParser[%d]: waiting for data"%self.level) self.parser.flush()
def flush (self): # flushing in wait state raises a filter exception if self.state=='wait': raise FilterWait("HtmlParser[%d]: waiting for data"%self.level) self.parser.flush()
15,560
def replay (self, waitbuf): """call the handler functions again with buffer data""" self._debug(NIGHTMARE, "replay", waitbuf) for item in waitbuf: if item[0]==DATA: self._data(item[1]) elif item[0]==STARTTAG: self.startElement(item[1], item[2]) elif item[0]==ENDTAG: self.endElement(item[1]) elif item[0]==COMMENT: self.comment(item[1])
def replay (self, waitbuf): """call the handler functions again with buffer data""" for item in waitbuf: if item[0]==DATA: self._data(item[1]) elif item[0]==STARTTAG: self.startElement(item[1], item[2]) elif item[0]==ENDTAG: self.endElement(item[1]) elif item[0]==COMMENT: self.comment(item[1])
15,561
def cdata (self, data): """character data""" self._debug(NIGHTMARE, "cdata", `data`) return self._data(data)
def cdata (self, data): """character data""" return self._data(data)
15,562
def characters (self, data): """characters""" self._debug(NIGHTMARE, "characters", `data`) return self._data(data)
def characters (self, data): """characters""" return self._data(data)
15,563
def comment (self, data): """a comment; accept only non-empty comments""" self._debug(NIGHTMARE, "comment", `data`) item = [COMMENT, data] if self.state=='wait': return self.waitbuf.append(item) if self.comments and data: self.buf.append(item)
def comment (self, data): """a comment; accept only non-empty comments""" item = [COMMENT, data] if self.state=='wait': return self.waitbuf.append(item) if self.comments and data: self.buf.append(item)
15,564
def doctype (self, data): self._debug(NIGHTMARE, "doctype", `data`) return self._data("<!DOCTYPE%s>"%data)
def doctype (self, data): return self._data("<!DOCTYPE%s>"%data)
15,565
def pi (self, data): self._debug(NIGHTMARE, "pi", `data`) return self._data("<?%s?>"%data)
def pi (self, data): return self._data("<?%s?>"%data)
15,566
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data self._debug(NIGHTMARE, "startElement", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = resolve_html_entities(attrs['href']) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): self._debug(NIGHTMARE, "matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: self._debug(NIGHTMARE, "put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
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 tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = resolve_html_entities(attrs['href']) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): self._debug(NIGHTMARE, "matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: self._debug(NIGHTMARE, "put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
15,567
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data self._debug(NIGHTMARE, "startElement", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = resolve_html_entities(attrs['href']) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): self._debug(NIGHTMARE, "matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: self._debug(NIGHTMARE, "put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data self._debug(NIGHTMARE, "startElement", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = resolve_html_entities(attrs['href']) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: self._debug(NIGHTMARE, "put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
15,568
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data self._debug(NIGHTMARE, "startElement", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = resolve_html_entities(attrs['href']) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): self._debug(NIGHTMARE, "matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: self._debug(NIGHTMARE, "put on buffer") rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
def startElement (self, tag, attrs): """We get a new start tag. New rules could be appended to the pending rules. No rules can be removed from the list.""" # default data self._debug(NIGHTMARE, "startElement", `tag`) tag = check_spelling(tag, self.url) item = [STARTTAG, tag, attrs] if self.state=='wait': return self.waitbuf.append(item) rulelist = [] filtered = 0 if tag=="meta" and \ attrs.get('http-equiv', '').lower() =='pics-label': labels = resolve_html_entities(attrs.get('content', '')) # note: if there are no pics rules, this loop is empty for rule in self.pics: msg = check_pics(rule, labels) if msg: raise FilterPics(msg) # first labels match counts self.pics = [] elif tag=="body": # headers finished if self.pics: # no pics data found self.pics = [] elif tag=="base" and attrs.has_key('href'): self.base_url = resolve_html_entities(attrs['href']) # look for filter rules which apply for rule in self.rules: if rule.match_tag(tag) and rule.match_attrs(attrs): self._debug(NIGHTMARE, "matched rule %s on tag %s" % (`rule.title`, `tag`)) if rule.start_sufficient: item = rule.filter_tag(tag, attrs) filtered = "True" if item[0]==STARTTAG and item[1]==tag: foo,tag,attrs = item # give'em a chance to replace more than one attribute continue else: break else: rulelist.append(rule) if rulelist: # remember buffer position for end tag matching pos = len(self.buf) self.rulestack.append((pos, rulelist)) if filtered: self.buf_append_data(item) elif self.js_filter: # if its not yet filtered, try filter javascript self.jsStartElement(tag, attrs) else: self.buf.append(item) # if rule stack is empty, write out the buffered data if not self.rulestack and not self.js_filter: self.buf2data()
15,569
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.
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.
15,570
def jsStartElement (self, tag, attrs): """Check popups for onmouseout and onmouseover. Inline extern javascript sources""" changed = 0 self.js_src = None self.js_output = 0 self.js_popup = 0 for name in ('onmouseover', 'onmouseout'): if attrs.has_key(name) and self.jsPopup(attrs, name): self._debug(NIGHTMARE, "JS: del", `name`, "from", `tag`) del attrs[name] changed = 1 if tag=='form': name = attrs.get('name', attrs.get('id')) self.jsForm(name, attrs.get('action', ''), attrs.get('target', '')) elif tag=='script': lang = attrs.get('language', '').lower() url = attrs.get('src', '') scrtype = attrs.get('type', '').lower() is_js = scrtype=='text/javascript' or \ lang.startswith('javascript') or \ not (lang or scrtype) if is_js and url: return self.jsScriptSrc(url, lang) self.buf.append([STARTTAG, tag, attrs])
def jsStartElement (self, tag, attrs): """Check popups for onmouseout and onmouseover. Inline extern javascript sources""" changed = 0 self.js_src = None self.js_output = 0 self.js_popup = 0 for name in ('onmouseover', 'onmouseout'): if attrs.has_key(name) and self.jsPopup(attrs, name): del attrs[name] changed = 1 if tag=='form': name = attrs.get('name', attrs.get('id')) self.jsForm(name, attrs.get('action', ''), attrs.get('target', '')) elif tag=='script': lang = attrs.get('language', '').lower() url = attrs.get('src', '') scrtype = attrs.get('type', '').lower() is_js = scrtype=='text/javascript' or \ lang.startswith('javascript') or \ not (lang or scrtype) if is_js and url: return self.jsScriptSrc(url, lang) self.buf.append([STARTTAG, tag, attrs])
15,571
def jsPopup (self, attrs, name): """check if attrs[name] javascript opens a popup window""" self._debug(NIGHTMARE, "JS: jsPopup") val = resolve_html_entities(attrs[name]) if not val: return self.js_env.attachListener(self) try: self.js_env.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.js_env.detachListener(self) res = self.js_popup self.js_popup = 0 return res
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.js_env.attachListener(self) try: self.js_env.executeScriptAsFunction(val, 0.0) except jslib.error, msg: pass self.js_env.detachListener(self) res = self.js_popup self.js_popup = 0 return res
15,572
def jsForm (self, name, action, target): """when hitting a (named) form, notify the JS engine about that""" if not name: return 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 self.js_env.addForm(name, action, target)
15,573
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.js_script: print >> sys.stderr, "HtmlParser[%d]: empty JS src"%self.level, url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) script = "\n<!--\n%s\n//-->\n"%escape_js(self.js_script) self.buf.append([DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.js_script = '' self.state = 'parse' self._debug(NIGHTMARE, "switching back to parse with") self._debugbuf() else: 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.js_script: print >> sys.stderr, "HtmlParser[%d]: empty JS src"%self.level, url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) script = "\n<!--\n%s\n//-->\n"%escape_js(self.js_script) self.buf.append([DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.js_script = '' self.state = 'parse' self._debugbuf() else: self._debug(HURT_ME_PLENTY, "JS read", len(data), "<=", url) self.js_script += data
15,574
def jsScriptData (self, data, url, ver): """Callback for loading <script src=""> data in the background If downloading is finished, data is None""" assert self.state=='wait' if data is None: if not self.js_script: print >> sys.stderr, "HtmlParser[%d]: empty JS src"%self.level, url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) script = "\n<!--\n%s\n//-->\n"%escape_js(self.js_script) self.buf.append([DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.js_script = '' self.state = 'parse' self._debug(NIGHTMARE, "switching back to parse with") self._debugbuf() else: 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.js_script: print >> sys.stderr, "HtmlParser[%d]: empty JS src"%self.level, url else: self.buf.append([STARTTAG, "script", {'type': 'text/javascript'}]) script = "\n<!--\n%s\n//-->\n"%escape_js(self.js_script) self.buf.append([DATA, script]) # Note: <script src=""> could be missing an end tag, # but now we need one. Look later for a duplicate </script>. self.buf.append([ENDTAG, "script"]) self.js_script = '' self.state = 'parse' self._debug(NIGHTMARE, "switching back to parse with") self._debugbuf() else: self.js_script += data
15,575
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')) if self.base_url: url = urlparse.urljoin(self.base_url, url) else: url = urlparse.urljoin(self.url, url) self._debug(HURT_ME_PLENTY, "JS jsScriptSrc", `url`, `ver`) if _has_ws(url): print >> sys.stderr, "HtmlParser[%d]: broken JS url"%self.level,\ `url`, "at", `self.url` return self.state = 'wait' self.waited = 'True' self.js_src = 'True' client = HttpProxyClient(self.jsScriptData, (url, ver)) ClientServerMatchmaker(client, "GET %s HTTP/1.1" % url, #request {}, #headers '', #content {'nofilter': None}, # nofilter 'identity', # compress mime = "application/x-javascript", )
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')) if self.base_url: url = urlparse.urljoin(self.base_url, url) else: url = urlparse.urljoin(self.url, url) if _has_ws(url): print >> sys.stderr, "HtmlParser[%d]: broken JS url"%self.level,\ `url`, "at", `self.url` return self.state = 'wait' self.waited = 'True' self.js_src = 'True' client = HttpProxyClient(self.jsScriptData, (url, ver)) ClientServerMatchmaker(client, "GET %s HTTP/1.1" % url, #request {}, #headers '', #content {'nofilter': None}, # nofilter 'identity', # compress mime = "application/x-javascript", )
15,576
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) # start recursive html filter (used by jsProcessData) self.js_html = FilterHtmlParser(self.rules, self.pics, self.url, comments=self.comments, javascript=self.js_filter, level=self.level+1) # execute self.js_env.executeScript(unescape_js(script), ver) self.js_env.detachListener(self) # wait for recursive filter to finish self.jsEndScript(item)
def jsScript (self, script, ver, item): """execute given script with javascript version ver""" assert self.state == 'parse' assert len(self.buf) >= 2 self.js_output = 0 self.js_env.attachListener(self) # start recursive html filter (used by jsProcessData) self.js_html = FilterHtmlParser(self.rules, self.pics, self.url, comments=self.comments, javascript=self.js_filter, level=self.level+1) # execute self.js_env.executeScript(unescape_js(script), ver) self.js_env.detachListener(self) # wait for recursive filter to finish self.jsEndScript(item)
15,577
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 FilterWait: self.state = 'wait' self.waited = 'True' make_timer(0.1, lambda : self.jsEndScript(item)) return self.js_html._debugbuf() assert not self.js_html.inbuf.getvalue() assert not self.js_html.waitbuf assert len(self.buf) >= 2 self.buf[-2:-2] = [[DATA, self.js_html.outbuf.getvalue()]]+self.js_html.buf self.js_html = None if (self.js_popup + self.js_output) > 0: # delete old script del self.buf[-1] del self.buf[-1] elif not self.filterEndElement(item[1]): self.buf.append(item) self._debug(NIGHTMARE, "JS: switching back to parse with") self._debugbuf() self.state = 'parse'
def jsEndScript (self, item): assert len(self.buf) >= 2 if self.js_output: try: self.js_html.feed('') self.js_html.flush() except FilterWait: self.state = 'wait' self.waited = 'True' make_timer(0.1, lambda : self.jsEndScript(item)) return self.js_html._debugbuf() assert not self.js_html.inbuf.getvalue() assert not self.js_html.waitbuf assert len(self.buf) >= 2 self.buf[-2:-2] = [[DATA, self.js_html.outbuf.getvalue()]]+self.js_html.buf self.js_html = None if (self.js_popup + self.js_output) > 0: # delete old script del self.buf[-1] del self.buf[-1] elif not self.filterEndElement(item[1]): self.buf.append(item) self._debug(NIGHTMARE, "JS: switching back to parse with") self._debugbuf() self.state = 'parse'
15,578
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 FilterWait: self.state = 'wait' self.waited = 'True' make_timer(0.1, lambda : self.jsEndScript(item)) return self.js_html._debugbuf() assert not self.js_html.inbuf.getvalue() assert not self.js_html.waitbuf assert len(self.buf) >= 2 self.buf[-2:-2] = [[DATA, self.js_html.outbuf.getvalue()]]+self.js_html.buf self.js_html = None if (self.js_popup + self.js_output) > 0: # delete old script del self.buf[-1] del self.buf[-1] elif not self.filterEndElement(item[1]): self.buf.append(item) self._debug(NIGHTMARE, "JS: switching back to parse with") self._debugbuf() self.state = 'parse'
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 FilterWait: self.state = 'wait' self.waited = 'True' make_timer(0.1, lambda : self.jsEndScript(item)) return self.js_html._debugbuf() assert not self.js_html.inbuf.getvalue() assert not self.js_html.waitbuf assert len(self.buf) >= 2 self.buf[-2:-2] = [[DATA, self.js_html.outbuf.getvalue()]]+self.js_html.buf self.js_html = None if (self.js_popup + self.js_output) > 0: # delete old script del self.buf[-1] del self.buf[-1] elif not self.filterEndElement(item[1]): self.buf.append(item) self._debugbuf() self.state = 'parse'
15,579
def applyfilter (filterstage, data, fun, attrs): """ Apply all filters which are registered in the given filter stage. For different filter stages we have different data objects. Look at the filter examples. One can prevent all filtering with the 'nofilter' attribute, or deactivate single filter modules with 'nofilter-<name>', for example 'nofilter-blocker'. """ attrs['filterstage'] = filterstage assert None == wc.log.debug(wc.LOG_FILTER, "Filter (%s) %d bytes in %s..", fun, len(data), filterstage) if attrs.get('nofilter') or (fun != 'finish' and not data): assert None == wc.log.debug(wc.LOG_FILTER, "..don't filter") return data for f in wc.configuration.config['filterlist'][filterstage]: assert None == wc.log.debug(wc.LOG_FILTER, "..filter with %s" % f) if f.applies_to_mime(attrs['mime']) and \ not "nofilter-%s" % str(f).lower() in attrs: assert None == wc.log.debug(wc.LOG_FILTER, "..applying") data = getattr(f, fun)(data, attrs) else: assert None == wc.log.debug(wc.LOG_FILTER, "..not applying") assert None == wc.log.debug(wc.LOG_FILTER, "..result %d bytes", len(data)) return data
def applyfilter (filterstage, data, fun, attrs): """ Apply all filters which are registered in the given filter stage. For different filter stages we have different data objects. Look at the filter examples. One can prevent all filtering with the 'nofilter' attribute, or deactivate single filter modules with 'nofilter-<name>', for example 'nofilter-blocker'. """ attrs['filterstage'] = filterstage assert None == wc.log.debug(wc.LOG_FILTER, "Filter (%s) %d bytes in %s..", fun, len(data), filterstage) if attrs.get('nofilter') or (fun != 'finish' and not data): assert None == wc.log.debug(wc.LOG_FILTER, "..don't filter") return data for f in wc.configuration.config['filterlist'][filterstage]: assert None == wc.log.debug(wc.LOG_FILTER, "..filter with %s" % f) if f.applies_to_mime(attrs['mime']) and \ not "nofilter-%s" % str(f).lower() in attrs: assert None == wc.log.debug(wc.LOG_FILTER, "..applying") data = getattr(f, fun)(data, attrs) else: assert None == wc.log.debug(wc.LOG_FILTER, "..not applying (mime %s)" % attrs['mime']) assert None == wc.log.debug(wc.LOG_FILTER, "..result %d bytes", len(data)) return data
15,580
def stopwatch (pidfile, watchfile): """stop webcleaner and the monitor""" if not os.path.exists(watchfile): return i18n._("Watcher was not running (no lock file found)"), 1 msg, status = _stop(watchfile) msg2, status2 = stop(pidfile) return "%s\n%s"%(msg,msg2), status2
def stopwatch (pidfile, watchfile): """stop webcleaner and the monitor""" if not os.path.exists(watchfile): return i18n._("Watcher was not running (no lock file found)"), 1 msg1, status1 = _stop(watchfile) msg2, status2 = stop(pidfile) return "%s\n%s"%(msg,msg2), status2
15,581
def stopwatch (pidfile, watchfile): """stop webcleaner and the monitor""" if not os.path.exists(watchfile): return i18n._("Watcher was not running (no lock file found)"), 1 msg, status = _stop(watchfile) msg2, status2 = stop(pidfile) return "%s\n%s"%(msg,msg2), status2
def stopwatch (pidfile, watchfile): """stop webcleaner and the monitor""" if not os.path.exists(watchfile): return i18n._("Watcher was not running (no lock file found)"), 1 msg, status = _stop(watchfile) msg2, status2 = stop(pidfile) if msg1: if msg2: msg = "%s\n%s"%(msg1,msg2) else: msg = msg1 else: msg = msg2 if status1: status = status1 else: status = status2 return msg, status
15,582
def toxml (self): """Rule data as XML for storing""" s = u"""<?xml version="1.0" encoding="%s"?>
def toxml (self): """Rule data as XML for storing""" s = u"""<?xml version="1.0" encoding="%s"?>
15,583
def process_headers (self): i = self.recv_buffer.find('\r\n\r\n') if i >= 0: # Two newlines ends headers i += 4 # Skip over newline terminator # the first 2 chars are the newline of request data = self.read(i)[2:] self.headers = rfc822.Message(StringIO(data)) #debug(HURT_ME_PLENTY, "Proxy: C/Headers", `self.headers.headers`) # set via header via = self.headers.get('Via', "").strip() if via: via += " " via += "1.1 unknown\r" self.headers['Via'] = via self.headers = applyfilter(FILTER_REQUEST_HEADER, self.headers, fun="finish", attrs=self.nofilter) # remember if client understands gzip self.compress = 'identity' encodings = self.headers.get('Accept-Encoding', '') for accept in encodings.split(','): if ';' in accept: accept, q = accept.split(';', 1) if accept.strip().lower() in ('gzip', 'x-gzip'): self.compress = 'gzip' break # we understand gzip, deflate and identity self.headers['Accept-Encoding'] = \ 'gzip;q=1.0, deflate;q=0.9, identity;q=0.5\r' # add decoders self.decoders = [] # Chunked encoded if self.headers.get('Transfer-Encoding') is not None: debug(BRING_IT_ON, 'Proxy: C/Transfer-encoding:', `self.headers['transfer-encoding']`) self.decoders.append(UnchunkStream()) # remove encoding header to_remove = ["Transfer-Encoding"] if self.headers.get("Content-Length") is not None: print >>sys.stderr, 'Warning: chunked encoding should not have Content-Length' to_remove.append("Content-Length") self.bytes_remaining = None remove_headers(self.headers, to_remove) # add warning self.headers['Warning'] = "214 Transformation applied\r" debug(HURT_ME_PLENTY, "Proxy: C/Headers", `str(self.headers)`) if self.headers.has_key('Content-Length'): self.bytes_remaining = int(self.headers['Content-Length']) if config["proxyuser"] and not self.check_proxy_auth(): return self.error(407, i18n._("Proxy Authentication Required")) if self.method=='OPTIONS': mf = int(self.headers.get('Max-Forwards', -1)) if mf==0: # XXX display options ? self.state = 'done' ServerHandleDirectly(self, 'HTTP/1.0 200 OK\r\n', 'Content-Type: text/plain\r\n\r\n', '') return if mf>0: self.headers['Max-Forwards'] = mf-1 self.state = 'content'
def process_headers (self): i = self.recv_buffer.find('\r\n\r\n') if i >= 0: # Two newlines ends headers i += 4 # Skip over newline terminator # the first 2 chars are the newline of request data = self.read(i)[2:] self.headers = rfc822.Message(StringIO(data)) #debug(HURT_ME_PLENTY, "Proxy: C/Headers", `self.headers.headers`) # set via header via = self.headers.get('Via', "").strip() if via: via += " " via += "1.1 unknown\r" self.headers['Via'] = via self.headers = applyfilter(FILTER_REQUEST_HEADER, self.headers, fun="finish", attrs=self.nofilter) # remember if client understands gzip self.compress = 'identity' encodings = self.headers.get('Accept-Encoding', '') for accept in encodings.split(','): if ';' in accept: accept, q = accept.split(';', 1) if accept.strip().lower() in ('gzip', 'x-gzip'): self.compress = 'gzip' break # we understand gzip, deflate and identity self.headers['Accept-Encoding'] = \ 'gzip;q=1.0, deflate;q=0.9, identity;q=0.5\r' # add decoders self.decoders = [] # Chunked encoded if self.headers.get('Transfer-Encoding') is not None: debug(BRING_IT_ON, 'Proxy: C/Transfer-encoding:', `self.headers['transfer-encoding']`) self.decoders.append(UnchunkStream()) # remove encoding header to_remove = ["Transfer-Encoding"] if self.headers.get("Content-Length") is not None: print >>sys.stderr, 'Warning: chunked encoding should not have Content-Length' to_remove.append("Content-Length") self.bytes_remaining = None remove_headers(self.headers, to_remove) # add warning self.headers['Warning'] = "214 Transformation applied\r" debug(HURT_ME_PLENTY, "Proxy: C/Headers", `str(self.headers)`) if self.headers.has_key('Content-Length'): self.bytes_remaining = int(self.headers['Content-Length']) if config["proxyuser"] and not self.check_proxy_auth(): return self.error(407, i18n._("Proxy Authentication Required")) if self.method=='OPTIONS': mf = int(self.headers.get('Max-Forwards', -1)) if mf==0: # XXX display options ? self.state = 'done' ServerHandleDirectly(self, 'HTTP/1.0 200 OK\r\n', 'Content-Type: text/plain\r\n\r\n', '') return if mf>0: self.headers['Max-Forwards'] = mf-1 self.state = 'content'
15,584
def process_headers (self): i = self.recv_buffer.find('\r\n\r\n') if i >= 0: # Two newlines ends headers i += 4 # Skip over newline terminator # the first 2 chars are the newline of request data = self.read(i)[2:] self.headers = rfc822.Message(StringIO(data)) #debug(HURT_ME_PLENTY, "Proxy: C/Headers", `self.headers.headers`) # set via header via = self.headers.get('Via', "").strip() if via: via += " " via += "1.1 unknown\r" self.headers['Via'] = via self.headers = applyfilter(FILTER_REQUEST_HEADER, self.headers, fun="finish", attrs=self.nofilter) # remember if client understands gzip self.compress = 'identity' encodings = self.headers.get('Accept-Encoding', '') for accept in encodings.split(','): if ';' in accept: accept, q = accept.split(';', 1) if accept.strip().lower() in ('gzip', 'x-gzip'): self.compress = 'gzip' break # we understand gzip, deflate and identity self.headers['Accept-Encoding'] = \ 'gzip;q=1.0, deflate;q=0.9, identity;q=0.5\r' # add decoders self.decoders = [] # Chunked encoded if self.headers.get('Transfer-Encoding') is not None: debug(BRING_IT_ON, 'Proxy: C/Transfer-encoding:', `self.headers['transfer-encoding']`) self.decoders.append(UnchunkStream()) # remove encoding header to_remove = ["Transfer-Encoding"] if self.headers.get("Content-Length") is not None: print >>sys.stderr, 'Warning: chunked encoding should not have Content-Length' to_remove.append("Content-Length") self.bytes_remaining = None remove_headers(self.headers, to_remove) # add warning self.headers['Warning'] = "214 Transformation applied\r" debug(HURT_ME_PLENTY, "Proxy: C/Headers", `str(self.headers)`) if self.headers.has_key('Content-Length'): self.bytes_remaining = int(self.headers['Content-Length']) if config["proxyuser"] and not self.check_proxy_auth(): return self.error(407, i18n._("Proxy Authentication Required")) if self.method=='OPTIONS': mf = int(self.headers.get('Max-Forwards', -1)) if mf==0: # XXX display options ? self.state = 'done' ServerHandleDirectly(self, 'HTTP/1.0 200 OK\r\n', 'Content-Type: text/plain\r\n\r\n', '') return if mf>0: self.headers['Max-Forwards'] = mf-1 self.state = 'content'
def process_headers (self): i = self.recv_buffer.find('\r\n\r\n') if i >= 0: # Two newlines ends headers i += 4 # Skip over newline terminator # the first 2 chars are the newline of request data = self.read(i)[2:] self.headers = rfc822.Message(StringIO(data)) #debug(HURT_ME_PLENTY, "Proxy: C/Headers", `self.headers.headers`) # set via header via = self.headers.get('Via', "").strip() if via: via += " " via += "1.1 unknown\r" self.headers['Via'] = via self.headers = applyfilter(FILTER_REQUEST_HEADER, self.headers, fun="finish", attrs=self.nofilter) # remember if client understands gzip self.compress = 'identity' encodings = self.headers.get('Accept-Encoding', '') for accept in encodings.split(','): if ';' in accept: accept, q = accept.split(';', 1) if accept.strip().lower() in ('gzip', 'x-gzip'): self.compress = 'gzip' break # we understand gzip, deflate and identity self.headers['Accept-Encoding'] = \ 'gzip;q=1.0, deflate;q=0.9, identity;q=0.5\r' # add decoders self.decoders = [] # Chunked encoded if self.headers.get('Transfer-Encoding') is not None: debug(BRING_IT_ON, 'Proxy: C/Transfer-encoding:', `self.headers['transfer-encoding']`) self.decoders.append(UnchunkStream()) # remove encoding header to_remove = ["Transfer-Encoding"] if self.headers.get("Content-Length") is not None: print >>sys.stderr, 'Warning: chunked encoding should not have Content-Length' to_remove.append("Content-Length") self.bytes_remaining = None remove_headers(self.headers, to_remove) # add warning self.headers['Warning'] = "214 Transformation applied\r" debug(HURT_ME_PLENTY, "Proxy: C/Headers", `str(self.headers)`) if config["proxyuser"] and not self.check_proxy_auth(): return self.error(407, i18n._("Proxy Authentication Required")) if self.method=='OPTIONS': mf = int(self.headers.get('Max-Forwards', -1)) if mf==0: # XXX display options ? self.state = 'done' ServerHandleDirectly(self, 'HTTP/1.0 200 OK\r\n', 'Content-Type: text/plain\r\n\r\n', '') return if mf>0: self.headers['Max-Forwards'] = mf-1 self.state = 'content'
15,585
def fix_configdata (): """ Fix install and config paths in the config file. """ name = "_webcleaner2_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_") or \ line.startswith("template_"): lines.append(fix_install_path(line)) else: lines.append(line) f = file(conffile, "w") f.write("".join(lines)) f.close()
def fix_configdata (): """ Fix install and config paths in the config file. """ name = "_webcleaner2_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_") or \ line.startswith("template_"): lines.append(fix_install_path(line.rstrip())) else: lines.append(line) f = file(conffile, "w") f.write("".join(lines)) f.close()
15,586
def do_quit (event=None): root.destroy()
def do_quit (event=None): root.destroy()
15,587
def purge_tempfiles (): """ Ask if user wants to purge local config files. """ import wc files = glob.glob(os.path.join(wc.ConfigDir, "local_*.zap")) if not files: return import tkMessageBox answer = tkMessageBox.askyesno(_("%s config purge") % wc.AppName, _("""There are local filter rules in the configuration directory.
def purge_tempfiles (): """ Ask if user wants to purge local config files. """ import wc files = glob.glob(os.path.join(wc.ConfigDir, "local_*.zap")) if not files: return import tkMessageBox answer = tkMessageBox.askyesno(_("%s config purge") % wc.AppName, _("""There are local filter rules in the configuration directory.
15,588
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(self.read(m.end())) msg = WcMessage(fp) # put unparsed data (if any) back to the buffer msg.rewindbody() self.recv_buffer = fp.read() + self.recv_buffer debug(PROXY, "%s server headers\n%s", self, msg) 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 http_ver = serverpool.http_versions[self.addr] if http_ver >= (1,1): self.persistent = not has_header_value(msg, 'Connection', 'Close') elif http_ver >= (1,0): self.persistent = has_header_value(msg, 'Connection', 'Keep-Alive') else: self.persistent = False self.attrs = get_filterattrs(self.url, [FILTER_RESPONSE_HEADER], headers=msg) try: self.headers = applyfilter(FILTER_RESPONSE_HEADER, msg, "finish", self.attrs) except FilterRating, msg: debug(PROXY, "%s FilterRating from header: %s", self, msg) msg = str(msg) if msg==rating.MISSING: self.show_rating_config(msg) else: self.show_rating_deny(msg) return server_set_headers(self.headers) self.bytes_remaining = server_set_encoding_headers(self.headers, self.is_rewrite(), self.decoders, self.bytes_remaining) # 304 Not Modified does not send any type info, because it was cached if self.statuscode!=304: # copy decoders decoders = [ d.__class__() for d in self.decoders] data = self.recv_buffer for decoder in decoders: data = decoder.decode(data) data += flush_decoders(decoders) server_set_content_headers(self.headers, data, self.document, self.mime, self.url) # XXX <doh> #if not self.headers.has_key('Content-Length'): # self.headers['Connection'] = 'close\r' #remove_headers(self.headers, ['Keep-Alive']) # XXX </doh> if self.statuscode in (204, 304) or self.method == 'HEAD': # These response codes indicate no content self.client.server_response(self, self.response, self.statuscode, self.headers) self.data_written = True self.state = 'recycle' else: self.state = 'content' self.attrs = get_filterattrs(self.url, _response_filters, headers=msg) debug(PROXY, "%s filtered headers %s", self, self.headers)
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(self.read(m.end())) msg = WcMessage(fp) # put unparsed data (if any) back to the buffer msg.rewindbody() self.recv_buffer = fp.read() + self.recv_buffer debug(PROXY, "%s server headers\n%s", self, msg) 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 http_ver = serverpool.http_versions[self.addr] if http_ver >= (1,1): self.persistent = not has_header_value(msg, 'Connection', 'Close') elif http_ver >= (1,0): self.persistent = has_header_value(msg, 'Connection', 'Keep-Alive') else: self.persistent = False self.attrs = get_filterattrs(self.url, [FILTER_RESPONSE_HEADER], headers=msg) try: self.headers = applyfilter(FILTER_RESPONSE_HEADER, msg, "finish", self.attrs) except FilterRating, msg: debug(PROXY, "%s FilterRating from header: %s", self, msg) msg = str(msg) if msg==MISSING: self.show_rating_config(msg) else: self.show_rating_deny(msg) return server_set_headers(self.headers) self.bytes_remaining = server_set_encoding_headers(self.headers, self.is_rewrite(), self.decoders, self.bytes_remaining) # 304 Not Modified does not send any type info, because it was cached if self.statuscode!=304: # copy decoders decoders = [ d.__class__() for d in self.decoders] data = self.recv_buffer for decoder in decoders: data = decoder.decode(data) data += flush_decoders(decoders) server_set_content_headers(self.headers, data, self.document, self.mime, self.url) # XXX <doh> #if not self.headers.has_key('Content-Length'): # self.headers['Connection'] = 'close\r' #remove_headers(self.headers, ['Keep-Alive']) # XXX </doh> if self.statuscode in (204, 304) or self.method == 'HEAD': # These response codes indicate no content self.client.server_response(self, self.response, self.statuscode, self.headers) self.data_written = True self.state = 'recycle' else: self.state = 'content' self.attrs = get_filterattrs(self.url, _response_filters, headers=msg) debug(PROXY, "%s filtered headers %s", self, self.headers)
15,589
def check_connect (self, addr): """ Check if the connection is etablished. See also http://cr.yp.to/docs/connect.html and connect(2) manpage. """ wc.log.debug(wc.LOG_PROXY, '%s check connect', self) self.connect_checks += 1 if self.connect_checks >= 50: wc.log.info(wc.LOG_PROXY, '%s connect timed out', self) self.handle_close() return try: (r, w, e) = select.select([], [self.fileno()], [], 0.2) except select.error, why: # not yet ready return if self.fileno() not in w: # not yet ready return err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err == 0: self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() elif err in (errno.EINPROGRESS, errno.EWOULDBLOCK): wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) else: strerr = errno.errorcode[err] wc.log.info(wc.LOG_PROXY, '%s connect error %s', self, strerr) self.handle_close()
def check_connect (self, addr): """ Check if the connection is etablished. See also http://cr.yp.to/docs/connect.html and connect(2) manpage. """ wc.log.debug(wc.LOG_PROXY, '%s check connect', self) self.connect_checks += 1 if self.connect_checks >= 50: wc.log.info(wc.LOG_PROXY, '%s connect timed out', self) self.handle_close() return try: (r, w, e) = select.select([], [self.fileno()], [], 0.2) except select.error, why: # not yet ready return if self.fileno() not in w: # not yet ready return err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err == 0: self.addr = addr self.connected = True wc.log.debug(wc.LOG_PROXY, '%s connected', self) self.handle_connect() elif err in (errno.EINPROGRESS, errno.EWOULDBLOCK): wc.proxy.make_timer(0.2, lambda a=addr: self.check_connect(addr)) else: strerr = errno.errorcode[err] wc.log.info(wc.LOG_PROXY, '%s connect(%s) error %s', self, addr, strerr) self.handle_close()
15,590
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) #debug(HURT_ME_PLENTY, "S/Headers", `self.headers.headers`) # check content-type against our own guess gm = mimetypes.guess_type(self.document, None) if gm[0]: # guessed an own content type if not self.headers.has_key('Content-Type'): self.headers['Content-Type'] = gm[0] print >>sys.stderr, _("Warning: %s guessed Content-Type (%s)") % \ (self.url, gm[0]) elif self.headers.get('Content-Type') != gm[0]: print >>sys.stderr, _("Warning: %s guessed Content-Type (%s) != server Content-Type (%s)") % \ (self.url, gm[0], self.headers.get('Content-Type')) self.headers['Content-Type'] = gm[0] if gm[1]: # guessed an own encoding type if not self.headers.has_key('Content-Encoding'): self.headers['Content-Encoding'] = gm[1] print >>sys.stderr, _("Warning: %s guessed Content-Encoding (%s)") % \ (self.url, gm[1]) elif self.headers.get('Content-Encoding') != gm[1]: print >>sys.stderr, _("Warning: %s guessed Content-Encoding (%s) != server Content-Encoding (%s)") % \ (self.url, gm[1], self.headers.get('Content-Encoding')) self.headers['Content-Encoding'] = gm[1] # will content be rewritten? rewrite = None for ro in config['mime_content_rewriting']: if ro.match(self.headers.get('Content-Type', '')): rewrite = "True" break # add client accept-encoding value self.headers['Accept-Encoding'] = self.client.compress if self.headers.has_key('Content-Length'): self.bytes_remaining = int(self.headers['Content-Length']) #debug(HURT_ME_PLENTY, "%d bytes remaining"%self.bytes_remaining) if rewrite: remove_headers(self.headers, ['Content-Length']) else: self.bytes_remaining = None
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) #debug(HURT_ME_PLENTY, "S/Headers", `self.headers.headers`) # check content-type against our own guess gm = mimetypes.guess_type(self.document, None) if gm[0]: # guessed an own content type if not self.headers.has_key('Content-Type'): self.headers['Content-Type'] = gm[0] print >>sys.stderr, _("Warning: %s guessed Content-Type (%s)") % \ (self.url, gm[0]) elif self.headers.get('Content-Type') != gm[0]: print >>sys.stderr, _("Warning: %s guessed Content-Type (%s) != server Content-Type (%s)") % \ (self.url, gm[0], self.headers.get('Content-Type')) self.headers['Content-Type'] = gm[0] if gm[1]: # guessed an own encoding type if not self.headers.has_key('Content-Encoding'): if gm[1] in _fix_content_types: self.headers['Content-Encoding'] = gm[1] print >>sys.stderr, _("Warning: %s guessed Content-Encoding (%s)") % \ (self.url, gm[1]) elif self.headers.get('Content-Encoding') != gm[1]: print >>sys.stderr, _("Warning: %s guessed Content-Encoding (%s) != server Content-Encoding (%s)") % \ (self.url, gm[1], self.headers.get('Content-Encoding')) if gm[1] in _fix_content_types: self.headers['Content-Encoding'] = gm[1] # will content be rewritten? rewrite = None for ro in config['mime_content_rewriting']: if ro.match(self.headers.get('Content-Type', '')): rewrite = "True" break # add client accept-encoding value self.headers['Accept-Encoding'] = self.client.compress if self.headers.has_key('Content-Length'): self.bytes_remaining = int(self.headers['Content-Length']) #debug(HURT_ME_PLENTY, "%d bytes remaining"%self.bytes_remaining) if rewrite: remove_headers(self.headers, ['Content-Length']) else: self.bytes_remaining = None
15,591
def socket_send (sock, data): """ Send data to socket. """ sock.sendall(data) debug("Socket sent %r" % data)
def socket_send (sock, data): """ Send data to socket. """ sock.sendall(data) debug("Socket sent %d bytes: %r" % (len(data), data))
15,592
def socket_read (sock): """ Read data from socket until no more data is available. """ data = "" while wc.proxy.readable_socket(sock): s = sock.recv(8192) if not s: break data += s debug("Socket read %r" % data) return data
def socket_read (sock): """ Read data from socket until no more data is available. """ data = "" while wc.proxy.readable_socket(sock): s = sock.recv(8192) if not s: break data += s debug("Socket read %d bytes: %r" % (len(data), data)) return data
15,593
def socketfile_read (sock): """ Read data from socket until no more data is available. """ data = "" while wc.proxy.readable_socket(sock): s = sock.read(1) if not s: break data += s debug("Socket file read %r" % data) return data + sock._rbuf
def socketfile_read (sock): """ Read data from socket until no more data is available. """ data = "" while wc.proxy.readable_socket(sock): s = sock.read(1) if not s: break data += s debug("Socket file read %d bytes: %r" % (len(data), data)) return data + sock._rbuf
15,594
def create_conf_file(self, directory, data=[]): data.insert(0, "# this file is automatically created by setup.py") filename = os.path.join(directory, self.config_file) # add metadata metanames = dir(self.metadata) + \ ['fullname', 'contact', 'contact_email'] for name in metanames: method = "get_" + name cmd = "%s = %s" % (name, `getattr(self.metadata, method)()`) data.append(cmd) util.execute(write_file, (filename, data), "creating %s" % filename, self.verbose>=1, self.dry_run)
def create_conf_file(self, directory, data=[]): data.insert(0, "# this file is automatically created by setup.py") filename = os.path.join(directory, self.config_file) # add metadata metanames = dir(self.metadata) + \ ['fullname', 'contact', 'contact_email'] for name in metanames: method = "get_" + name cmd = "%s = %s" % (name, `getattr(self.metadata, method)()`) data.append(cmd) util.execute(write_file, (filename, data), "creating %s" % filename, self.verbose>=1, self.dry_run)
15,595
def write (self): """ Write pickled cache to disk. """ fp = file(self.filename, 'wb') pickle.dump(self.cache, fp, 1) fp.close()
def write (self): """ Write pickled cache to disk. """ fp = file(self.filename, 'wb') pickle.dump(self.cache, fp, 1) fp.close()
15,596
def check_headers (self): """add missing content-type and/or encoding headers if needed""" # 304 Not Modified does not send any type or encoding info, # because this info was cached if self.statuscode == '304': return # check content-type against our own guess i = self.document.find('?') if i>0: document = self.document[:i] else: document = self.document gm = mimetypes.guess_type(document, None) if gm[0]: # guessed an own content type if self.headers.get('Content-Type') is None: print >>sys.stderr, "Warning: add Content-Type %s to %s" % \ (`gm[0]`, `self.url`) self.headers['Content-Type'] = gm[0] # fix some content types elif not self.headers['Content-Type'].startswith(gm[0]) and \ gm[0] in _fix_content_types: print >>sys.stderr, "Warning: change Content-Type from %s to %s in %s" % \ (`self.headers['Content-Type']`, `gm[0]`, `self.url`) self.headers['Content-Type'] = gm[0] if gm[1] and gm[1] in _fix_content_encodings: # guessed an own encoding type if self.headers.get('Content-Encoding') is None: self.headers['Content-Encoding'] = gm[1] print >>sys.stderr, "Warning: add Content-Encoding %s to %s" % \ (`gm[1]`, `self.url`) elif self.headers.get('Content-Encoding') != gm[1]: print >>sys.stderr, "Warning: change Content-Encoding from %s to %s in %s" % \ (`self.headers['Content-Encoding']`, `gm[1]`, `self.url`) self.headers['Content-Encoding'] = gm[1]
def if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' check_headers if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' (self): if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' """add if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' missing if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' content-type if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' and/or if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' encoding if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' headers if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' if if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' needed""" if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' # if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' 304 if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' Not if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' Modified if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' does if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' not if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' send if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' any if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' type if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' or if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' encoding if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' info, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' # if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' because if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' this if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' info if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' was if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' cached if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' if if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.statuscode if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' == if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' '304': if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' return if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' # if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' check if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' content-type if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' against if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' our if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' own if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' guess if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' i if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' = if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.document.find('?') if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' if if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' i>0: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' document if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' = if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.document[:i] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' else: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' document if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' = if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.document if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' = if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' mimetypes.guess_type(document, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' None) if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' if if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[0]: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' # if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' guessed if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' an if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' own if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' content if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' type if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' if if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.headers.get('Content-Type') if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' is if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' None: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' print if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' >>sys.stderr, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' "Warning: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' add if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' Content-Type if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' to if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s" if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' % if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' \ if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' (`gm[0]`, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' `self.url`) if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.headers['Content-Type'] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' = if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[0] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' # if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' fix if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' some if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' content if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' types if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' elif if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' not if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.headers['Content-Type'].startswith(gm[0]) if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' and if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' \ if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[0] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' in if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' _fix_content_types: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' print if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' >>sys.stderr, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' "Warning: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' change if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' Content-Type if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' from if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' to if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' in if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s" if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' % if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' \ if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' (`self.headers['Content-Type']`, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' `gm[0]`, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' `self.url`) if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.headers['Content-Type'] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' = if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[0] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' if if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[1] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' and if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[1] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' in if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' _fix_content_encodings: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' # if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' guessed if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' an if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' own if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' encoding if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' type if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' if if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.headers.get('Content-Encoding') if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' is if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' None: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.headers['Content-Encoding'] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' = if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[1] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' print if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' >>sys.stderr, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' "Warning: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' add if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' Content-Encoding if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' to if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s" if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' % if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' \ if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' (`gm[1]`, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' `self.url`) if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' elif if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.headers.get('Content-Encoding') if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' != if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[1]: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' print if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' >>sys.stderr, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' "Warning: if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' change if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' Content-Encoding if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' from if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' to if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' in if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' %s" if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' % if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' \ if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' (`self.headers['Content-Encoding']`, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' `gm[1]`, if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' `self.url`) if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' self.headers['Content-Encoding'] if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' = if self.headers.get('Content-Type', '').lower().startswith('application/x-httpd-php'): self.headers['Content-Type'] = 'text/html' gm[1]
15,597
def create_socket (family, socktype, proto=0): """ Create a socket with given family and type. If SSL context is given an SSL socket is created. """ sock = socket.socket(family, socktype, proto=proto) # store family, type and proto in the object sock.family = family sock.socktype = socktype sock.proto = proto # XXX disable custom timeouts for now #sock.settimeout(wc.configuration.config['timeout']) socktypes_inet = [socket.AF_INET] if has_ipv6: socktypes_inet.append(socket.AF_INET6) if family in socktypes_inet and socktype == socket.SOCK_STREAM: # disable NAGLE algorithm, which means sending pending data # immediately, possibly wasting bandwidth but improving # responsiveness for fast networks sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) return sock
def sock = wc.objproxy.Proxy(sock) create_socket sock = wc.objproxy.Proxy(sock) (family, sock = wc.objproxy.Proxy(sock) socktype, sock = wc.objproxy.Proxy(sock) proto=0): sock = wc.objproxy.Proxy(sock) """ sock = wc.objproxy.Proxy(sock) Create sock = wc.objproxy.Proxy(sock) a sock = wc.objproxy.Proxy(sock) socket sock = wc.objproxy.Proxy(sock) with sock = wc.objproxy.Proxy(sock) given sock = wc.objproxy.Proxy(sock) family sock = wc.objproxy.Proxy(sock) and sock = wc.objproxy.Proxy(sock) type. sock = wc.objproxy.Proxy(sock) If sock = wc.objproxy.Proxy(sock) SSL sock = wc.objproxy.Proxy(sock) context sock = wc.objproxy.Proxy(sock) is sock = wc.objproxy.Proxy(sock) given sock = wc.objproxy.Proxy(sock) an sock = wc.objproxy.Proxy(sock) SSL sock = wc.objproxy.Proxy(sock) socket sock = wc.objproxy.Proxy(sock) is sock = wc.objproxy.Proxy(sock) created. sock = wc.objproxy.Proxy(sock) """ sock = wc.objproxy.Proxy(sock) sock sock = wc.objproxy.Proxy(sock) = sock = wc.objproxy.Proxy(sock) socket.socket(family, sock = wc.objproxy.Proxy(sock) socktype, sock = wc.objproxy.Proxy(sock) proto=proto) sock = wc.objproxy.Proxy(sock) # sock = wc.objproxy.Proxy(sock) store sock = wc.objproxy.Proxy(sock) family, sock = wc.objproxy.Proxy(sock) type sock = wc.objproxy.Proxy(sock) and sock = wc.objproxy.Proxy(sock) proto sock = wc.objproxy.Proxy(sock) in sock = wc.objproxy.Proxy(sock) the sock = wc.objproxy.Proxy(sock) object sock = wc.objproxy.Proxy(sock) sock.family sock = wc.objproxy.Proxy(sock) = sock = wc.objproxy.Proxy(sock) family sock = wc.objproxy.Proxy(sock) sock.socktype sock = wc.objproxy.Proxy(sock) = sock = wc.objproxy.Proxy(sock) socktype sock = wc.objproxy.Proxy(sock) sock.proto sock = wc.objproxy.Proxy(sock) = sock = wc.objproxy.Proxy(sock) proto sock = wc.objproxy.Proxy(sock) # sock = wc.objproxy.Proxy(sock) XXX sock = wc.objproxy.Proxy(sock) disable sock = wc.objproxy.Proxy(sock) custom sock = wc.objproxy.Proxy(sock) timeouts sock = wc.objproxy.Proxy(sock) for sock = wc.objproxy.Proxy(sock) now sock = wc.objproxy.Proxy(sock) #sock.settimeout(wc.configuration.config['timeout']) sock = wc.objproxy.Proxy(sock) socktypes_inet sock = wc.objproxy.Proxy(sock) = sock = wc.objproxy.Proxy(sock) [socket.AF_INET] sock = wc.objproxy.Proxy(sock) if sock = wc.objproxy.Proxy(sock) has_ipv6: sock = wc.objproxy.Proxy(sock) socktypes_inet.append(socket.AF_INET6) sock = wc.objproxy.Proxy(sock) if sock = wc.objproxy.Proxy(sock) family sock = wc.objproxy.Proxy(sock) in sock = wc.objproxy.Proxy(sock) socktypes_inet sock = wc.objproxy.Proxy(sock) and sock = wc.objproxy.Proxy(sock) socktype sock = wc.objproxy.Proxy(sock) == sock = wc.objproxy.Proxy(sock) socket.SOCK_STREAM: sock = wc.objproxy.Proxy(sock) # sock = wc.objproxy.Proxy(sock) disable sock = wc.objproxy.Proxy(sock) NAGLE sock = wc.objproxy.Proxy(sock) algorithm, sock = wc.objproxy.Proxy(sock) which sock = wc.objproxy.Proxy(sock) means sock = wc.objproxy.Proxy(sock) sending sock = wc.objproxy.Proxy(sock) pending sock = wc.objproxy.Proxy(sock) data sock = wc.objproxy.Proxy(sock) # sock = wc.objproxy.Proxy(sock) immediately, sock = wc.objproxy.Proxy(sock) possibly sock = wc.objproxy.Proxy(sock) wasting sock = wc.objproxy.Proxy(sock) bandwidth sock = wc.objproxy.Proxy(sock) but sock = wc.objproxy.Proxy(sock) improving sock = wc.objproxy.Proxy(sock) # sock = wc.objproxy.Proxy(sock) responsiveness sock = wc.objproxy.Proxy(sock) for sock = wc.objproxy.Proxy(sock) fast sock = wc.objproxy.Proxy(sock) networks sock = wc.objproxy.Proxy(sock) sock.setsockopt(socket.IPPROTO_TCP, sock = wc.objproxy.Proxy(sock) socket.TCP_NODELAY, sock = wc.objproxy.Proxy(sock) 1) sock = wc.objproxy.Proxy(sock) return sock = wc.objproxy.Proxy(sock) sock sock = wc.objproxy.Proxy(sock) sock = wc.objproxy.Proxy(sock)
15,598
def accept (self): """ Accept a new connection on the socket.
def accept (self): """ Accept a new connection on the socket.
15,599