def _handle_get_local(handler, path_match, data): """Return a static file from the hass.config.path/www for the frontend.""" req_file = util.sanitize_path(path_match.group('file')) path = handler.server.hass.config.path('www', req_file) handler.write_file(path)
def _handle_get_static(self, path_match, data): """ Returns a static file. """ req_file = util.sanitize_path(path_match.group('file')) # Strip md5 hash out of frontend filename if re.match(r'^frontend-[A-Za-z0-9]{32}\.html$', req_file): req_file = "frontend.html" path = os.path.join(os.path.dirname(__file__), 'www_static', req_file) inp = None try: inp = open(path, 'rb') do_gzip = 'gzip' in self.headers.get('accept-encoding', '') self.send_response(HTTP_OK) ctype = self.guess_type(path) self.send_header("Content-Type", ctype) # Add cache if not development if not self.server.development: # 1 year in seconds cache_time = 365 * 86400 self.send_header( "Cache-Control", "public, max-age={}".format(cache_time)) self.send_header( "Expires", self.date_time_string(time.time()+cache_time)) if do_gzip: gzip_data = gzip.compress(inp.read()) self.send_header("Content-Encoding", "gzip") self.send_header("Vary", "Accept-Encoding") self.send_header("Content-Length", str(len(gzip_data))) else: fs = os.fstat(inp.fileno()) self.send_header("Content-Length", str(fs[6])) self.end_headers() if do_gzip: self.wfile.write(gzip_data) else: self.copyfile(inp, self.wfile) except IOError: self.send_response(HTTP_NOT_FOUND) self.end_headers() finally: if inp: inp.close()
def path(value: Any) -> str: """Validate it's a safe path.""" if not isinstance(value, str): raise vol.Invalid("Expected a string") if sanitize_path(value) != value: raise vol.Invalid("Invalid path") return value
def _handle_get_static(handler, path_match, data): """ Returns a static file for the frontend. """ req_file = util.sanitize_path(path_match.group('file')) # Strip md5 hash out of frontend filename if re.match(r'^frontend-[A-Za-z0-9]{32}\.html$', req_file): req_file = "frontend.html" path = os.path.join(os.path.dirname(__file__), 'www_static', req_file) handler.write_file(path)
def _handle_get_local(handler, path_match, data): """ Returns a static file from the hass.config.path/www for the frontend. """ req_file = util.sanitize_path(path_match.group('file')) path = os.path.join(get_default_config_dir(), 'www', req_file) if not os.path.isfile(path): return False handler.write_file(path)
def _handle_get_static(handler, path_match, data): """ Returns a static file for the frontend. """ req_file = util.sanitize_path(path_match.group('file')) # Strip md5 hash out fingerprinted = _FINGERPRINT.match(req_file) if fingerprinted: req_file = "{}.{}".format(*fingerprinted.groups()) path = os.path.join(os.path.dirname(__file__), 'www_static', req_file) handler.write_file(path)
async def get(self, request, filename): filename = sanitize_path(filename) path = os.path.join(self.config_dir, 'custom_components', self.domain, filename) filecontent = "" try: with open(path, mode="r", encoding="utf-8", errors="ignore") as localfile: filecontent = localfile.read() localfile.close() except Exception: return web.Response(status=404) return web.Response(body=filecontent, content_type="text/javascript", charset="utf-8")
def async_parse_identifier(self, item: MediaSourceItem) -> Tuple[str, str]: """Parse identifier.""" if not item.identifier: # Empty source_dir_id and location return "", "" source_dir_id, location = item.identifier.split("/", 1) if source_dir_id not in self.hass.config.media_dirs: raise Unresolvable("Unknown source directory.") if location != sanitize_path(location): raise Unresolvable("Invalid path.") return source_dir_id, location
def async_parse_identifier(item: MediaSourceItem) -> Tuple[str, str]: """Parse identifier.""" if not item.identifier: source_dir_id = "media" location = "" else: source_dir_id, location = item.identifier.lstrip("/").split("/", 1) if source_dir_id != "media": raise Unresolvable("Unknown source directory.") if location != sanitize_path(location): raise Unresolvable("Invalid path.") return source_dir_id, location
async def get(self, request: web.Request, location: str) -> web.FileResponse: """Start a GET request.""" if location != sanitize_path(location): return web.HTTPNotFound() media_path = Path(self.hass.config.path("media", location)) # Check that the file exists if not media_path.is_file(): raise web.HTTPNotFound() # Check that it's a media file mime_type, _ = mimetypes.guess_type(str(media_path)) if not mime_type or mime_type.split("/")[0] not in MEDIA_MIME_TYPES: raise web.HTTPNotFound() return web.FileResponse(media_path)
async def get(self, request, path): """Retrieve custom_card.""" _LOGGER.error("This integration is deprecated, and is no longer maintained." "As an alternative have a look at HACS https://hacs.xyz") if path != sanitize_path(path): raise web.HTTPBadRequest if '?' in path: path = path.split('?')[0] file = "{}/www/{}".format(self.hadir, path) if os.path.exists(file): msg = "Serving /customcards/{path} from /www/{path}".format( path=path) _LOGGER.debug(msg) resp = web.FileResponse(file) resp.headers["Cache-Control"] = "max-age=0, must-revalidate" return resp else: _LOGGER.error("Tried to serve up '%s' but it does not exist", file) return None
def test_sanitize_path(self): """Test sanitize_path.""" assert "test/path" == util.sanitize_path("test/path") assert "test/path" == util.sanitize_path("~test/path") assert "//test/path" == util.sanitize_path("~/../test/path")
def test_sanitize_path(): """Test sanitize_path.""" assert util.sanitize_path("test/path") == "test/path" assert util.sanitize_path("~test/path") == "" assert util.sanitize_path("~/../test/path") == ""
def test_sanitize_path(self): """Test sanitize_path.""" self.assertEqual("test/path", util.sanitize_path("test/path")) self.assertEqual("test/path", util.sanitize_path("~test/path")) self.assertEqual("//test/path", util.sanitize_path("~/../test/path"))
async def get(self, request, requested_file): # pylint: disable=unused-argument """Handle HACS Web requests.""" return await get_file_response(request, sanitize_path(requested_file))