Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
28
33
content
stringlengths
14
265k
max_stars_repo_path
stringlengths
49
55
crossvul-python_data_bad_3565_0
import json import webob from xml.dom import minidom from xml.parsers import expat import faults from nova import exception from nova import log as logging from nova import utils from nova import wsgi XMLNS_V10 = 'http://docs.rackspacecloud.com/servers/api/v1.0' XMLNS_V11 = 'http://docs.openstack.org/compute/api/v1.1' XMLNS_ATOM = 'http://www.w3.org/2005/Atom' LOG = logging.getLogger('nova.api.openstack.wsgi') class Request(webob.Request): """Add some Openstack API-specific logic to the base webob.Request.""" def best_match_content_type(self, supported_content_types=None): """Determine the requested response content-type. Based on the query extension then the Accept header. """ supported_content_types = supported_content_types or \ ('application/json', 'application/xml') parts = self.path.rsplit('.', 1) if len(parts) > 1: ctype = 'application/{0}'.format(parts[1]) if ctype in supported_content_types: return ctype bm = self.accept.best_match(supported_content_types) # default to application/json if we don't find a preference return bm or 'application/json' def get_content_type(self): """Determine content type of the request body. Does not do any body introspection, only checks header """ if not "Content-Type" in self.headers: return None allowed_types = ("application/xml", "application/json") content_type = self.content_type if content_type not in allowed_types: raise exception.InvalidContentType(content_type=content_type) return content_type class ActionDispatcher(object): """Maps method name to local methods through action name.""" def dispatch(self, *args, **kwargs): """Find and call local method.""" action = kwargs.pop('action', 'default') action_method = getattr(self, str(action), self.default) return action_method(*args, **kwargs) def default(self, data): raise NotImplementedError() class TextDeserializer(ActionDispatcher): """Default request body deserialization""" def deserialize(self, datastring, action='default'): return self.dispatch(datastring, action=action) def default(self, datastring): return {} class JSONDeserializer(TextDeserializer): def _from_json(self, datastring): try: return utils.loads(datastring) except ValueError: msg = _("cannot understand JSON") raise exception.MalformedRequestBody(reason=msg) def default(self, datastring): return {'body': self._from_json(datastring)} class XMLDeserializer(TextDeserializer): def __init__(self, metadata=None): """ :param metadata: information needed to deserialize xml into a dictionary. """ super(XMLDeserializer, self).__init__() self.metadata = metadata or {} def _from_xml(self, datastring): plurals = set(self.metadata.get('plurals', {})) try: node = minidom.parseString(datastring).childNodes[0] return {node.nodeName: self._from_xml_node(node, plurals)} except expat.ExpatError: msg = _("cannot understand XML") raise exception.MalformedRequestBody(reason=msg) def _from_xml_node(self, node, listnames): """Convert a minidom node to a simple Python type. :param listnames: list of XML node names whose subnodes should be considered list items. """ if len(node.childNodes) == 1 and node.childNodes[0].nodeType == 3: return node.childNodes[0].nodeValue elif node.nodeName in listnames: return [self._from_xml_node(n, listnames) for n in node.childNodes] else: result = dict() for attr in node.attributes.keys(): result[attr] = node.attributes[attr].nodeValue for child in node.childNodes: if child.nodeType != node.TEXT_NODE: result[child.nodeName] = self._from_xml_node(child, listnames) return result def find_first_child_named(self, parent, name): """Search a nodes children for the first child with a given name""" for node in parent.childNodes: if node.nodeName == name: return node return None def find_children_named(self, parent, name): """Return all of a nodes children who have the given name""" for node in parent.childNodes: if node.nodeName == name: yield node def extract_text(self, node): """Get the text field contained by the given node""" if len(node.childNodes) == 1: child = node.childNodes[0] if child.nodeType == child.TEXT_NODE: return child.nodeValue return "" def default(self, datastring): return {'body': self._from_xml(datastring)} class MetadataXMLDeserializer(XMLDeserializer): def extract_metadata(self, metadata_node): """Marshal the metadata attribute of a parsed request""" metadata = {} if metadata_node is not None: for meta_node in self.find_children_named(metadata_node, "meta"): key = meta_node.getAttribute("key") metadata[key] = self.extract_text(meta_node) return metadata class RequestHeadersDeserializer(ActionDispatcher): """Default request headers deserializer""" def deserialize(self, request, action): return self.dispatch(request, action=action) def default(self, request): return {} class RequestDeserializer(object): """Break up a Request object into more useful pieces.""" def __init__(self, body_deserializers=None, headers_deserializer=None, supported_content_types=None): self.supported_content_types = supported_content_types or \ ('application/json', 'application/xml') self.body_deserializers = { 'application/xml': XMLDeserializer(), 'application/json': JSONDeserializer(), } self.body_deserializers.update(body_deserializers or {}) self.headers_deserializer = headers_deserializer or \ RequestHeadersDeserializer() def deserialize(self, request): """Extract necessary pieces of the request. :param request: Request object :returns tuple of expected controller action name, dictionary of keyword arguments to pass to the controller, the expected content type of the response """ action_args = self.get_action_args(request.environ) action = action_args.pop('action', None) action_args.update(self.deserialize_headers(request, action)) action_args.update(self.deserialize_body(request, action)) accept = self.get_expected_content_type(request) return (action, action_args, accept) def deserialize_headers(self, request, action): return self.headers_deserializer.deserialize(request, action) def deserialize_body(self, request, action): try: content_type = request.get_content_type() except exception.InvalidContentType: LOG.debug(_("Unrecognized Content-Type provided in request")) return {} if content_type is None: LOG.debug(_("No Content-Type provided in request")) return {} if not len(request.body) > 0: LOG.debug(_("Empty body provided in request")) return {} try: deserializer = self.get_body_deserializer(content_type) except exception.InvalidContentType: LOG.debug(_("Unable to deserialize body as provided Content-Type")) raise return deserializer.deserialize(request.body, action) def get_body_deserializer(self, content_type): try: return self.body_deserializers[content_type] except (KeyError, TypeError): raise exception.InvalidContentType(content_type=content_type) def get_expected_content_type(self, request): return request.best_match_content_type(self.supported_content_types) def get_action_args(self, request_environment): """Parse dictionary created by routes library.""" try: args = request_environment['wsgiorg.routing_args'][1].copy() except Exception: return {} try: del args['controller'] except KeyError: pass try: del args['format'] except KeyError: pass return args class DictSerializer(ActionDispatcher): """Default request body serialization""" def serialize(self, data, action='default'): return self.dispatch(data, action=action) def default(self, data): return "" class JSONDictSerializer(DictSerializer): """Default JSON request body serialization""" def default(self, data): return utils.dumps(data) class XMLDictSerializer(DictSerializer): def __init__(self, metadata=None, xmlns=None): """ :param metadata: information needed to deserialize xml into a dictionary. :param xmlns: XML namespace to include with serialized xml """ super(XMLDictSerializer, self).__init__() self.metadata = metadata or {} self.xmlns = xmlns def default(self, data): # We expect data to contain a single key which is the XML root. root_key = data.keys()[0] doc = minidom.Document() node = self._to_xml_node(doc, self.metadata, root_key, data[root_key]) return self.to_xml_string(node) def to_xml_string(self, node, has_atom=False): self._add_xmlns(node, has_atom) return node.toprettyxml(indent=' ', encoding='UTF-8') #NOTE (ameade): the has_atom should be removed after all of the # xml serializers and view builders have been updated to the current # spec that required all responses include the xmlns:atom, the has_atom # flag is to prevent current tests from breaking def _add_xmlns(self, node, has_atom=False): if self.xmlns is not None: node.setAttribute('xmlns', self.xmlns) if has_atom: node.setAttribute('xmlns:atom', "http://www.w3.org/2005/Atom") def _to_xml_node(self, doc, metadata, nodename, data): """Recursive method to convert data members to XML nodes.""" result = doc.createElement(nodename) # Set the xml namespace if one is specified # TODO(justinsb): We could also use prefixes on the keys xmlns = metadata.get('xmlns', None) if xmlns: result.setAttribute('xmlns', xmlns) #TODO(bcwaldon): accomplish this without a type-check if type(data) is list: collections = metadata.get('list_collections', {}) if nodename in collections: metadata = collections[nodename] for item in data: node = doc.createElement(metadata['item_name']) node.setAttribute(metadata['item_key'], str(item)) result.appendChild(node) return result singular = metadata.get('plurals', {}).get(nodename, None) if singular is None: if nodename.endswith('s'): singular = nodename[:-1] else: singular = 'item' for item in data: node = self._to_xml_node(doc, metadata, singular, item) result.appendChild(node) #TODO(bcwaldon): accomplish this without a type-check elif type(data) is dict: collections = metadata.get('dict_collections', {}) if nodename in collections: metadata = collections[nodename] for k, v in data.items(): node = doc.createElement(metadata['item_name']) node.setAttribute(metadata['item_key'], str(k)) text = doc.createTextNode(str(v)) node.appendChild(text) result.appendChild(node) return result attrs = metadata.get('attributes', {}).get(nodename, {}) for k, v in data.items(): if k in attrs: result.setAttribute(k, str(v)) else: node = self._to_xml_node(doc, metadata, k, v) result.appendChild(node) else: # Type is atom node = doc.createTextNode(str(data)) result.appendChild(node) return result def _create_link_nodes(self, xml_doc, links): link_nodes = [] for link in links: link_node = xml_doc.createElement('atom:link') link_node.setAttribute('rel', link['rel']) link_node.setAttribute('href', link['href']) if 'type' in link: link_node.setAttribute('type', link['type']) link_nodes.append(link_node) return link_nodes class ResponseHeadersSerializer(ActionDispatcher): """Default response headers serialization""" def serialize(self, response, data, action): self.dispatch(response, data, action=action) def default(self, response, data): response.status_int = 200 class ResponseSerializer(object): """Encode the necessary pieces into a response object""" def __init__(self, body_serializers=None, headers_serializer=None): self.body_serializers = { 'application/xml': XMLDictSerializer(), 'application/json': JSONDictSerializer(), } self.body_serializers.update(body_serializers or {}) self.headers_serializer = headers_serializer or \ ResponseHeadersSerializer() def serialize(self, response_data, content_type, action='default'): """Serialize a dict into a string and wrap in a wsgi.Request object. :param response_data: dict produced by the Controller :param content_type: expected mimetype of serialized response body """ response = webob.Response() self.serialize_headers(response, response_data, action) self.serialize_body(response, response_data, content_type, action) return response def serialize_headers(self, response, data, action): self.headers_serializer.serialize(response, data, action) def serialize_body(self, response, data, content_type, action): response.headers['Content-Type'] = content_type if data is not None: serializer = self.get_body_serializer(content_type) response.body = serializer.serialize(data, action) def get_body_serializer(self, content_type): try: return self.body_serializers[content_type] except (KeyError, TypeError): raise exception.InvalidContentType(content_type=content_type) class Resource(wsgi.Application): """WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Request. If the operation is a PUT or POST, the controller method must also accept a 'body' argument (the deserialized request body). They may raise a webob.exc exception or return a dict, which will be serialized by requested content type. """ def __init__(self, controller, deserializer=None, serializer=None): """ :param controller: object that implement methods created by routes lib :param deserializer: object that can serialize the output of a controller into a webob response :param serializer: object that can deserialize a webob request into necessary pieces """ self.controller = controller self.deserializer = deserializer or RequestDeserializer() self.serializer = serializer or ResponseSerializer() @webob.dec.wsgify(RequestClass=Request) def __call__(self, request): """WSGI method that controls (de)serialization and method dispatch.""" LOG.info("%(method)s %(url)s" % {"method": request.method, "url": request.url}) try: action, args, accept = self.deserializer.deserialize(request) except exception.InvalidContentType: msg = _("Unsupported Content-Type") return faults.Fault(webob.exc.HTTPBadRequest(explanation=msg)) except exception.MalformedRequestBody: msg = _("Malformed request body") return faults.Fault(webob.exc.HTTPBadRequest(explanation=msg)) project_id = args.pop("project_id", None) if 'nova.context' in request.environ and project_id: request.environ['nova.context'].project_id = project_id try: action_result = self.dispatch(request, action, args) except faults.Fault as ex: LOG.info(_("Fault thrown: %s"), unicode(ex)) action_result = ex except webob.exc.HTTPException as ex: LOG.info(_("HTTP exception thrown: %s"), unicode(ex)) action_result = faults.Fault(ex) if type(action_result) is dict or action_result is None: response = self.serializer.serialize(action_result, accept, action=action) else: response = action_result try: msg_dict = dict(url=request.url, status=response.status_int) msg = _("%(url)s returned with HTTP %(status)d") % msg_dict except AttributeError, e: msg_dict = dict(url=request.url, e=e) msg = _("%(url)s returned a fault: %(e)s" % msg_dict) LOG.info(msg) return response def dispatch(self, request, action, action_args): """Find action-spefic method on controller and call it.""" controller_method = getattr(self.controller, action) try: return controller_method(req=request, **action_args) except TypeError as exc: LOG.exception(exc) return faults.Fault(webob.exc.HTTPBadRequest())
./CrossVul/dataset_final_sorted/CWE-264/py/bad_3565_0
crossvul-python_data_good_4833_0
#!/usr/bin/env python2 # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import time, textwrap, json from bisect import bisect_right from base64 import b64encode from future_builtins import map from threading import Thread from Queue import Queue, Empty from functools import partial from urlparse import urlparse from PyQt5.Qt import ( QWidget, QVBoxLayout, QApplication, QSize, QNetworkAccessManager, QMenu, QIcon, QNetworkReply, QTimer, QNetworkRequest, QUrl, Qt, QNetworkDiskCache, QToolBar, pyqtSlot, pyqtSignal) from PyQt5.QtWebKitWidgets import QWebView, QWebInspector, QWebPage from calibre import prints from calibre.constants import iswindows from calibre.ebooks.oeb.polish.parsing import parse from calibre.ebooks.oeb.base import serialize, OEB_DOCS from calibre.ptempfile import PersistentTemporaryDirectory from calibre.gui2 import error_dialog, open_url, NO_URL_FORMATTING from calibre.gui2.tweak_book import current_container, editors, tprefs, actions, TOP from calibre.gui2.viewer.documentview import apply_settings from calibre.gui2.viewer.config import config from calibre.gui2.widgets2 import HistoryLineEdit2 from calibre.utils.ipc.simple_worker import offload_worker shutdown = object() def get_data(name): 'Get the data for name. Returns a unicode string if name is a text document/stylesheet' if name in editors: return editors[name].get_raw_data() return current_container().raw_data(name) # Parsing of html to add linenumbers {{{ def parse_html(raw): root = parse(raw, decoder=lambda x:x.decode('utf-8'), line_numbers=True, linenumber_attribute='data-lnum') return serialize(root, 'text/html').encode('utf-8') class ParseItem(object): __slots__ = ('name', 'length', 'fingerprint', 'parsing_done', 'parsed_data') def __init__(self, name): self.name = name self.length, self.fingerprint = 0, None self.parsed_data = None self.parsing_done = False def __repr__(self): return 'ParsedItem(name=%r, length=%r, fingerprint=%r, parsing_done=%r, parsed_data_is_None=%r)' % ( self.name, self.length, self.fingerprint, self.parsing_done, self.parsed_data is None) class ParseWorker(Thread): daemon = True SLEEP_TIME = 1 def __init__(self): Thread.__init__(self) self.requests = Queue() self.request_count = 0 self.parse_items = {} self.launch_error = None def run(self): mod, func = 'calibre.gui2.tweak_book.preview', 'parse_html' try: # Connect to the worker and send a dummy job to initialize it self.worker = offload_worker(priority='low') self.worker(mod, func, '<p></p>') except: import traceback traceback.print_exc() self.launch_error = traceback.format_exc() return while True: time.sleep(self.SLEEP_TIME) x = self.requests.get() requests = [x] while True: try: requests.append(self.requests.get_nowait()) except Empty: break if shutdown in requests: self.worker.shutdown() break request = sorted(requests, reverse=True)[0] del requests pi, data = request[1:] try: res = self.worker(mod, func, data) except: import traceback traceback.print_exc() else: pi.parsing_done = True parsed_data = res['result'] if res['tb']: prints("Parser error:") prints(res['tb']) else: pi.parsed_data = parsed_data def add_request(self, name): data = get_data(name) ldata, hdata = len(data), hash(data) pi = self.parse_items.get(name, None) if pi is None: self.parse_items[name] = pi = ParseItem(name) else: if pi.parsing_done and pi.length == ldata and pi.fingerprint == hdata: return pi.parsed_data = None pi.parsing_done = False pi.length, pi.fingerprint = ldata, hdata self.requests.put((self.request_count, pi, data)) self.request_count += 1 def shutdown(self): self.requests.put(shutdown) def get_data(self, name): return getattr(self.parse_items.get(name, None), 'parsed_data', None) def clear(self): self.parse_items.clear() def is_alive(self): return Thread.is_alive(self) or (hasattr(self, 'worker') and self.worker.is_alive()) parse_worker = ParseWorker() # }}} # Override network access to load data "live" from the editors {{{ class NetworkReply(QNetworkReply): def __init__(self, parent, request, mime_type, name): QNetworkReply.__init__(self, parent) self.setOpenMode(QNetworkReply.ReadOnly | QNetworkReply.Unbuffered) self.setRequest(request) self.setUrl(request.url()) self._aborted = False if mime_type in OEB_DOCS: self.resource_name = name QTimer.singleShot(0, self.check_for_parse) else: data = get_data(name) if isinstance(data, type('')): data = data.encode('utf-8') mime_type += '; charset=utf-8' self.__data = data self.setHeader(QNetworkRequest.ContentTypeHeader, mime_type) self.setHeader(QNetworkRequest.ContentLengthHeader, len(self.__data)) QTimer.singleShot(0, self.finalize_reply) def check_for_parse(self): if self._aborted: return data = parse_worker.get_data(self.resource_name) if data is None: return QTimer.singleShot(10, self.check_for_parse) self.__data = data self.setHeader(QNetworkRequest.ContentTypeHeader, 'application/xhtml+xml; charset=utf-8') self.setHeader(QNetworkRequest.ContentLengthHeader, len(self.__data)) self.finalize_reply() def bytesAvailable(self): try: return len(self.__data) except AttributeError: return 0 def isSequential(self): return True def abort(self): self._aborted = True def readData(self, maxlen): ans, self.__data = self.__data[:maxlen], self.__data[maxlen:] return ans read = readData def finalize_reply(self): if self._aborted: return self.setFinished(True) self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200) self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok") self.metaDataChanged.emit() self.downloadProgress.emit(len(self.__data), len(self.__data)) self.readyRead.emit() self.finished.emit() class NetworkAccessManager(QNetworkAccessManager): OPERATION_NAMES = {getattr(QNetworkAccessManager, '%sOperation'%x) : x.upper() for x in ('Head', 'Get', 'Put', 'Post', 'Delete', 'Custom') } def __init__(self, *args): QNetworkAccessManager.__init__(self, *args) self.current_root = None self.cache = QNetworkDiskCache(self) self.setCache(self.cache) self.cache.setCacheDirectory(PersistentTemporaryDirectory(prefix='disk_cache_')) self.cache.setMaximumCacheSize(0) def createRequest(self, operation, request, data): url = unicode(request.url().toString(NO_URL_FORMATTING)) if operation == self.GetOperation and url.startswith('file://'): path = url[7:] if iswindows and path.startswith('/'): path = path[1:] c = current_container() try: name = c.abspath_to_name(path, root=self.current_root) except ValueError: # Happens on windows with absolute paths on different drives name = None if c.has_name(name): try: return NetworkReply(self, request, c.mime_map.get(name, 'application/octet-stream'), name) except Exception: import traceback traceback.print_exc() return QNetworkAccessManager.createRequest(self, operation, request, data) # }}} def uniq(vals): ''' Remove all duplicates from vals, while preserving order. ''' vals = vals or () seen = set() seen_add = seen.add return tuple(x for x in vals if x not in seen and not seen_add(x)) def find_le(a, x): 'Find rightmost value in a less than or equal to x' try: return a[bisect_right(a, x)] except IndexError: return a[-1] class WebPage(QWebPage): sync_requested = pyqtSignal(object, object, object) split_requested = pyqtSignal(object, object) def __init__(self, parent): QWebPage.__init__(self, parent) settings = self.settings() apply_settings(settings, config().parse()) settings.setMaximumPagesInCache(0) settings.setAttribute(settings.JavaEnabled, False) settings.setAttribute(settings.PluginsEnabled, False) settings.setAttribute(settings.PrivateBrowsingEnabled, True) settings.setAttribute(settings.JavascriptCanOpenWindows, False) settings.setAttribute(settings.JavascriptCanAccessClipboard, False) settings.setAttribute(settings.LocalContentCanAccessFileUrls, False) # ensure javascript cannot read from local files settings.setAttribute(settings.LinksIncludedInFocusChain, False) settings.setAttribute(settings.DeveloperExtrasEnabled, True) settings.setDefaultTextEncoding('utf-8') data = 'data:text/css;charset=utf-8;base64,' css = '[data-in-split-mode="1"] [data-is-block="1"]:hover { cursor: pointer !important; border-top: solid 5px green !important }' data += b64encode(css.encode('utf-8')) settings.setUserStyleSheetUrl(QUrl(data)) self.setNetworkAccessManager(NetworkAccessManager(self)) self.setLinkDelegationPolicy(self.DelegateAllLinks) self.mainFrame().javaScriptWindowObjectCleared.connect(self.init_javascript) self.init_javascript() @dynamic_property def current_root(self): def fget(self): return self.networkAccessManager().current_root def fset(self, val): self.networkAccessManager().current_root = val return property(fget=fget, fset=fset) def javaScriptConsoleMessage(self, msg, lineno, source_id): prints('preview js:%s:%s:'%(unicode(source_id), lineno), unicode(msg)) def init_javascript(self): if not hasattr(self, 'js'): from calibre.utils.resources import compiled_coffeescript self.js = compiled_coffeescript('ebooks.oeb.display.utils', dynamic=False) self.js += P('csscolorparser.js', data=True, allow_user_override=False) self.js += compiled_coffeescript('ebooks.oeb.polish.preview', dynamic=False) self._line_numbers = None mf = self.mainFrame() mf.addToJavaScriptWindowObject("py_bridge", self) mf.evaluateJavaScript(self.js) @pyqtSlot(str, str, str) def request_sync(self, tag_name, href, sourceline_address): try: self.sync_requested.emit(unicode(tag_name), unicode(href), json.loads(unicode(sourceline_address))) except (TypeError, ValueError, OverflowError, AttributeError): pass def go_to_anchor(self, anchor, lnum): self.mainFrame().evaluateJavaScript('window.calibre_preview_integration.go_to_anchor(%s, %s)' % ( json.dumps(anchor), json.dumps(str(lnum)))) @pyqtSlot(str, str) def request_split(self, loc, totals): actions['split-in-preview'].setChecked(False) loc, totals = json.loads(unicode(loc)), json.loads(unicode(totals)) if not loc or not totals: return error_dialog(self.view(), _('Invalid location'), _('Cannot split on the body tag'), show=True) self.split_requested.emit(loc, totals) @property def line_numbers(self): if self._line_numbers is None: def atoi(x): try: ans = int(x) except (TypeError, ValueError): ans = None return ans val = self.mainFrame().evaluateJavaScript('window.calibre_preview_integration.line_numbers()') self._line_numbers = sorted(uniq(filter(lambda x:x is not None, map(atoi, val)))) return self._line_numbers def go_to_line(self, lnum): try: lnum = find_le(self.line_numbers, lnum) except IndexError: return self.mainFrame().evaluateJavaScript( 'window.calibre_preview_integration.go_to_line(%d)' % lnum) def go_to_sourceline_address(self, sourceline_address): lnum, tags = sourceline_address if lnum is None: return tags = [x.lower() for x in tags] self.mainFrame().evaluateJavaScript( 'window.calibre_preview_integration.go_to_sourceline_address(%d, %s)' % (lnum, json.dumps(tags))) def split_mode(self, enabled): self.mainFrame().evaluateJavaScript( 'window.calibre_preview_integration.split_mode(%s)' % ( 'true' if enabled else 'false')) class WebView(QWebView): def __init__(self, parent=None): QWebView.__init__(self, parent) self.inspector = QWebInspector(self) w = QApplication.instance().desktop().availableGeometry(self).width() self._size_hint = QSize(int(w/3), int(w/2)) self._page = WebPage(self) self.setPage(self._page) self.inspector.setPage(self._page) self.clear() self.setAcceptDrops(False) def sizeHint(self): return self._size_hint def refresh(self): self.pageAction(self.page().Reload).trigger() @dynamic_property def scroll_pos(self): def fget(self): mf = self.page().mainFrame() return (mf.scrollBarValue(Qt.Horizontal), mf.scrollBarValue(Qt.Vertical)) def fset(self, val): mf = self.page().mainFrame() mf.setScrollBarValue(Qt.Horizontal, val[0]) mf.setScrollBarValue(Qt.Vertical, val[1]) return property(fget=fget, fset=fset) def clear(self): self.setHtml(_( ''' <h3>Live preview</h3> <p>Here you will see a live preview of the HTML file you are currently editing. The preview will update automatically as you make changes. <p style="font-size:x-small; color: gray">Note that this is a quick preview only, it is not intended to simulate an actual ebook reader. Some aspects of your ebook will not work, such as page breaks and page margins. ''')) self.page().current_root = None def setUrl(self, qurl): self.page().current_root = current_container().root return QWebView.setUrl(self, qurl) def inspect(self): self.inspector.parent().show() self.inspector.parent().raise_() self.pageAction(self.page().InspectElement).trigger() def contextMenuEvent(self, ev): menu = QMenu(self) p = self.page() mf = p.mainFrame() r = mf.hitTestContent(ev.pos()) url = unicode(r.linkUrl().toString(NO_URL_FORMATTING)).strip() ca = self.pageAction(QWebPage.Copy) if ca.isEnabled(): menu.addAction(ca) menu.addAction(actions['reload-preview']) menu.addAction(QIcon(I('debug.png')), _('Inspect element'), self.inspect) if url.partition(':')[0].lower() in {'http', 'https'}: menu.addAction(_('Open link'), partial(open_url, r.linkUrl())) menu.exec_(ev.globalPos()) class Preview(QWidget): sync_requested = pyqtSignal(object, object) split_requested = pyqtSignal(object, object, object) split_start_requested = pyqtSignal() link_clicked = pyqtSignal(object, object) refresh_starting = pyqtSignal() refreshed = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout() self.setLayout(l) l.setContentsMargins(0, 0, 0, 0) self.view = WebView(self) self.view.page().sync_requested.connect(self.request_sync) self.view.page().split_requested.connect(self.request_split) self.view.page().loadFinished.connect(self.load_finished) self.inspector = self.view.inspector self.inspector.setPage(self.view.page()) l.addWidget(self.view) self.bar = QToolBar(self) l.addWidget(self.bar) ac = actions['auto-reload-preview'] ac.setCheckable(True) ac.setChecked(True) ac.toggled.connect(self.auto_reload_toggled) self.auto_reload_toggled(ac.isChecked()) self.bar.addAction(ac) ac = actions['sync-preview-to-editor'] ac.setCheckable(True) ac.setChecked(True) ac.toggled.connect(self.sync_toggled) self.sync_toggled(ac.isChecked()) self.bar.addAction(ac) self.bar.addSeparator() ac = actions['split-in-preview'] ac.setCheckable(True) ac.setChecked(False) ac.toggled.connect(self.split_toggled) self.split_toggled(ac.isChecked()) self.bar.addAction(ac) ac = actions['reload-preview'] ac.triggered.connect(self.refresh) self.bar.addAction(ac) actions['preview-dock'].toggled.connect(self.visibility_changed) self.current_name = None self.last_sync_request = None self.refresh_timer = QTimer(self) self.refresh_timer.timeout.connect(self.refresh) parse_worker.start() self.current_sync_request = None self.search = HistoryLineEdit2(self) self.search.initialize('tweak_book_preview_search') self.search.setPlaceholderText(_('Search in preview')) self.search.returnPressed.connect(partial(self.find, 'next')) self.bar.addSeparator() self.bar.addWidget(self.search) for d in ('next', 'prev'): ac = actions['find-%s-preview' % d] ac.triggered.connect(partial(self.find, d)) self.bar.addAction(ac) def find(self, direction): text = unicode(self.search.text()) self.view.findText(text, QWebPage.FindWrapsAroundDocument | ( QWebPage.FindBackward if direction == 'prev' else QWebPage.FindFlags(0))) def request_sync(self, tagname, href, lnum): if self.current_name: c = current_container() if tagname == 'a' and href: if href and href.startswith('#'): name = self.current_name else: name = c.href_to_name(href, self.current_name) if href else None if name == self.current_name: return self.view.page().go_to_anchor(urlparse(href).fragment, lnum) if name and c.exists(name) and c.mime_map[name] in OEB_DOCS: return self.link_clicked.emit(name, urlparse(href).fragment or TOP) self.sync_requested.emit(self.current_name, lnum) def request_split(self, loc, totals): if self.current_name: self.split_requested.emit(self.current_name, loc, totals) def sync_to_editor(self, name, sourceline_address): self.current_sync_request = (name, sourceline_address) QTimer.singleShot(100, self._sync_to_editor) def _sync_to_editor(self): if not actions['sync-preview-to-editor'].isChecked(): return try: if self.refresh_timer.isActive() or self.current_sync_request[0] != self.current_name: return QTimer.singleShot(100, self._sync_to_editor) except TypeError: return # Happens if current_sync_request is None sourceline_address = self.current_sync_request[1] self.current_sync_request = None self.view.page().go_to_sourceline_address(sourceline_address) def report_worker_launch_error(self): if parse_worker.launch_error is not None: tb, parse_worker.launch_error = parse_worker.launch_error, None error_dialog(self, _('Failed to launch worker'), _( 'Failed to launch the worker process used for rendering the preview'), det_msg=tb, show=True) def show(self, name): if name != self.current_name: self.refresh_timer.stop() self.current_name = name self.report_worker_launch_error() parse_worker.add_request(name) self.view.setUrl(QUrl.fromLocalFile(current_container().name_to_abspath(name))) return True def refresh(self): if self.current_name: self.refresh_timer.stop() # This will check if the current html has changed in its editor, # and re-parse it if so self.report_worker_launch_error() parse_worker.add_request(self.current_name) # Tell webkit to reload all html and associated resources current_url = QUrl.fromLocalFile(current_container().name_to_abspath(self.current_name)) self.refresh_starting.emit() if current_url != self.view.url(): # The container was changed self.view.setUrl(current_url) else: self.view.refresh() self.refreshed.emit() def clear(self): self.view.clear() self.current_name = None @property def current_root(self): return self.view.page().current_root @property def is_visible(self): return actions['preview-dock'].isChecked() @property def live_css_is_visible(self): try: return actions['live-css-dock'].isChecked() except KeyError: return False def start_refresh_timer(self): if self.live_css_is_visible or (self.is_visible and actions['auto-reload-preview'].isChecked()): self.refresh_timer.start(tprefs['preview_refresh_time'] * 1000) def stop_refresh_timer(self): self.refresh_timer.stop() def auto_reload_toggled(self, checked): if self.live_css_is_visible and not actions['auto-reload-preview'].isChecked(): actions['auto-reload-preview'].setChecked(True) error_dialog(self, _('Cannot disable'), _( 'Auto reloading of the preview panel cannot be disabled while the' ' Live CSS panel is open.'), show=True) actions['auto-reload-preview'].setToolTip(_( 'Auto reload preview when text changes in editor') if not checked else _( 'Disable auto reload of preview')) def sync_toggled(self, checked): actions['sync-preview-to-editor'].setToolTip(_( 'Disable syncing of preview position to editor position') if checked else _( 'Enable syncing of preview position to editor position')) def visibility_changed(self, is_visible): if is_visible: self.refresh() def split_toggled(self, checked): actions['split-in-preview'].setToolTip(textwrap.fill(_( 'Abort file split') if checked else _( 'Split this file at a specified location.\n\nAfter clicking this button, click' ' inside the preview panel above at the location you want the file to be split.'))) if checked: self.split_start_requested.emit() else: self.view.page().split_mode(False) def do_start_split(self): self.view.page().split_mode(True) def stop_split(self): actions['split-in-preview'].setChecked(False) def load_finished(self, ok): if actions['split-in-preview'].isChecked(): if ok: self.do_start_split() else: self.stop_split() def apply_settings(self): s = self.view.page().settings() s.setFontSize(s.DefaultFontSize, tprefs['preview_base_font_size']) s.setFontSize(s.DefaultFixedFontSize, tprefs['preview_mono_font_size']) s.setFontSize(s.MinimumLogicalFontSize, tprefs['preview_minimum_font_size']) s.setFontSize(s.MinimumFontSize, tprefs['preview_minimum_font_size']) sf, ssf, mf = tprefs['preview_serif_family'], tprefs['preview_sans_family'], tprefs['preview_mono_family'] s.setFontFamily(s.StandardFont, {'serif':sf, 'sans':ssf, 'mono':mf, None:sf}[tprefs['preview_standard_font_family']]) s.setFontFamily(s.SerifFont, sf) s.setFontFamily(s.SansSerifFont, ssf) s.setFontFamily(s.FixedFont, mf)
./CrossVul/dataset_final_sorted/CWE-264/py/good_4833_0
crossvul-python_data_bad_3784_0
# Copyright 2012 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import datetime import json import re import urllib import webob.exc from glance.api import policy import glance.api.v2 as v2 from glance.common import exception from glance.common import utils from glance.common import wsgi import glance.db import glance.notifier from glance.openstack.common import cfg import glance.openstack.common.log as logging from glance.openstack.common import timeutils import glance.schema import glance.store LOG = logging.getLogger(__name__) CONF = cfg.CONF class ImagesController(object): def __init__(self, db_api=None, policy_enforcer=None, notifier=None, store_api=None): self.db_api = db_api or glance.db.get_api() self.db_api.configure_db() self.policy = policy_enforcer or policy.Enforcer() self.notifier = notifier or glance.notifier.Notifier() self.store_api = store_api or glance.store self.store_api.create_stores() def _enforce(self, req, action): """Authorize an action against our policies""" try: self.policy.enforce(req.context, action, {}) except exception.Forbidden: raise webob.exc.HTTPForbidden() def _normalize_properties(self, image): """Convert the properties from the stored format to a dict The db api returns a list of dicts that look like {'name': <key>, 'value': <value>}, while it expects a format like {<key>: <value>} in image create and update calls. This function takes the extra step that the db api should be responsible for in the image get calls. The db api will also return deleted image properties that must be filtered out. """ properties = [(p['name'], p['value']) for p in image['properties'] if not p['deleted']] image['properties'] = dict(properties) return image def _extract_tags(self, image): try: #NOTE(bcwaldon): cast to set to make the list unique, then # cast back to list since that's a more sane response type return list(set(image.pop('tags'))) except KeyError: pass def _append_tags(self, context, image): image['tags'] = self.db_api.image_tag_get_all(context, image['id']) return image @utils.mutating def create(self, req, image): self._enforce(req, 'add_image') is_public = image.get('is_public') if is_public: self._enforce(req, 'publicize_image') image['owner'] = req.context.owner image['status'] = 'queued' tags = self._extract_tags(image) image = dict(self.db_api.image_create(req.context, image)) if tags is not None: self.db_api.image_tag_set_all(req.context, image['id'], tags) image['tags'] = tags else: image['tags'] = [] image = self._normalize_properties(dict(image)) self.notifier.info('image.update', image) return image def index(self, req, marker=None, limit=None, sort_key='created_at', sort_dir='desc', filters={}): self._enforce(req, 'get_images') filters['deleted'] = False result = {} if limit is None: limit = CONF.limit_param_default limit = min(CONF.api_limit_max, limit) try: images = self.db_api.image_get_all(req.context, filters=filters, marker=marker, limit=limit, sort_key=sort_key, sort_dir=sort_dir) if len(images) != 0 and len(images) == limit: result['next_marker'] = images[-1]['id'] except exception.InvalidFilterRangeValue as e: raise webob.exc.HTTPBadRequest(explanation=unicode(e)) except exception.InvalidSortKey as e: raise webob.exc.HTTPBadRequest(explanation=unicode(e)) except exception.NotFound as e: raise webob.exc.HTTPBadRequest(explanation=unicode(e)) images = [self._normalize_properties(dict(image)) for image in images] result['images'] = [self._append_tags(req.context, image) for image in images] return result def _get_image(self, context, image_id): try: image = self.db_api.image_get(context, image_id) if image['deleted']: raise exception.NotFound() except (exception.NotFound, exception.Forbidden): raise webob.exc.HTTPNotFound() else: return dict(image) def show(self, req, image_id): self._enforce(req, 'get_image') image = self._get_image(req.context, image_id) image = self._normalize_properties(image) return self._append_tags(req.context, image) @utils.mutating def update(self, req, image_id, changes): self._enforce(req, 'modify_image') context = req.context image = self._get_image(context, image_id) image = self._normalize_properties(image) updates = self._extract_updates(req, image, changes) tags = None if len(updates) > 0: tags = self._extract_tags(updates) purge_props = 'properties' in updates try: image = self.db_api.image_update(context, image_id, updates, purge_props) except (exception.NotFound, exception.Forbidden): raise webob.exc.HTTPNotFound() image = self._normalize_properties(dict(image)) if tags is not None: self.db_api.image_tag_set_all(req.context, image_id, tags) image['tags'] = tags else: self._append_tags(req.context, image) self.notifier.info('image.update', image) return image def _extract_updates(self, req, image, changes): """ Determine the updates to pass to the database api. Given the current image, convert a list of changes to be made into the corresponding update dictionary that should be passed to db_api.image_update. Changes have the following parts op - 'add' a new attribute, 'replace' an existing attribute, or 'remove' an existing attribute. path - A list of path parts for determining which attribute the the operation applies to. value - For 'add' and 'replace', the new value the attribute should assume. For the current use case, there are two types of valid paths. For base attributes (fields stored directly on the Image object) the path must take the form ['<attribute name>']. These attributes are always present so the only valid operation on them is 'replace'. For image properties, the path takes the form ['properties', '<property name>'] and all operations are valid. Future refactoring should simplify this code by hardening the image abstraction such that database details such as how image properties are stored do not have any influence here. """ updates = {} property_updates = image['properties'] for change in changes: path = change['path'] if len(path) == 1: assert change['op'] == 'replace' key = change['path'][0] if key == 'is_public' and change['value']: self._enforce(req, 'publicize_image') updates[key] = change['value'] else: assert len(path) == 2 assert path[0] == 'properties' update_method_name = '_do_%s_property' % change['op'] assert hasattr(self, update_method_name) update_method = getattr(self, update_method_name) update_method(property_updates, change) updates['properties'] = property_updates return updates def _do_replace_property(self, updates, change): """ Replace a single image property, ensuring it's present. """ key = change['path'][1] if key not in updates: msg = _("Property %s does not exist.") raise webob.exc.HTTPConflict(msg % key) updates[key] = change['value'] def _do_add_property(self, updates, change): """ Add a new image property, ensuring it does not already exist. """ key = change['path'][1] if key in updates: msg = _("Property %s already present.") raise webob.exc.HTTPConflict(msg % key) updates[key] = change['value'] def _do_remove_property(self, updates, change): """ Remove an image property, ensuring it's present. """ key = change['path'][1] if key not in updates: msg = _("Property %s does not exist.") raise webob.exc.HTTPConflict(msg % key) del updates[key] @utils.mutating def delete(self, req, image_id): self._enforce(req, 'delete_image') image = self._get_image(req.context, image_id) if image['protected']: msg = _("Unable to delete as image %(image_id)s is protected" % locals()) raise webob.exc.HTTPForbidden(explanation=msg) status = 'deleted' if image['location']: if CONF.delayed_delete: status = 'pending_delete' self.store_api.schedule_delayed_delete_from_backend( image['location'], id) else: self.store_api.safe_delete_from_backend(image['location'], req.context, id) try: self.db_api.image_update(req.context, image_id, {'status': status}) self.db_api.image_destroy(req.context, image_id) except (exception.NotFound, exception.Forbidden): msg = ("Failed to find image %(image_id)s to delete" % locals()) LOG.info(msg) raise webob.exc.HTTPNotFound() else: self.notifier.info('image.delete', image) class RequestDeserializer(wsgi.JSONRequestDeserializer): _readonly_properties = ['created_at', 'updated_at', 'status', 'checksum', 'size', 'direct_url', 'self', 'file', 'schema'] _reserved_properties = ['owner', 'is_public', 'location', 'deleted', 'deleted_at'] _base_properties = ['checksum', 'created_at', 'container_format', 'disk_format', 'id', 'min_disk', 'min_ram', 'name', 'size', 'status', 'tags', 'updated_at', 'visibility', 'protected'] def __init__(self, schema=None): super(RequestDeserializer, self).__init__() self.schema = schema or get_schema() def _parse_image(self, request): body = self._get_request_body(request) try: self.schema.validate(body) except exception.InvalidObject as e: raise webob.exc.HTTPBadRequest(explanation=unicode(e)) # Ensure all specified properties are allowed self._check_readonly(body) self._check_reserved(body) # Create a dict of base image properties, with user- and deployer- # defined properties contained in a 'properties' dictionary image = {'properties': body} for key in self._base_properties: try: image[key] = image['properties'].pop(key) except KeyError: pass if 'visibility' in image: image['is_public'] = image.pop('visibility') == 'public' return {'image': image} def _get_request_body(self, request): output = super(RequestDeserializer, self).default(request) if not 'body' in output: msg = _('Body expected in request.') raise webob.exc.HTTPBadRequest(explanation=msg) return output['body'] @classmethod def _check_readonly(cls, image): for key in cls._readonly_properties: if key in image: msg = "Attribute \'%s\' is read-only." % key raise webob.exc.HTTPForbidden(explanation=unicode(msg)) @classmethod def _check_reserved(cls, image): for key in cls._reserved_properties: if key in image: msg = "Attribute \'%s\' is reserved." % key raise webob.exc.HTTPForbidden(explanation=unicode(msg)) def create(self, request): return self._parse_image(request) def _get_change_operation(self, raw_change): op = None for key in ['replace', 'add', 'remove']: if key in raw_change: if op is not None: msg = _('Operation objects must contain only one member' ' named "add", "remove", or "replace".') raise webob.exc.HTTPBadRequest(explanation=msg) op = key if op is None: msg = _('Operation objects must contain exactly one member' ' named "add", "remove", or "replace".') raise webob.exc.HTTPBadRequest(explanation=msg) return op def _get_change_path(self, raw_change, op): key = self._decode_json_pointer(raw_change[op]) if key in self._readonly_properties: msg = "Attribute \'%s\' is read-only." % key raise webob.exc.HTTPForbidden(explanation=unicode(msg)) if key in self._reserved_properties: msg = "Attribute \'%s\' is reserved." % key raise webob.exc.HTTPForbidden(explanation=unicode(msg)) # For image properties, we need to put "properties" at the beginning if key not in self._base_properties: return ['properties', key] return [key] def _decode_json_pointer(self, pointer): """ Parse a json pointer. Json Pointers are defined in http://tools.ietf.org/html/draft-pbryan-zyp-json-pointer . The pointers use '/' for separation between object attributes, such that '/A/B' would evaluate to C in {"A": {"B": "C"}}. A '/' character in an attribute name is encoded as "~1" and a '~' character is encoded as "~0". """ self._validate_json_pointer(pointer) return pointer.lstrip('/').replace('~1', '/').replace('~0', '~') def _validate_json_pointer(self, pointer): """ Validate a json pointer. We only accept a limited form of json pointers. Specifically, we do not allow multiple levels of indirection, so there can only be one '/' in the pointer, located at the start of the string. """ if not pointer.startswith('/'): msg = _('Pointer `%s` does not start with "/".' % pointer) raise webob.exc.HTTPBadRequest(explanation=msg) if '/' in pointer[1:]: msg = _('Pointer `%s` contains more than one "/".' % pointer) raise webob.exc.HTTPBadRequest(explanation=msg) if re.match('~[^01]', pointer): msg = _('Pointer `%s` contains "~" not part of' ' a recognized escape sequence.' % pointer) raise webob.exc.HTTPBadRequest(explanation=msg) def _get_change_value(self, raw_change, op): if 'value' not in raw_change: msg = _('Operation "%s" requires a member named "value".') raise webob.exc.HTTPBadRequest(explanation=msg % op) return raw_change['value'] def _validate_change(self, change): if change['op'] == 'delete': return partial_image = {change['path'][-1]: change['value']} try: self.schema.validate(partial_image) except exception.InvalidObject as e: raise webob.exc.HTTPBadRequest(explanation=unicode(e)) def update(self, request): changes = [] valid_content_types = [ 'application/openstack-images-v2.0-json-patch' ] if request.content_type not in valid_content_types: headers = {'Accept-Patch': ','.join(valid_content_types)} raise webob.exc.HTTPUnsupportedMediaType(headers=headers) body = self._get_request_body(request) if not isinstance(body, list): msg = _('Request body must be a JSON array of operation objects.') raise webob.exc.HTTPBadRequest(explanation=msg) for raw_change in body: if not isinstance(raw_change, dict): msg = _('Operations must be JSON objects.') raise webob.exc.HTTPBadRequest(explanation=msg) op = self._get_change_operation(raw_change) path = self._get_change_path(raw_change, op) change = {'op': op, 'path': path} if not op == 'remove': change['value'] = self._get_change_value(raw_change, op) self._validate_change(change) if change['path'] == ['visibility']: change['path'] = ['is_public'] change['value'] = change['value'] == 'public' changes.append(change) return {'changes': changes} def _validate_limit(self, limit): try: limit = int(limit) except ValueError: msg = _("limit param must be an integer") raise webob.exc.HTTPBadRequest(explanation=msg) if limit < 0: msg = _("limit param must be positive") raise webob.exc.HTTPBadRequest(explanation=msg) return limit def _validate_sort_dir(self, sort_dir): if sort_dir not in ['asc', 'desc']: msg = _('Invalid sort direction: %s' % sort_dir) raise webob.exc.HTTPBadRequest(explanation=msg) return sort_dir def _get_filters(self, filters): visibility = filters.pop('visibility', None) if visibility: if visibility in ['public', 'private']: filters['is_public'] = visibility == 'public' else: msg = _('Invalid visibility value: %s') % visibility raise webob.exc.HTTPBadRequest(explanation=msg) return filters def index(self, request): params = request.params.copy() limit = params.pop('limit', None) marker = params.pop('marker', None) sort_dir = params.pop('sort_dir', 'desc') query_params = { 'sort_key': params.pop('sort_key', 'created_at'), 'sort_dir': self._validate_sort_dir(sort_dir), 'filters': self._get_filters(params), } if marker is not None: query_params['marker'] = marker if limit is not None: query_params['limit'] = self._validate_limit(limit) return query_params class ResponseSerializer(wsgi.JSONResponseSerializer): def __init__(self, schema=None): super(ResponseSerializer, self).__init__() self.schema = schema or get_schema() def _get_image_href(self, image, subcollection=''): base_href = '/v2/images/%s' % image['id'] if subcollection: base_href = '%s/%s' % (base_href, subcollection) return base_href def _get_image_links(self, image): return [ {'rel': 'self', 'href': self._get_image_href(image)}, {'rel': 'file', 'href': self._get_image_href(image, 'file')}, {'rel': 'describedby', 'href': '/v2/schemas/image'}, ] def _format_image(self, image): #NOTE(bcwaldon): merge the contained properties dict with the # top-level image object image_view = image['properties'] attributes = ['id', 'name', 'disk_format', 'container_format', 'size', 'status', 'checksum', 'tags', 'protected', 'created_at', 'updated_at', 'min_ram', 'min_disk'] for key in attributes: image_view[key] = image[key] location = image['location'] if CONF.show_image_direct_url and location is not None: image_view['direct_url'] = location visibility = 'public' if image['is_public'] else 'private' image_view['visibility'] = visibility image_view['self'] = self._get_image_href(image) image_view['file'] = self._get_image_href(image, 'file') image_view['schema'] = '/v2/schemas/image' self._serialize_datetimes(image_view) image_view = self.schema.filter(image_view) return image_view @staticmethod def _serialize_datetimes(image): for (key, value) in image.iteritems(): if isinstance(value, datetime.datetime): image[key] = timeutils.isotime(value) def create(self, response, image): response.status_int = 201 body = json.dumps(self._format_image(image), ensure_ascii=False) response.unicode_body = unicode(body) response.content_type = 'application/json' response.location = self._get_image_href(image) def show(self, response, image): body = json.dumps(self._format_image(image), ensure_ascii=False) response.unicode_body = unicode(body) response.content_type = 'application/json' def update(self, response, image): body = json.dumps(self._format_image(image), ensure_ascii=False) response.unicode_body = unicode(body) response.content_type = 'application/json' def index(self, response, result): params = dict(response.request.params) params.pop('marker', None) query = urllib.urlencode(params) body = { 'images': [self._format_image(i) for i in result['images']], 'first': '/v2/images', 'schema': '/v2/schemas/images', } if query: body['first'] = '%s?%s' % (body['first'], query) if 'next_marker' in result: params['marker'] = result['next_marker'] next_query = urllib.urlencode(params) body['next'] = '/v2/images?%s' % next_query response.unicode_body = unicode(json.dumps(body, ensure_ascii=False)) response.content_type = 'application/json' def delete(self, response, result): response.status_int = 204 _BASE_PROPERTIES = { 'id': { 'type': 'string', 'description': 'An identifier for the image', 'pattern': ('^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}' '-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$'), }, 'name': { 'type': 'string', 'description': 'Descriptive name for the image', 'maxLength': 255, }, 'status': { 'type': 'string', 'description': 'Status of the image', 'enum': ['queued', 'saving', 'active', 'killed', 'deleted', 'pending_delete'], }, 'visibility': { 'type': 'string', 'description': 'Scope of image accessibility', 'enum': ['public', 'private'], }, 'protected': { 'type': 'boolean', 'description': 'If true, image will not be deletable.', }, 'checksum': { 'type': 'string', 'description': 'md5 hash of image contents.', 'type': 'string', 'maxLength': 32, }, 'size': { 'type': 'integer', 'description': 'Size of image file in bytes', }, 'container_format': { 'type': 'string', 'description': '', 'type': 'string', 'enum': ['bare', 'ovf', 'ami', 'aki', 'ari'], }, 'disk_format': { 'type': 'string', 'description': '', 'type': 'string', 'enum': ['raw', 'vhd', 'vmdk', 'vdi', 'iso', 'qcow2', 'aki', 'ari', 'ami'], }, 'created_at': { 'type': 'string', 'description': 'Date and time of image registration', #TODO(bcwaldon): our jsonschema library doesn't seem to like the # format attribute, figure out why! #'format': 'date-time', }, 'updated_at': { 'type': 'string', 'description': 'Date and time of the last image modification', #'format': 'date-time', }, 'tags': { 'type': 'array', 'description': 'List of strings related to the image', 'items': { 'type': 'string', 'maxLength': 255, }, }, 'direct_url': { 'type': 'string', 'description': 'URL to access the image file kept in external store', }, 'min_ram': { 'type': 'integer', 'description': 'Amount of ram (in MB) required to boot image.', }, 'min_disk': { 'type': 'integer', 'description': 'Amount of disk space (in GB) required to boot image.', }, 'self': {'type': 'string'}, 'file': {'type': 'string'}, 'schema': {'type': 'string'}, } _BASE_LINKS = [ {'rel': 'self', 'href': '{self}'}, {'rel': 'enclosure', 'href': '{file}'}, {'rel': 'describedby', 'href': '{schema}'}, ] def get_schema(custom_properties=None): properties = copy.deepcopy(_BASE_PROPERTIES) links = copy.deepcopy(_BASE_LINKS) if CONF.allow_additional_image_properties: schema = glance.schema.PermissiveSchema('image', properties, links) else: schema = glance.schema.Schema('image', properties) schema.merge_properties(custom_properties or {}) return schema def get_collection_schema(custom_properties=None): image_schema = get_schema(custom_properties) return glance.schema.CollectionSchema('images', image_schema) def load_custom_properties(): """Find the schema properties files and load them into a dict.""" filename = 'schema-image.json' match = CONF.find_file(filename) if match: schema_file = open(match) schema_data = schema_file.read() return json.loads(schema_data) else: msg = _('Could not find schema properties file %s. Continuing ' 'without custom properties') LOG.warn(msg % filename) return {} def create_resource(custom_properties=None): """Images resource factory method""" schema = get_schema(custom_properties) deserializer = RequestDeserializer(schema) serializer = ResponseSerializer(schema) controller = ImagesController() return wsgi.Resource(controller, deserializer, serializer)
./CrossVul/dataset_final_sorted/CWE-264/py/bad_3784_0
crossvul-python_data_good_3725_0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Main entry point into the Identity service.""" import urllib import urlparse import uuid from keystone.common import logging from keystone.common import manager from keystone.common import wsgi from keystone import config from keystone import exception from keystone import policy from keystone import token CONF = config.CONF LOG = logging.getLogger(__name__) class Manager(manager.Manager): """Default pivot point for the Identity backend. See :mod:`keystone.common.manager.Manager` for more details on how this dynamically calls the backend. """ def __init__(self): super(Manager, self).__init__(CONF.identity.driver) class Driver(object): """Interface description for an Identity driver.""" def authenticate(self, user_id=None, tenant_id=None, password=None): """Authenticate a given user, tenant and password. :returns: (user_ref, tenant_ref, metadata_ref) :raises: AssertionError """ raise exception.NotImplemented() def get_tenant(self, tenant_id): """Get a tenant by id. :returns: tenant_ref :raises: keystone.exception.TenantNotFound """ raise exception.NotImplemented() def get_tenant_by_name(self, tenant_name): """Get a tenant by name. :returns: tenant_ref :raises: keystone.exception.TenantNotFound """ raise exception.NotImplemented() def get_user(self, user_id): """Get a user by id. :returns: user_ref :raises: keystone.exception.UserNotFound """ raise exception.NotImplemented() def get_user_by_name(self, user_name): """Get a user by name. :returns: user_ref :raises: keystone.exception.UserNotFound """ raise exception.NotImplemented() def get_role(self, role_id): """Get a role by id. :returns: role_ref :raises: keystone.exception.RoleNotFound """ raise exception.NotImplemented() def list_users(self): """List all users in the system. NOTE(termie): I'd prefer if this listed only the users for a given tenant. :returns: a list of user_refs or an empty list """ raise exception.NotImplemented() def list_roles(self): """List all roles in the system. :returns: a list of role_refs or an empty list. """ raise exception.NotImplemented() # NOTE(termie): seven calls below should probably be exposed by the api # more clearly when the api redesign happens def add_user_to_tenant(self, tenant_id, user_id): """Add user to a tenant without an explicit role relationship. :raises: keystone.exception.TenantNotFound, keystone.exception.UserNotFound """ raise exception.NotImplemented() def remove_user_from_tenant(self, tenant_id, user_id): """Remove user from a tenant without an explicit role relationship. :raises: keystone.exception.TenantNotFound, keystone.exception.UserNotFound """ raise exception.NotImplemented() def get_all_tenants(self): """FIXME(dolph): Lists all tenants in the system? I'm not sure how this is different from get_tenants, why get_tenants isn't documented as part of the driver, or why it's called get_tenants instead of list_tenants (i.e. list_roles and list_users)... :returns: a list of ... FIXME(dolph): tenant_refs or tenant_id's? """ raise exception.NotImplemented() def get_tenant_users(self, tenant_id): """FIXME(dolph): Lists all users with a relationship to the specified tenant? :returns: a list of ... FIXME(dolph): user_refs or user_id's? :raises: keystone.exception.UserNotFound """ raise exception.NotImplemented() def get_tenants_for_user(self, user_id): """Get the tenants associated with a given user. :returns: a list of tenant_id's. :raises: keystone.exception.UserNotFound """ raise exception.NotImplemented() def get_roles_for_user_and_tenant(self, user_id, tenant_id): """Get the roles associated with a user within given tenant. :returns: a list of role ids. :raises: keystone.exception.UserNotFound, keystone.exception.TenantNotFound """ raise exception.NotImplemented() def add_role_to_user_and_tenant(self, user_id, tenant_id, role_id): """Add a role to a user within given tenant. :raises: keystone.exception.UserNotFound, keystone.exception.TenantNotFound, keystone.exception.RoleNotFound """ raise exception.NotImplemented() def remove_role_from_user_and_tenant(self, user_id, tenant_id, role_id): """Remove a role from a user within given tenant. :raises: keystone.exception.UserNotFound, keystone.exception.TenantNotFound, keystone.exception.RoleNotFound """ raise exception.NotImplemented() # user crud def create_user(self, user_id, user): """Creates a new user. :raises: keystone.exception.Conflict """ raise exception.NotImplemented() def update_user(self, user_id, user): """Updates an existing user. :raises: keystone.exception.UserNotFound, keystone.exception.Conflict """ raise exception.NotImplemented() def delete_user(self, user_id): """Deletes an existing user. :raises: keystone.exception.UserNotFound """ raise exception.NotImplemented() # tenant crud def create_tenant(self, tenant_id, tenant): """Creates a new tenant. :raises: keystone.exception.Conflict """ raise exception.NotImplemented() def update_tenant(self, tenant_id, tenant): """Updates an existing tenant. :raises: keystone.exception.TenantNotFound, keystone.exception.Conflict """ raise exception.NotImplemented() def delete_tenant(self, tenant_id): """Deletes an existing tenant. :raises: keystone.exception.TenantNotFound """ raise exception.NotImplemented() # metadata crud def get_metadata(self, user_id, tenant_id): raise exception.NotImplemented() def create_metadata(self, user_id, tenant_id, metadata): raise exception.NotImplemented() def update_metadata(self, user_id, tenant_id, metadata): raise exception.NotImplemented() def delete_metadata(self, user_id, tenant_id): raise exception.NotImplemented() # role crud def create_role(self, role_id, role): """Creates a new role. :raises: keystone.exception.Conflict """ raise exception.NotImplemented() def update_role(self, role_id, role): """Updates an existing role. :raises: keystone.exception.RoleNotFound, keystone.exception.Conflict """ raise exception.NotImplemented() def delete_role(self, role_id): """Deletes an existing role. :raises: keystone.exception.RoleNotFound """ raise exception.NotImplemented() class PublicRouter(wsgi.ComposableRouter): def add_routes(self, mapper): tenant_controller = TenantController() mapper.connect('/tenants', controller=tenant_controller, action='get_tenants_for_token', conditions=dict(method=['GET'])) class AdminRouter(wsgi.ComposableRouter): def add_routes(self, mapper): # Tenant Operations tenant_controller = TenantController() mapper.connect('/tenants', controller=tenant_controller, action='get_all_tenants', conditions=dict(method=['GET'])) mapper.connect('/tenants/{tenant_id}', controller=tenant_controller, action='get_tenant', conditions=dict(method=['GET'])) # User Operations user_controller = UserController() mapper.connect('/users/{user_id}', controller=user_controller, action='get_user', conditions=dict(method=['GET'])) # Role Operations roles_controller = RoleController() mapper.connect('/tenants/{tenant_id}/users/{user_id}/roles', controller=roles_controller, action='get_user_roles', conditions=dict(method=['GET'])) mapper.connect('/users/{user_id}/roles', controller=roles_controller, action='get_user_roles', conditions=dict(method=['GET'])) class TenantController(wsgi.Application): def __init__(self): self.identity_api = Manager() self.policy_api = policy.Manager() self.token_api = token.Manager() super(TenantController, self).__init__() def get_all_tenants(self, context, **kw): """Gets a list of all tenants for an admin user.""" self.assert_admin(context) tenant_refs = self.identity_api.get_tenants(context) params = { 'limit': context['query_string'].get('limit'), 'marker': context['query_string'].get('marker'), } return self._format_tenant_list(tenant_refs, **params) def get_tenants_for_token(self, context, **kw): """Get valid tenants for token based on token used to authenticate. Pulls the token from the context, validates it and gets the valid tenants for the user in the token. Doesn't care about token scopedness. """ try: token_ref = self.token_api.get_token(context=context, token_id=context['token_id']) except exception.NotFound: raise exception.Unauthorized() user_ref = token_ref['user'] tenant_ids = self.identity_api.get_tenants_for_user( context, user_ref['id']) tenant_refs = [] for tenant_id in tenant_ids: tenant_refs.append(self.identity_api.get_tenant( context=context, tenant_id=tenant_id)) params = { 'limit': context['query_string'].get('limit'), 'marker': context['query_string'].get('marker'), } return self._format_tenant_list(tenant_refs, **params) def get_tenant(self, context, tenant_id): # TODO(termie): this stuff should probably be moved to middleware self.assert_admin(context) return {'tenant': self.identity_api.get_tenant(context, tenant_id)} # CRUD Extension def create_tenant(self, context, tenant): tenant_ref = self._normalize_dict(tenant) if not 'name' in tenant_ref or not tenant_ref['name']: msg = 'Name field is required and cannot be empty' raise exception.ValidationError(message=msg) self.assert_admin(context) tenant_ref['id'] = tenant_ref.get('id', uuid.uuid4().hex) tenant = self.identity_api.create_tenant( context, tenant_ref['id'], tenant_ref) return {'tenant': tenant} def update_tenant(self, context, tenant_id, tenant): self.assert_admin(context) tenant_ref = self.identity_api.update_tenant( context, tenant_id, tenant) return {'tenant': tenant_ref} def delete_tenant(self, context, tenant_id): self.assert_admin(context) self.identity_api.delete_tenant(context, tenant_id) def get_tenant_users(self, context, tenant_id, **kw): self.assert_admin(context) user_refs = self.identity_api.get_tenant_users(context, tenant_id) return {'users': user_refs} def _format_tenant_list(self, tenant_refs, **kwargs): marker = kwargs.get('marker') first_index = 0 if marker is not None: for (marker_index, tenant) in enumerate(tenant_refs): if tenant['id'] == marker: # we start pagination after the marker first_index = marker_index + 1 break else: msg = 'Marker could not be found' raise exception.ValidationError(message=msg) limit = kwargs.get('limit') last_index = None if limit is not None: try: limit = int(limit) if limit < 0: raise AssertionError() except (ValueError, AssertionError): msg = 'Invalid limit value' raise exception.ValidationError(message=msg) last_index = first_index + limit tenant_refs = tenant_refs[first_index:last_index] for x in tenant_refs: if 'enabled' not in x: x['enabled'] = True o = {'tenants': tenant_refs, 'tenants_links': []} return o class UserController(wsgi.Application): def __init__(self): self.identity_api = Manager() self.policy_api = policy.Manager() self.token_api = token.Manager() super(UserController, self).__init__() def get_user(self, context, user_id): self.assert_admin(context) return {'user': self.identity_api.get_user(context, user_id)} def get_users(self, context): # NOTE(termie): i can't imagine that this really wants all the data # about every single user in the system... self.assert_admin(context) return {'users': self.identity_api.list_users(context)} # CRUD extension def create_user(self, context, user): user = self._normalize_dict(user) self.assert_admin(context) if not 'name' in user or not user['name']: msg = 'Name field is required and cannot be empty' raise exception.ValidationError(message=msg) tenant_id = user.get('tenantId', None) if (tenant_id is not None and self.identity_api.get_tenant(context, tenant_id) is None): raise exception.TenantNotFound(tenant_id=tenant_id) user_id = uuid.uuid4().hex user_ref = user.copy() user_ref['id'] = user_id new_user_ref = self.identity_api.create_user( context, user_id, user_ref) if tenant_id: self.identity_api.add_user_to_tenant(context, tenant_id, user_id) return {'user': new_user_ref} def update_user(self, context, user_id, user): # NOTE(termie): this is really more of a patch than a put self.assert_admin(context) user_ref = self.identity_api.update_user(context, user_id, user) # If the password was changed or the user was disabled we clear tokens if user.get('password') or not user.get('enabled', True): try: for token_id in self.token_api.list_tokens(context, user_id): self.token_api.delete_token(context, token_id) except exception.NotImplemented: # The users status has been changed but tokens remain valid for # backends that can't list tokens for users LOG.warning('User %s status has changed, but existing tokens ' 'remain valid' % user_id) return {'user': user_ref} def delete_user(self, context, user_id): self.assert_admin(context) self.identity_api.delete_user(context, user_id) def set_user_enabled(self, context, user_id, user): return self.update_user(context, user_id, user) def set_user_password(self, context, user_id, user): return self.update_user(context, user_id, user) def update_user_tenant(self, context, user_id, user): """Update the default tenant.""" self.assert_admin(context) # ensure that we're a member of that tenant tenant_id = user.get('tenantId') self.identity_api.add_user_to_tenant(context, tenant_id, user_id) return self.update_user(context, user_id, user) class RoleController(wsgi.Application): def __init__(self): self.identity_api = Manager() self.token_api = token.Manager() self.policy_api = policy.Manager() super(RoleController, self).__init__() # COMPAT(essex-3) def get_user_roles(self, context, user_id, tenant_id=None): """Get the roles for a user and tenant pair. Since we're trying to ignore the idea of user-only roles we're not implementing them in hopes that the idea will die off. """ self.assert_admin(context) if tenant_id is None: raise exception.NotImplemented(message='User roles not supported: ' 'tenant ID required') roles = self.identity_api.get_roles_for_user_and_tenant( context, user_id, tenant_id) return {'roles': [self.identity_api.get_role(context, x) for x in roles]} # CRUD extension def get_role(self, context, role_id): self.assert_admin(context) return {'role': self.identity_api.get_role(context, role_id)} def create_role(self, context, role): role = self._normalize_dict(role) self.assert_admin(context) if not 'name' in role or not role['name']: msg = 'Name field is required and cannot be empty' raise exception.ValidationError(message=msg) role_id = uuid.uuid4().hex role['id'] = role_id role_ref = self.identity_api.create_role(context, role_id, role) return {'role': role_ref} def delete_role(self, context, role_id): self.assert_admin(context) self.identity_api.delete_role(context, role_id) def get_roles(self, context): self.assert_admin(context) return {'roles': self.identity_api.list_roles(context)} def add_role_to_user(self, context, user_id, role_id, tenant_id=None): """Add a role to a user and tenant pair. Since we're trying to ignore the idea of user-only roles we're not implementing them in hopes that the idea will die off. """ self.assert_admin(context) if tenant_id is None: raise exception.NotImplemented(message='User roles not supported: ' 'tenant_id required') # This still has the weird legacy semantics that adding a role to # a user also adds them to a tenant self.identity_api.add_user_to_tenant(context, tenant_id, user_id) self.identity_api.add_role_to_user_and_tenant( context, user_id, tenant_id, role_id) role_ref = self.identity_api.get_role(context, role_id) return {'role': role_ref} def remove_role_from_user(self, context, user_id, role_id, tenant_id=None): """Remove a role from a user and tenant pair. Since we're trying to ignore the idea of user-only roles we're not implementing them in hopes that the idea will die off. """ self.assert_admin(context) if tenant_id is None: raise exception.NotImplemented(message='User roles not supported: ' 'tenant_id required') # This still has the weird legacy semantics that adding a role to # a user also adds them to a tenant, so we must follow up on that self.identity_api.remove_role_from_user_and_tenant( context, user_id, tenant_id, role_id) roles = self.identity_api.get_roles_for_user_and_tenant( context, user_id, tenant_id) if not roles: self.identity_api.remove_user_from_tenant( context, tenant_id, user_id) return # COMPAT(diablo): CRUD extension def get_role_refs(self, context, user_id): """Ultimate hack to get around having to make role_refs first-class. This will basically iterate over the various roles the user has in all tenants the user is a member of and create fake role_refs where the id encodes the user-tenant-role information so we can look up the appropriate data when we need to delete them. """ self.assert_admin(context) # Ensure user exists by getting it first. self.identity_api.get_user(context, user_id) tenant_ids = self.identity_api.get_tenants_for_user(context, user_id) o = [] for tenant_id in tenant_ids: role_ids = self.identity_api.get_roles_for_user_and_tenant( context, user_id, tenant_id) for role_id in role_ids: ref = {'roleId': role_id, 'tenantId': tenant_id, 'userId': user_id} ref['id'] = urllib.urlencode(ref) o.append(ref) return {'roles': o} # COMPAT(diablo): CRUD extension def create_role_ref(self, context, user_id, role): """This is actually used for adding a user to a tenant. In the legacy data model adding a user to a tenant required setting a role. """ self.assert_admin(context) # TODO(termie): for now we're ignoring the actual role tenant_id = role.get('tenantId') role_id = role.get('roleId') self.identity_api.add_user_to_tenant(context, tenant_id, user_id) self.identity_api.add_role_to_user_and_tenant( context, user_id, tenant_id, role_id) role_ref = self.identity_api.get_role(context, role_id) return {'role': role_ref} # COMPAT(diablo): CRUD extension def delete_role_ref(self, context, user_id, role_ref_id): """This is actually used for deleting a user from a tenant. In the legacy data model removing a user from a tenant required deleting a role. To emulate this, we encode the tenant and role in the role_ref_id, and if this happens to be the last role for the user-tenant pair, we remove the user from the tenant. """ self.assert_admin(context) # TODO(termie): for now we're ignoring the actual role role_ref_ref = urlparse.parse_qs(role_ref_id) tenant_id = role_ref_ref.get('tenantId')[0] role_id = role_ref_ref.get('roleId')[0] self.identity_api.remove_role_from_user_and_tenant( context, user_id, tenant_id, role_id) roles = self.identity_api.get_roles_for_user_and_tenant( context, user_id, tenant_id) if not roles: self.identity_api.remove_user_from_tenant( context, tenant_id, user_id)
./CrossVul/dataset_final_sorted/CWE-264/py/good_3725_0
crossvul-python_data_good_3697_2
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # # Copyright 2011, Piston Cloud Computing, Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Utility methods to resize, repartition, and modify disk images. Includes injection of SSH PGP keys into authorized_keys file. """ import crypt import os import random import tempfile from nova import exception from nova import flags from nova.openstack.common import cfg from nova.openstack.common import jsonutils from nova.openstack.common import log as logging from nova import utils from nova.virt.disk import guestfs from nova.virt.disk import loop from nova.virt.disk import nbd from nova.virt import images LOG = logging.getLogger(__name__) disk_opts = [ cfg.StrOpt('injected_network_template', default='$pybasedir/nova/virt/interfaces.template', help='Template file for injected network'), cfg.ListOpt('img_handlers', default=['loop', 'nbd', 'guestfs'], help='Order of methods used to mount disk images'), # NOTE(yamahata): ListOpt won't work because the command may include a # comma. For example: # # mkfs.ext3 -O dir_index,extent -E stride=8,stripe-width=16 # --label %(fs_label)s %(target)s # # list arguments are comma separated and there is no way to # escape such commas. # cfg.MultiStrOpt('virt_mkfs', default=[ 'default=mkfs.ext3 -L %(fs_label)s -F %(target)s', 'linux=mkfs.ext3 -L %(fs_label)s -F %(target)s', 'windows=mkfs.ntfs' ' --force --fast --label %(fs_label)s %(target)s', # NOTE(yamahata): vfat case #'windows=mkfs.vfat -n %(fs_label)s %(target)s', ], help='mkfs commands for ephemeral device. ' 'The format is <os_type>=<mkfs command>'), ] FLAGS = flags.FLAGS FLAGS.register_opts(disk_opts) _MKFS_COMMAND = {} _DEFAULT_MKFS_COMMAND = None for s in FLAGS.virt_mkfs: # NOTE(yamahata): mkfs command may includes '=' for its options. # So item.partition('=') doesn't work here os_type, mkfs_command = s.split('=', 1) if os_type: _MKFS_COMMAND[os_type] = mkfs_command if os_type == 'default': _DEFAULT_MKFS_COMMAND = mkfs_command def mkfs(os_type, fs_label, target): mkfs_command = (_MKFS_COMMAND.get(os_type, _DEFAULT_MKFS_COMMAND) or '') % locals() if mkfs_command: utils.execute(*mkfs_command.split()) def resize2fs(image, check_exit_code=False): utils.execute('e2fsck', '-fp', image, check_exit_code=check_exit_code) utils.execute('resize2fs', image, check_exit_code=check_exit_code) def get_disk_size(path): """Get the (virtual) size of a disk image :param path: Path to the disk image :returns: Size (in bytes) of the given disk image as it would be seen by a virtual machine. """ size = images.qemu_img_info(path)['virtual size'] size = size.split('(')[1].split()[0] return int(size) def extend(image, size): """Increase image to size""" virt_size = get_disk_size(image) if virt_size >= size: return utils.execute('qemu-img', 'resize', image, size) # NOTE(vish): attempts to resize filesystem resize2fs(image) def can_resize_fs(image, size, use_cow=False): """Check whether we can resize contained file system.""" # Check that we're increasing the size virt_size = get_disk_size(image) if virt_size >= size: return False # Check the image is unpartitioned if use_cow: # Try to mount an unpartitioned qcow2 image try: inject_data(image, use_cow=True) except exception.NovaException: return False else: # For raw, we can directly inspect the file system try: utils.execute('e2label', image) except exception.ProcessExecutionError: return False return True def bind(src, target, instance_name): """Bind device to a filesytem""" if src: utils.execute('touch', target, run_as_root=True) utils.execute('mount', '-o', 'bind', src, target, run_as_root=True) s = os.stat(src) cgroup_info = "b %s:%s rwm\n" % (os.major(s.st_rdev), os.minor(s.st_rdev)) cgroups_path = ("/sys/fs/cgroup/devices/libvirt/lxc/" "%s/devices.allow" % instance_name) utils.execute('tee', cgroups_path, process_input=cgroup_info, run_as_root=True) def unbind(target): if target: utils.execute('umount', target, run_as_root=True) class _DiskImage(object): """Provide operations on a disk image file.""" tmp_prefix = 'openstack-disk-mount-tmp' def __init__(self, image, partition=None, use_cow=False, mount_dir=None): # These passed to each mounter self.image = image self.partition = partition self.mount_dir = mount_dir # Internal self._mkdir = False self._mounter = None self._errors = [] # As a performance tweak, don't bother trying to # directly loopback mount a cow image. self.handlers = FLAGS.img_handlers[:] if use_cow and 'loop' in self.handlers: self.handlers.remove('loop') if not self.handlers: msg = _('no capable image handler configured') raise exception.NovaException(msg) if mount_dir: # Note the os.path.ismount() shortcut doesn't # work with libguestfs due to permissions issues. device = self._device_for_path(mount_dir) if device: self._reset(device) @staticmethod def _device_for_path(path): device = None with open("/proc/mounts", 'r') as ifp: for line in ifp: fields = line.split() if fields[1] == path: device = fields[0] break return device def _reset(self, device): """Reset internal state for a previously mounted directory.""" mounter_cls = self._handler_class(device=device) mounter = mounter_cls(image=self.image, partition=self.partition, mount_dir=self.mount_dir, device=device) self._mounter = mounter mount_name = os.path.basename(self.mount_dir or '') self._mkdir = mount_name.startswith(self.tmp_prefix) @property def errors(self): """Return the collated errors from all operations.""" return '\n--\n'.join([''] + self._errors) @staticmethod def _handler_class(mode=None, device=None): """Look up the appropriate class to use based on MODE or DEVICE.""" for cls in (loop.Mount, nbd.Mount, guestfs.Mount): if mode and cls.mode == mode: return cls elif device and cls.device_id_string in device: return cls msg = _("no disk image handler for: %s") % mode or device raise exception.NovaException(msg) def mount(self): """Mount a disk image, using the object attributes. The first supported means provided by the mount classes is used. True, or False is returned and the 'errors' attribute contains any diagnostics. """ if self._mounter: raise exception.NovaException(_('image already mounted')) if not self.mount_dir: self.mount_dir = tempfile.mkdtemp(prefix=self.tmp_prefix) self._mkdir = True try: for h in self.handlers: mounter_cls = self._handler_class(h) mounter = mounter_cls(image=self.image, partition=self.partition, mount_dir=self.mount_dir) if mounter.do_mount(): self._mounter = mounter break else: LOG.debug(mounter.error) self._errors.append(mounter.error) finally: if not self._mounter: self.umount() # rmdir return bool(self._mounter) def umount(self): """Unmount a disk image from the file system.""" try: if self._mounter: self._mounter.do_umount() finally: if self._mkdir: os.rmdir(self.mount_dir) # Public module functions def inject_data(image, key=None, net=None, metadata=None, admin_password=None, files=None, partition=None, use_cow=False): """Injects a ssh key and optionally net data into a disk image. it will mount the image as a fully partitioned disk and attempt to inject into the specified partition number. If partition is not specified it mounts the image as a single partition. """ img = _DiskImage(image=image, partition=partition, use_cow=use_cow) if img.mount(): try: inject_data_into_fs(img.mount_dir, key, net, metadata, admin_password, files) finally: img.umount() else: raise exception.NovaException(img.errors) def setup_container(image, container_dir, use_cow=False): """Setup the LXC container. It will mount the loopback image to the container directory in order to create the root filesystem for the container. """ img = _DiskImage(image=image, use_cow=use_cow, mount_dir=container_dir) if not img.mount(): LOG.error(_("Failed to mount container filesystem '%(image)s' " "on '%(target)s': %(errors)s") % {"image": img, "target": container_dir, "errors": img.errors}) raise exception.NovaException(img.errors) def destroy_container(container_dir): """Destroy the container once it terminates. It will umount the container that is mounted, and delete any linked devices. """ try: img = _DiskImage(image=None, mount_dir=container_dir) img.umount() except Exception, exn: LOG.exception(_('Failed to unmount container filesystem: %s'), exn) def inject_data_into_fs(fs, key, net, metadata, admin_password, files): """Injects data into a filesystem already mounted by the caller. Virt connections can call this directly if they mount their fs in a different way to inject_data """ if key: _inject_key_into_fs(key, fs) if net: _inject_net_into_fs(net, fs) if metadata: _inject_metadata_into_fs(metadata, fs) if admin_password: _inject_admin_password_into_fs(admin_password, fs) if files: for (path, contents) in files: _inject_file_into_fs(fs, path, contents) def _join_and_check_path_within_fs(fs, *args): '''os.path.join() with safety check for injected file paths. Join the supplied path components and make sure that the resulting path we are injecting into is within the mounted guest fs. Trying to be clever and specifying a path with '..' in it will hit this safeguard. ''' absolute_path, _err = utils.execute('readlink', '-nm', os.path.join(fs, *args), run_as_root=True) if not absolute_path.startswith(os.path.realpath(fs) + '/'): raise exception.Invalid(_('injected file path not valid')) return absolute_path def _inject_file_into_fs(fs, path, contents, append=False): absolute_path = _join_and_check_path_within_fs(fs, path.lstrip('/')) parent_dir = os.path.dirname(absolute_path) utils.execute('mkdir', '-p', parent_dir, run_as_root=True) args = [] if append: args.append('-a') args.append(absolute_path) kwargs = dict(process_input=contents, run_as_root=True) utils.execute('tee', *args, **kwargs) def _inject_metadata_into_fs(metadata, fs): metadata = dict([(m.key, m.value) for m in metadata]) _inject_file_into_fs(fs, 'meta.js', jsonutils.dumps(metadata)) def _setup_selinux_for_keys(fs): """Get selinux guests to ensure correct context on injected keys.""" se_cfg = _join_and_check_path_within_fs(fs, 'etc', 'selinux') se_cfg, _err = utils.trycmd('readlink', '-e', se_cfg, run_as_root=True) if not se_cfg: return rclocal = _join_and_check_path_within_fs(fs, 'etc', 'rc.local') # Support systemd based systems rc_d = _join_and_check_path_within_fs(fs, 'etc', 'rc.d') rclocal_e, _err = utils.trycmd('readlink', '-e', rclocal, run_as_root=True) rc_d_e, _err = utils.trycmd('readlink', '-e', rc_d, run_as_root=True) if not rclocal_e and rc_d_e: rclocal = os.path.join(rc_d, 'rc.local') # Note some systems end rc.local with "exit 0" # and so to append there you'd need something like: # utils.execute('sed', '-i', '${/^exit 0$/d}' rclocal, run_as_root=True) restorecon = [ '#!/bin/sh\n', '# Added by Nova to ensure injected ssh keys have the right context\n', 'restorecon -RF /root/.ssh/ 2>/dev/null || :\n', ] rclocal_rel = os.path.relpath(rclocal, fs) _inject_file_into_fs(fs, rclocal_rel, ''.join(restorecon), append=True) utils.execute('chmod', 'a+x', rclocal, run_as_root=True) def _inject_key_into_fs(key, fs): """Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """ sshdir = _join_and_check_path_within_fs(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_as_root=True) utils.execute('chown', 'root', sshdir, run_as_root=True) utils.execute('chmod', '700', sshdir, run_as_root=True) keyfile = os.path.join('root', '.ssh', 'authorized_keys') key_data = ''.join([ '\n', '# The following ssh key was injected by Nova', '\n', key.strip(), '\n', ]) _inject_file_into_fs(fs, keyfile, key_data, append=True) _setup_selinux_for_keys(fs) def _inject_net_into_fs(net, fs): """Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """ netdir = _join_and_check_path_within_fs(fs, 'etc', 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute('chown', 'root:root', netdir, run_as_root=True) utils.execute('chmod', 755, netdir, run_as_root=True) netfile = os.path.join('etc', 'network', 'interfaces') _inject_file_into_fs(fs, netfile, net) def _inject_admin_password_into_fs(admin_passwd, fs): """Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require a guest agent running in the instance. """ # The approach used here is to copy the password and shadow # files from the instance filesystem to local files, make any # necessary changes, and then copy them back. admin_user = 'root' fd, tmp_passwd = tempfile.mkstemp() os.close(fd) fd, tmp_shadow = tempfile.mkstemp() os.close(fd) passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd') shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow') utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True) utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True) _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow) utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True) os.unlink(tmp_passwd) utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True) os.unlink(tmp_shadow) def _set_passwd(username, admin_passwd, passwd_file, shadow_file): """set the password for username to admin_passwd The passwd_file is not modified. The shadow_file is updated. if the username is not found in both files, an exception is raised. :param username: the username :param encrypted_passwd: the encrypted password :param passwd_file: path to the passwd file :param shadow_file: path to the shadow password file :returns: nothing :raises: exception.NovaException(), IOError() """ salt_set = ('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789./') # encryption algo - id pairs for crypt() algos = {'SHA-512': '$6$', 'SHA-256': '$5$', 'MD5': '$1$', 'DES': ''} salt = 16 * ' ' salt = ''.join([random.choice(salt_set) for c in salt]) # crypt() depends on the underlying libc, and may not support all # forms of hash. We try md5 first. If we get only 13 characters back, # then the underlying crypt() didn't understand the '$n$salt' magic, # so we fall back to DES. # md5 is the default because it's widely supported. Although the # local crypt() might support stronger SHA, the target instance # might not. encrypted_passwd = crypt.crypt(admin_passwd, algos['MD5'] + salt) if len(encrypted_passwd) == 13: encrypted_passwd = crypt.crypt(admin_passwd, algos['DES'] + salt) try: p_file = open(passwd_file, 'rb') s_file = open(shadow_file, 'rb') # username MUST exist in passwd file or it's an error found = False for entry in p_file: split_entry = entry.split(':') if split_entry[0] == username: found = True break if not found: msg = _('User %(username)s not found in password file.') raise exception.NovaException(msg % username) # update password in the shadow file.It's an error if the # the user doesn't exist. new_shadow = list() found = False for entry in s_file: split_entry = entry.split(':') if split_entry[0] == username: split_entry[1] = encrypted_passwd found = True new_entry = ':'.join(split_entry) new_shadow.append(new_entry) s_file.close() if not found: msg = _('User %(username)s not found in shadow file.') raise exception.NovaException(msg % username) s_file = open(shadow_file, 'wb') for entry in new_shadow: s_file.write(entry) finally: p_file.close() s_file.close()
./CrossVul/dataset_final_sorted/CWE-264/py/good_3697_2
crossvul-python_data_good_3633_4
"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2010 United States Government as represe(...TRUNCATED)
./CrossVul/dataset_final_sorted/CWE-264/py/good_3633_4
crossvul-python_data_good_3633_5
"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2010 United States Government as represe(...TRUNCATED)
./CrossVul/dataset_final_sorted/CWE-264/py/good_3633_5
crossvul-python_data_bad_3785_0
"# Copyright 2012 OpenStack LLC.\n# All Rights Reserved.\n#\n# Licensed under the Apache License,(...TRUNCATED)
./CrossVul/dataset_final_sorted/CWE-264/py/bad_3785_0
crossvul-python_data_good_3690_0
"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2012 OpenStack LLC\n#\n# Licensed under (...TRUNCATED)
./CrossVul/dataset_final_sorted/CWE-264/py/good_3690_0
crossvul-python_data_good_3633_3
"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2010 United States Government as represe(...TRUNCATED)
./CrossVul/dataset_final_sorted/CWE-264/py/good_3633_3
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4