Brad Bishop | 68caa1e | 2016-03-04 15:42:08 -0500 | [diff] [blame] | 1 | # Contributors Listed Below - COPYRIGHT 2016 |
| 2 | # [+] International Business Machines Corp. |
| 3 | # |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| 14 | # implied. See the License for the specific language governing |
| 15 | # permissions and limitations under the License. |
| 16 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 17 | import os |
Alexander Filippov | d08a456 | 2018-03-20 12:02:23 +0300 | [diff] [blame^] | 18 | import sys |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 19 | import dbus |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 20 | import dbus.exceptions |
| 21 | import json |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 22 | from xml.etree import ElementTree |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 23 | from bottle import Bottle, abort, request, response, JSONPlugin, HTTPError |
Jayanth Othayoth | 9bc9499 | 2017-06-29 06:30:40 -0500 | [diff] [blame] | 24 | from bottle import static_file |
Brad Bishop | b103d2d | 2016-03-04 16:19:14 -0500 | [diff] [blame] | 25 | import obmc.utils.misc |
Brad Bishop | b103d2d | 2016-03-04 16:19:14 -0500 | [diff] [blame] | 26 | from obmc.dbuslib.introspection import IntrospectionNodeParser |
| 27 | import obmc.mapper |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 28 | import spwd |
| 29 | import grp |
| 30 | import crypt |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 31 | import tempfile |
Leonel Gonzalez | 0bdef95 | 2017-04-18 08:17:49 -0500 | [diff] [blame] | 32 | import re |
Matt Spinler | d41643e | 2018-02-02 13:51:38 -0600 | [diff] [blame] | 33 | import mimetypes |
Deepak Kodihalli | 639b502 | 2017-10-13 06:40:26 -0500 | [diff] [blame] | 34 | have_wsock = True |
| 35 | try: |
| 36 | from geventwebsocket import WebSocketError |
| 37 | except ImportError: |
| 38 | have_wsock = False |
| 39 | if have_wsock: |
| 40 | from dbus.mainloop.glib import DBusGMainLoop |
| 41 | DBusGMainLoop(set_as_default=True) |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 42 | # TODO: openbmc/openbmc#2994 remove python 2 support |
| 43 | try: # python 2 |
| 44 | import gobject |
| 45 | except ImportError: # python 3 |
| 46 | from gi.repository import GObject as gobject |
Deepak Kodihalli | 639b502 | 2017-10-13 06:40:26 -0500 | [diff] [blame] | 47 | import gevent |
Deepak Kodihalli | 5c518f6 | 2018-04-23 03:26:38 -0500 | [diff] [blame] | 48 | from gevent import socket |
| 49 | from gevent import Greenlet |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 50 | |
Adriana Kobylak | f92cf4d | 2017-12-13 11:46:50 -0600 | [diff] [blame] | 51 | DBUS_UNKNOWN_INTERFACE = 'org.freedesktop.DBus.Error.UnknownInterface' |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 52 | DBUS_UNKNOWN_METHOD = 'org.freedesktop.DBus.Error.UnknownMethod' |
| 53 | DBUS_INVALID_ARGS = 'org.freedesktop.DBus.Error.InvalidArgs' |
Brad Bishop | d457892 | 2015-12-02 11:10:36 -0500 | [diff] [blame] | 54 | DBUS_TYPE_ERROR = 'org.freedesktop.DBus.Python.TypeError' |
Deepak Kodihalli | 6075bb4 | 2017-04-04 05:49:17 -0500 | [diff] [blame] | 55 | DELETE_IFACE = 'xyz.openbmc_project.Object.Delete' |
Adriana Kobylak | 5369389 | 2018-03-12 13:05:50 -0500 | [diff] [blame] | 56 | SOFTWARE_PATH = '/xyz/openbmc_project/software' |
Brad Bishop | 9ee57c4 | 2015-11-03 14:59:29 -0500 | [diff] [blame] | 57 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 58 | _4034_msg = "The specified %s cannot be %s: '%s'" |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 59 | |
Matt Spinler | d41643e | 2018-02-02 13:51:38 -0600 | [diff] [blame] | 60 | www_base_path = '/usr/share/www/' |
| 61 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 62 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 63 | def valid_user(session, *a, **kw): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 64 | ''' Authorization plugin callback that checks |
| 65 | that the user is logged in. ''' |
| 66 | if session is None: |
Brad Bishop | dc3fbfa | 2016-09-08 09:51:38 -0400 | [diff] [blame] | 67 | abort(401, 'Login required') |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 68 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 69 | |
Leonel Gonzalez | 0bdef95 | 2017-04-18 08:17:49 -0500 | [diff] [blame] | 70 | def get_type_signature_by_introspection(bus, service, object_path, |
| 71 | property_name): |
| 72 | obj = bus.get_object(service, object_path) |
| 73 | iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable') |
| 74 | xml_string = iface.Introspect() |
| 75 | for child in ElementTree.fromstring(xml_string): |
| 76 | # Iterate over each interfaces's properties to find |
| 77 | # matching property_name, and return its signature string |
| 78 | if child.tag == 'interface': |
| 79 | for i in child.iter(): |
| 80 | if ('name' in i.attrib) and \ |
| 81 | (i.attrib['name'] == property_name): |
| 82 | type_signature = i.attrib['type'] |
| 83 | return type_signature |
| 84 | |
| 85 | |
Ratan Gupta | a6a8a4c | 2017-08-07 08:18:44 +0530 | [diff] [blame] | 86 | def get_method_signature(bus, service, object_path, interface, method): |
| 87 | obj = bus.get_object(service, object_path) |
| 88 | iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable') |
| 89 | xml_string = iface.Introspect() |
| 90 | arglist = [] |
| 91 | |
| 92 | root = ElementTree.fromstring(xml_string) |
| 93 | for dbus_intf in root.findall('interface'): |
| 94 | if (dbus_intf.get('name') == interface): |
| 95 | for dbus_method in dbus_intf.findall('method'): |
| 96 | if(dbus_method.get('name') == method): |
| 97 | for arg in dbus_method.findall('arg'): |
| 98 | arglist.append(arg.get('type')) |
| 99 | return arglist |
| 100 | |
| 101 | |
Leonel Gonzalez | 0bdef95 | 2017-04-18 08:17:49 -0500 | [diff] [blame] | 102 | def split_struct_signature(signature): |
| 103 | struct_regex = r'(b|y|n|i|x|q|u|t|d|s|a\(.+?\)|\(.+?\))|a\{.+?\}+?' |
| 104 | struct_matches = re.findall(struct_regex, signature) |
| 105 | return struct_matches |
| 106 | |
| 107 | |
| 108 | def convert_type(signature, value): |
| 109 | # Basic Types |
| 110 | converted_value = None |
| 111 | converted_container = None |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 112 | # TODO: openbmc/openbmc#2994 remove python 2 support |
| 113 | try: # python 2 |
| 114 | basic_types = {'b': bool, 'y': dbus.Byte, 'n': dbus.Int16, 'i': int, |
| 115 | 'x': long, 'q': dbus.UInt16, 'u': dbus.UInt32, |
| 116 | 't': dbus.UInt64, 'd': float, 's': str} |
| 117 | except NameError: # python 3 |
| 118 | basic_types = {'b': bool, 'y': dbus.Byte, 'n': dbus.Int16, 'i': int, |
| 119 | 'x': int, 'q': dbus.UInt16, 'u': dbus.UInt32, |
| 120 | 't': dbus.UInt64, 'd': float, 's': str} |
Leonel Gonzalez | 0bdef95 | 2017-04-18 08:17:49 -0500 | [diff] [blame] | 121 | array_matches = re.match(r'a\((\S+)\)', signature) |
| 122 | struct_matches = re.match(r'\((\S+)\)', signature) |
| 123 | dictionary_matches = re.match(r'a{(\S+)}', signature) |
| 124 | if signature in basic_types: |
| 125 | converted_value = basic_types[signature](value) |
| 126 | return converted_value |
| 127 | # Array |
| 128 | if array_matches: |
| 129 | element_type = array_matches.group(1) |
| 130 | converted_container = list() |
| 131 | # Test if value is a list |
| 132 | # to avoid iterating over each character in a string. |
| 133 | # Iterate over each item and convert type |
| 134 | if isinstance(value, list): |
| 135 | for i in value: |
| 136 | converted_element = convert_type(element_type, i) |
| 137 | converted_container.append(converted_element) |
| 138 | # Convert non-sequence to expected type, and append to list |
| 139 | else: |
| 140 | converted_element = convert_type(element_type, value) |
| 141 | converted_container.append(converted_element) |
| 142 | return converted_container |
| 143 | # Struct |
| 144 | if struct_matches: |
| 145 | element_types = struct_matches.group(1) |
| 146 | split_element_types = split_struct_signature(element_types) |
| 147 | converted_container = list() |
| 148 | # Test if value is a list |
| 149 | if isinstance(value, list): |
| 150 | for index, val in enumerate(value): |
| 151 | converted_element = convert_type(split_element_types[index], |
| 152 | value[index]) |
| 153 | converted_container.append(converted_element) |
| 154 | else: |
| 155 | converted_element = convert_type(element_types, value) |
| 156 | converted_container.append(converted_element) |
| 157 | return tuple(converted_container) |
| 158 | # Dictionary |
| 159 | if dictionary_matches: |
| 160 | element_types = dictionary_matches.group(1) |
| 161 | split_element_types = split_struct_signature(element_types) |
| 162 | converted_container = dict() |
| 163 | # Convert each element of dict |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 164 | for key, val in value.items(): |
Leonel Gonzalez | 0bdef95 | 2017-04-18 08:17:49 -0500 | [diff] [blame] | 165 | converted_key = convert_type(split_element_types[0], key) |
| 166 | converted_val = convert_type(split_element_types[1], val) |
| 167 | converted_container[converted_key] = converted_val |
| 168 | return converted_container |
| 169 | |
| 170 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 171 | class UserInGroup: |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 172 | ''' Authorization plugin callback that checks that the user is logged in |
| 173 | and a member of a group. ''' |
| 174 | def __init__(self, group): |
| 175 | self.group = group |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 176 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 177 | def __call__(self, session, *a, **kw): |
| 178 | valid_user(session, *a, **kw) |
| 179 | res = False |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 180 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 181 | try: |
| 182 | res = session['user'] in grp.getgrnam(self.group)[3] |
| 183 | except KeyError: |
| 184 | pass |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 185 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 186 | if not res: |
| 187 | abort(403, 'Insufficient access') |
| 188 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 189 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 190 | class RouteHandler(object): |
Brad Bishop | 6d19060 | 2016-04-15 13:09:39 -0400 | [diff] [blame] | 191 | _require_auth = obmc.utils.misc.makelist(valid_user) |
Brad Bishop | d0c404a | 2017-02-21 09:23:25 -0500 | [diff] [blame] | 192 | _enable_cors = True |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 193 | |
Deepak Kodihalli | 83afbaf | 2017-04-10 06:37:19 -0500 | [diff] [blame] | 194 | def __init__(self, app, bus, verbs, rules, content_type=''): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 195 | self.app = app |
| 196 | self.bus = bus |
Brad Bishop | b103d2d | 2016-03-04 16:19:14 -0500 | [diff] [blame] | 197 | self.mapper = obmc.mapper.Mapper(bus) |
Brad Bishop | 6d19060 | 2016-04-15 13:09:39 -0400 | [diff] [blame] | 198 | self._verbs = obmc.utils.misc.makelist(verbs) |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 199 | self._rules = rules |
Deepak Kodihalli | 83afbaf | 2017-04-10 06:37:19 -0500 | [diff] [blame] | 200 | self._content_type = content_type |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 201 | |
Brad Bishop | 88c76a4 | 2017-02-21 00:02:02 -0500 | [diff] [blame] | 202 | if 'GET' in self._verbs: |
| 203 | self._verbs = list(set(self._verbs + ['HEAD'])) |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 204 | if 'OPTIONS' not in self._verbs: |
| 205 | self._verbs.append('OPTIONS') |
Brad Bishop | 88c76a4 | 2017-02-21 00:02:02 -0500 | [diff] [blame] | 206 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 207 | def _setup(self, **kw): |
| 208 | request.route_data = {} |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 209 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 210 | if request.method in self._verbs: |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 211 | if request.method != 'OPTIONS': |
| 212 | return self.setup(**kw) |
Brad Bishop | 88c76a4 | 2017-02-21 00:02:02 -0500 | [diff] [blame] | 213 | |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 214 | # Javascript implementations will not send credentials |
| 215 | # with an OPTIONS request. Don't help malicious clients |
| 216 | # by checking the path here and returning a 404 if the |
| 217 | # path doesn't exist. |
| 218 | return None |
Brad Bishop | 88c76a4 | 2017-02-21 00:02:02 -0500 | [diff] [blame] | 219 | |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 220 | # Return 405 |
Brad Bishop | 88c76a4 | 2017-02-21 00:02:02 -0500 | [diff] [blame] | 221 | raise HTTPError( |
| 222 | 405, "Method not allowed.", Allow=','.join(self._verbs)) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 223 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 224 | def __call__(self, **kw): |
| 225 | return getattr(self, 'do_' + request.method.lower())(**kw) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 226 | |
Brad Bishop | 88c76a4 | 2017-02-21 00:02:02 -0500 | [diff] [blame] | 227 | def do_head(self, **kw): |
| 228 | return self.do_get(**kw) |
| 229 | |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 230 | def do_options(self, **kw): |
| 231 | for v in self._verbs: |
| 232 | response.set_header( |
| 233 | 'Allow', |
| 234 | ','.join(self._verbs)) |
| 235 | return None |
| 236 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 237 | def install(self): |
| 238 | self.app.route( |
| 239 | self._rules, callback=self, |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 240 | method=['OPTIONS', 'GET', 'PUT', 'PATCH', 'POST', 'DELETE']) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 241 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 242 | @staticmethod |
| 243 | def try_mapper_call(f, callback=None, **kw): |
| 244 | try: |
| 245 | return f(**kw) |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 246 | except dbus.exceptions.DBusException as e: |
Brad Bishop | fce7756 | 2016-11-28 15:44:18 -0500 | [diff] [blame] | 247 | if e.get_dbus_name() == \ |
| 248 | 'org.freedesktop.DBus.Error.ObjectPathInUse': |
| 249 | abort(503, str(e)) |
Brad Bishop | b103d2d | 2016-03-04 16:19:14 -0500 | [diff] [blame] | 250 | if e.get_dbus_name() != obmc.mapper.MAPPER_NOT_FOUND: |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 251 | raise |
| 252 | if callback is None: |
| 253 | def callback(e, **kw): |
| 254 | abort(404, str(e)) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 255 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 256 | callback(e, **kw) |
| 257 | |
| 258 | @staticmethod |
| 259 | def try_properties_interface(f, *a): |
| 260 | try: |
| 261 | return f(*a) |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 262 | except dbus.exceptions.DBusException as e: |
Adriana Kobylak | f92cf4d | 2017-12-13 11:46:50 -0600 | [diff] [blame] | 263 | if DBUS_UNKNOWN_INTERFACE in e.get_dbus_name(): |
Brad Bishop | f4e7498 | 2016-04-01 14:53:05 -0400 | [diff] [blame] | 264 | # interface doesn't have any properties |
| 265 | return None |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 266 | if DBUS_UNKNOWN_METHOD == e.get_dbus_name(): |
| 267 | # properties interface not implemented at all |
| 268 | return None |
| 269 | raise |
| 270 | |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 271 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 272 | class DirectoryHandler(RouteHandler): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 273 | verbs = 'GET' |
| 274 | rules = '<path:path>/' |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 275 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 276 | def __init__(self, app, bus): |
| 277 | super(DirectoryHandler, self).__init__( |
Brad Bishop | c431e1a | 2017-07-10 16:44:51 -0400 | [diff] [blame] | 278 | app, bus, self.verbs, self.rules) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 279 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 280 | def find(self, path='/'): |
| 281 | return self.try_mapper_call( |
| 282 | self.mapper.get_subtree_paths, path=path, depth=1) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 283 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 284 | def setup(self, path='/'): |
| 285 | request.route_data['map'] = self.find(path) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 286 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 287 | def do_get(self, path='/'): |
| 288 | return request.route_data['map'] |
| 289 | |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 290 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 291 | class ListNamesHandler(RouteHandler): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 292 | verbs = 'GET' |
| 293 | rules = ['/list', '<path:path>/list'] |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 294 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 295 | def __init__(self, app, bus): |
| 296 | super(ListNamesHandler, self).__init__( |
Brad Bishop | c431e1a | 2017-07-10 16:44:51 -0400 | [diff] [blame] | 297 | app, bus, self.verbs, self.rules) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 298 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 299 | def find(self, path='/'): |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 300 | return list(self.try_mapper_call( |
| 301 | self.mapper.get_subtree, path=path).keys()) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 302 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 303 | def setup(self, path='/'): |
| 304 | request.route_data['map'] = self.find(path) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 305 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 306 | def do_get(self, path='/'): |
| 307 | return request.route_data['map'] |
| 308 | |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 309 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 310 | class ListHandler(RouteHandler): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 311 | verbs = 'GET' |
| 312 | rules = ['/enumerate', '<path:path>/enumerate'] |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 313 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 314 | def __init__(self, app, bus): |
| 315 | super(ListHandler, self).__init__( |
Brad Bishop | c431e1a | 2017-07-10 16:44:51 -0400 | [diff] [blame] | 316 | app, bus, self.verbs, self.rules) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 317 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 318 | def find(self, path='/'): |
| 319 | return self.try_mapper_call( |
| 320 | self.mapper.get_subtree, path=path) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 321 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 322 | def setup(self, path='/'): |
| 323 | request.route_data['map'] = self.find(path) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 324 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 325 | def do_get(self, path='/'): |
Brad Bishop | 71527b4 | 2016-04-01 14:51:14 -0400 | [diff] [blame] | 326 | return {x: y for x, y in self.mapper.enumerate_subtree( |
| 327 | path, |
| 328 | mapper_data=request.route_data['map']).dataitems()} |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 329 | |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 330 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 331 | class MethodHandler(RouteHandler): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 332 | verbs = 'POST' |
| 333 | rules = '<path:path>/action/<method>' |
| 334 | request_type = list |
Deepak Kodihalli | 83afbaf | 2017-04-10 06:37:19 -0500 | [diff] [blame] | 335 | content_type = 'application/json' |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 336 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 337 | def __init__(self, app, bus): |
| 338 | super(MethodHandler, self).__init__( |
Deepak Kodihalli | 83afbaf | 2017-04-10 06:37:19 -0500 | [diff] [blame] | 339 | app, bus, self.verbs, self.rules, self.content_type) |
Ratan Gupta | a6a8a4c | 2017-08-07 08:18:44 +0530 | [diff] [blame] | 340 | self.service = '' |
| 341 | self.interface = '' |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 342 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 343 | def find(self, path, method): |
Saqib Khan | 3a00b1f | 2017-11-04 15:56:21 -0500 | [diff] [blame] | 344 | method_list = [] |
Gunnar Mills | 313aadb | 2018-04-08 14:50:09 -0500 | [diff] [blame] | 345 | buses = self.try_mapper_call( |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 346 | self.mapper.get_object, path=path) |
Gunnar Mills | 313aadb | 2018-04-08 14:50:09 -0500 | [diff] [blame] | 347 | for items in buses.items(): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 348 | m = self.find_method_on_bus(path, method, *items) |
| 349 | if m: |
Saqib Khan | 3a00b1f | 2017-11-04 15:56:21 -0500 | [diff] [blame] | 350 | method_list.append(m) |
Nagaraju Goruganti | 765c2c8 | 2017-11-13 06:17:13 -0600 | [diff] [blame] | 351 | if method_list: |
| 352 | return method_list |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 353 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 354 | abort(404, _4034_msg % ('method', 'found', method)) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 355 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 356 | def setup(self, path, method): |
Saqib Khan | 3a00b1f | 2017-11-04 15:56:21 -0500 | [diff] [blame] | 357 | request.route_data['map'] = self.find(path, method) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 358 | |
Marri Devender Rao | bc0c673 | 2017-11-20 00:15:47 -0600 | [diff] [blame] | 359 | def do_post(self, path, method, retry=True): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 360 | try: |
Nagaraju Goruganti | 765c2c8 | 2017-11-13 06:17:13 -0600 | [diff] [blame] | 361 | args = [] |
| 362 | if request.parameter_list: |
| 363 | args = request.parameter_list |
| 364 | # To see if the return type is capable of being merged |
| 365 | if len(request.route_data['map']) > 1: |
| 366 | results = None |
| 367 | for item in request.route_data['map']: |
| 368 | tmp = item(*args) |
| 369 | if not results: |
| 370 | if tmp is not None: |
| 371 | results = type(tmp)() |
| 372 | if isinstance(results, dict): |
| 373 | results = results.update(tmp) |
| 374 | elif isinstance(results, list): |
| 375 | results = results + tmp |
| 376 | elif isinstance(results, type(None)): |
| 377 | results = None |
| 378 | else: |
| 379 | abort(501, 'Don\'t know how to merge method call ' |
| 380 | 'results of {}'.format(type(tmp))) |
| 381 | return results |
| 382 | # There is only one method |
| 383 | return request.route_data['map'][0](*args) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 384 | |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 385 | except dbus.exceptions.DBusException as e: |
Ratan Gupta | a6a8a4c | 2017-08-07 08:18:44 +0530 | [diff] [blame] | 386 | paramlist = [] |
Brad Bishop | b7fca9b | 2018-01-23 12:16:50 -0500 | [diff] [blame] | 387 | if e.get_dbus_name() == DBUS_INVALID_ARGS and retry: |
Ratan Gupta | a6a8a4c | 2017-08-07 08:18:44 +0530 | [diff] [blame] | 388 | |
| 389 | signature_list = get_method_signature(self.bus, self.service, |
| 390 | path, self.interface, |
| 391 | method) |
| 392 | if not signature_list: |
| 393 | abort(400, "Failed to get method signature: %s" % str(e)) |
| 394 | if len(signature_list) != len(request.parameter_list): |
| 395 | abort(400, "Invalid number of args") |
| 396 | converted_value = None |
| 397 | try: |
| 398 | for index, expected_type in enumerate(signature_list): |
| 399 | value = request.parameter_list[index] |
| 400 | converted_value = convert_type(expected_type, value) |
| 401 | paramlist.append(converted_value) |
| 402 | request.parameter_list = paramlist |
Marri Devender Rao | bc0c673 | 2017-11-20 00:15:47 -0600 | [diff] [blame] | 403 | self.do_post(path, method, False) |
Ratan Gupta | a6a8a4c | 2017-08-07 08:18:44 +0530 | [diff] [blame] | 404 | return |
| 405 | except Exception as ex: |
Nagaraju Goruganti | ab404fa | 2017-12-14 10:24:40 -0600 | [diff] [blame] | 406 | abort(400, "Bad Request/Invalid Args given") |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 407 | abort(400, str(e)) |
Ratan Gupta | a6a8a4c | 2017-08-07 08:18:44 +0530 | [diff] [blame] | 408 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 409 | if e.get_dbus_name() == DBUS_TYPE_ERROR: |
| 410 | abort(400, str(e)) |
| 411 | raise |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 412 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 413 | @staticmethod |
| 414 | def find_method_in_interface(method, obj, interface, methods): |
| 415 | if methods is None: |
| 416 | return None |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 417 | |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 418 | method = obmc.utils.misc.find_case_insensitive(method, list(methods.keys())) |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 419 | if method is not None: |
| 420 | iface = dbus.Interface(obj, interface) |
| 421 | return iface.get_dbus_method(method) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 422 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 423 | def find_method_on_bus(self, path, method, bus, interfaces): |
| 424 | obj = self.bus.get_object(bus, path, introspect=False) |
| 425 | iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE) |
| 426 | data = iface.Introspect() |
| 427 | parser = IntrospectionNodeParser( |
| 428 | ElementTree.fromstring(data), |
Brad Bishop | aeb995d | 2018-04-04 22:28:42 -0400 | [diff] [blame] | 429 | intf_match=lambda x: x in interfaces) |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 430 | for x, y in parser.get_interfaces().items(): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 431 | m = self.find_method_in_interface( |
| 432 | method, obj, x, y.get('method')) |
| 433 | if m: |
Ratan Gupta | a6a8a4c | 2017-08-07 08:18:44 +0530 | [diff] [blame] | 434 | self.service = bus |
| 435 | self.interface = x |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 436 | return m |
| 437 | |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 438 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 439 | class PropertyHandler(RouteHandler): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 440 | verbs = ['PUT', 'GET'] |
| 441 | rules = '<path:path>/attr/<prop>' |
Deepak Kodihalli | 83afbaf | 2017-04-10 06:37:19 -0500 | [diff] [blame] | 442 | content_type = 'application/json' |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 443 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 444 | def __init__(self, app, bus): |
| 445 | super(PropertyHandler, self).__init__( |
Deepak Kodihalli | 83afbaf | 2017-04-10 06:37:19 -0500 | [diff] [blame] | 446 | app, bus, self.verbs, self.rules, self.content_type) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 447 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 448 | def find(self, path, prop): |
| 449 | self.app.instance_handler.setup(path) |
| 450 | obj = self.app.instance_handler.do_get(path) |
Brad Bishop | 56ad87f | 2017-02-21 23:33:29 -0500 | [diff] [blame] | 451 | real_name = obmc.utils.misc.find_case_insensitive( |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 452 | prop, list(obj.keys())) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 453 | |
Brad Bishop | 56ad87f | 2017-02-21 23:33:29 -0500 | [diff] [blame] | 454 | if not real_name: |
| 455 | if request.method == 'PUT': |
| 456 | abort(403, _4034_msg % ('property', 'created', prop)) |
| 457 | else: |
| 458 | abort(404, _4034_msg % ('property', 'found', prop)) |
| 459 | return real_name, {path: obj} |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 460 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 461 | def setup(self, path, prop): |
Brad Bishop | 56ad87f | 2017-02-21 23:33:29 -0500 | [diff] [blame] | 462 | name, obj = self.find(path, prop) |
| 463 | request.route_data['obj'] = obj |
| 464 | request.route_data['name'] = name |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 465 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 466 | def do_get(self, path, prop): |
Brad Bishop | 56ad87f | 2017-02-21 23:33:29 -0500 | [diff] [blame] | 467 | name = request.route_data['name'] |
| 468 | return request.route_data['obj'][path][name] |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 469 | |
Marri Devender Rao | bc0c673 | 2017-11-20 00:15:47 -0600 | [diff] [blame] | 470 | def do_put(self, path, prop, value=None, retry=True): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 471 | if value is None: |
| 472 | value = request.parameter_list |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 473 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 474 | prop, iface, properties_iface = self.get_host_interface( |
| 475 | path, prop, request.route_data['map'][path]) |
| 476 | try: |
| 477 | properties_iface.Set(iface, prop, value) |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 478 | except ValueError as e: |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 479 | abort(400, str(e)) |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 480 | except dbus.exceptions.DBusException as e: |
Brad Bishop | b7fca9b | 2018-01-23 12:16:50 -0500 | [diff] [blame] | 481 | if e.get_dbus_name() == DBUS_INVALID_ARGS and retry: |
Leonel Gonzalez | 0bdef95 | 2017-04-18 08:17:49 -0500 | [diff] [blame] | 482 | bus_name = properties_iface.bus_name |
| 483 | expected_type = get_type_signature_by_introspection(self.bus, |
| 484 | bus_name, |
| 485 | path, |
| 486 | prop) |
| 487 | if not expected_type: |
| 488 | abort(403, "Failed to get expected type: %s" % str(e)) |
| 489 | converted_value = None |
| 490 | try: |
| 491 | converted_value = convert_type(expected_type, value) |
Marri Devender Rao | bc0c673 | 2017-11-20 00:15:47 -0600 | [diff] [blame] | 492 | self.do_put(path, prop, converted_value, False) |
Leonel Gonzalez | 0bdef95 | 2017-04-18 08:17:49 -0500 | [diff] [blame] | 493 | return |
| 494 | except Exception as ex: |
| 495 | abort(403, "Failed to convert %s to type %s" % |
| 496 | (value, expected_type)) |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 497 | abort(403, str(e)) |
| 498 | raise |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 499 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 500 | def get_host_interface(self, path, prop, bus_info): |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 501 | for bus, interfaces in bus_info.items(): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 502 | obj = self.bus.get_object(bus, path, introspect=True) |
| 503 | properties_iface = dbus.Interface( |
| 504 | obj, dbus_interface=dbus.PROPERTIES_IFACE) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 505 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 506 | info = self.get_host_interface_on_bus( |
| 507 | path, prop, properties_iface, bus, interfaces) |
| 508 | if info is not None: |
| 509 | prop, iface = info |
| 510 | return prop, iface, properties_iface |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 511 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 512 | def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces): |
| 513 | for i in interfaces: |
| 514 | properties = self.try_properties_interface(iface.GetAll, i) |
Brad Bishop | 69cb6d1 | 2017-02-21 12:01:52 -0500 | [diff] [blame] | 515 | if not properties: |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 516 | continue |
Leonel Gonzalez | 409f671 | 2017-05-24 09:51:55 -0500 | [diff] [blame] | 517 | match = obmc.utils.misc.find_case_insensitive( |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 518 | prop, list(properties.keys())) |
Leonel Gonzalez | 409f671 | 2017-05-24 09:51:55 -0500 | [diff] [blame] | 519 | if match is None: |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 520 | continue |
Leonel Gonzalez | 409f671 | 2017-05-24 09:51:55 -0500 | [diff] [blame] | 521 | prop = match |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 522 | return prop, i |
| 523 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 524 | |
Brad Bishop | 2503bd6 | 2015-12-16 17:56:12 -0500 | [diff] [blame] | 525 | class SchemaHandler(RouteHandler): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 526 | verbs = ['GET'] |
| 527 | rules = '<path:path>/schema' |
Brad Bishop | 2503bd6 | 2015-12-16 17:56:12 -0500 | [diff] [blame] | 528 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 529 | def __init__(self, app, bus): |
| 530 | super(SchemaHandler, self).__init__( |
Brad Bishop | 529029b | 2017-07-10 16:46:01 -0400 | [diff] [blame] | 531 | app, bus, self.verbs, self.rules) |
Brad Bishop | 2503bd6 | 2015-12-16 17:56:12 -0500 | [diff] [blame] | 532 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 533 | def find(self, path): |
| 534 | return self.try_mapper_call( |
| 535 | self.mapper.get_object, |
| 536 | path=path) |
Brad Bishop | 2503bd6 | 2015-12-16 17:56:12 -0500 | [diff] [blame] | 537 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 538 | def setup(self, path): |
| 539 | request.route_data['map'] = self.find(path) |
Brad Bishop | 2503bd6 | 2015-12-16 17:56:12 -0500 | [diff] [blame] | 540 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 541 | def do_get(self, path): |
| 542 | schema = {} |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 543 | for x in request.route_data['map'].keys(): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 544 | obj = self.bus.get_object(x, path, introspect=False) |
| 545 | iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE) |
| 546 | data = iface.Introspect() |
| 547 | parser = IntrospectionNodeParser( |
| 548 | ElementTree.fromstring(data)) |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 549 | for x, y in parser.get_interfaces().items(): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 550 | schema[x] = y |
Brad Bishop | 2503bd6 | 2015-12-16 17:56:12 -0500 | [diff] [blame] | 551 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 552 | return schema |
| 553 | |
Brad Bishop | 2503bd6 | 2015-12-16 17:56:12 -0500 | [diff] [blame] | 554 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 555 | class InstanceHandler(RouteHandler): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 556 | verbs = ['GET', 'PUT', 'DELETE'] |
| 557 | rules = '<path:path>' |
| 558 | request_type = dict |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 559 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 560 | def __init__(self, app, bus): |
| 561 | super(InstanceHandler, self).__init__( |
Brad Bishop | 529029b | 2017-07-10 16:46:01 -0400 | [diff] [blame] | 562 | app, bus, self.verbs, self.rules) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 563 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 564 | def find(self, path, callback=None): |
| 565 | return {path: self.try_mapper_call( |
| 566 | self.mapper.get_object, |
| 567 | callback, |
| 568 | path=path)} |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 569 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 570 | def setup(self, path): |
| 571 | callback = None |
| 572 | if request.method == 'PUT': |
| 573 | def callback(e, **kw): |
| 574 | abort(403, _4034_msg % ('resource', 'created', path)) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 575 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 576 | if request.route_data.get('map') is None: |
| 577 | request.route_data['map'] = self.find(path, callback) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 578 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 579 | def do_get(self, path): |
Brad Bishop | 71527b4 | 2016-04-01 14:51:14 -0400 | [diff] [blame] | 580 | return self.mapper.enumerate_object( |
| 581 | path, |
| 582 | mapper_data=request.route_data['map']) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 583 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 584 | def do_put(self, path): |
| 585 | # make sure all properties exist in the request |
| 586 | obj = set(self.do_get(path).keys()) |
| 587 | req = set(request.parameter_list.keys()) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 588 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 589 | diff = list(obj.difference(req)) |
| 590 | if diff: |
| 591 | abort(403, _4034_msg % ( |
| 592 | 'resource', 'removed', '%s/attr/%s' % (path, diff[0]))) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 593 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 594 | diff = list(req.difference(obj)) |
| 595 | if diff: |
| 596 | abort(403, _4034_msg % ( |
| 597 | 'resource', 'created', '%s/attr/%s' % (path, diff[0]))) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 598 | |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 599 | for p, v in request.parameter_list.items(): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 600 | self.app.property_handler.do_put( |
| 601 | path, p, v) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 602 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 603 | def do_delete(self, path): |
Matt Spinler | b1f6a2c | 2018-05-14 12:25:21 -0500 | [diff] [blame] | 604 | deleted = False |
| 605 | for bus, interfaces in request.route_data['map'][path].items(): |
| 606 | if self.bus_has_delete(interfaces): |
| 607 | self.delete_on_bus(path, bus) |
| 608 | deleted = True |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 609 | |
Matt Spinler | b1f6a2c | 2018-05-14 12:25:21 -0500 | [diff] [blame] | 610 | #It's OK if some objects didn't have a Delete, but not all |
| 611 | if not deleted: |
| 612 | abort(403, _4034_msg % ('resource', 'removed', path)) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 613 | |
Matt Spinler | b1f6a2c | 2018-05-14 12:25:21 -0500 | [diff] [blame] | 614 | def bus_has_delete(self, interfaces): |
| 615 | return DELETE_IFACE in interfaces |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 616 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 617 | def delete_on_bus(self, path, bus): |
| 618 | obj = self.bus.get_object(bus, path, introspect=False) |
| 619 | delete_iface = dbus.Interface( |
| 620 | obj, dbus_interface=DELETE_IFACE) |
| 621 | delete_iface.Delete() |
| 622 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 623 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 624 | class SessionHandler(MethodHandler): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 625 | ''' Handles the /login and /logout routes, manages |
| 626 | server side session store and session cookies. ''' |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 627 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 628 | rules = ['/login', '/logout'] |
| 629 | login_str = "User '%s' logged %s" |
| 630 | bad_passwd_str = "Invalid username or password" |
| 631 | no_user_str = "No user logged in" |
| 632 | bad_json_str = "Expecting request format { 'data': " \ |
| 633 | "[<username>, <password>] }, got '%s'" |
Alexander Filippov | d08a456 | 2018-03-20 12:02:23 +0300 | [diff] [blame^] | 634 | bmc_not_ready_str = "BMC is not ready (booting)" |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 635 | _require_auth = None |
| 636 | MAX_SESSIONS = 16 |
Alexander Filippov | d08a456 | 2018-03-20 12:02:23 +0300 | [diff] [blame^] | 637 | BMCSTATE_IFACE = 'xyz.openbmc_project.State.BMC' |
| 638 | BMCSTATE_PATH = '/xyz/openbmc_project/state/bmc0' |
| 639 | BMCSTATE_PROPERTY = 'CurrentBMCState' |
| 640 | BMCSTATE_READY = 'xyz.openbmc_project.State.BMC.BMCState.Ready' |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 641 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 642 | def __init__(self, app, bus): |
| 643 | super(SessionHandler, self).__init__( |
| 644 | app, bus) |
| 645 | self.hmac_key = os.urandom(128) |
| 646 | self.session_store = [] |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 647 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 648 | @staticmethod |
| 649 | def authenticate(username, clear): |
| 650 | try: |
| 651 | encoded = spwd.getspnam(username)[1] |
| 652 | return encoded == crypt.crypt(clear, encoded) |
| 653 | except KeyError: |
| 654 | return False |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 655 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 656 | def invalidate_session(self, session): |
| 657 | try: |
| 658 | self.session_store.remove(session) |
| 659 | except ValueError: |
| 660 | pass |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 661 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 662 | def new_session(self): |
| 663 | sid = os.urandom(32) |
| 664 | if self.MAX_SESSIONS <= len(self.session_store): |
| 665 | self.session_store.pop() |
| 666 | self.session_store.insert(0, {'sid': sid}) |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 667 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 668 | return self.session_store[0] |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 669 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 670 | def get_session(self, sid): |
| 671 | sids = [x['sid'] for x in self.session_store] |
| 672 | try: |
| 673 | return self.session_store[sids.index(sid)] |
| 674 | except ValueError: |
| 675 | return None |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 676 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 677 | def get_session_from_cookie(self): |
| 678 | return self.get_session( |
| 679 | request.get_cookie( |
| 680 | 'sid', secret=self.hmac_key)) |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 681 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 682 | def do_post(self, **kw): |
| 683 | if request.path == '/login': |
| 684 | return self.do_login(**kw) |
| 685 | else: |
| 686 | return self.do_logout(**kw) |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 687 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 688 | def do_logout(self, **kw): |
| 689 | session = self.get_session_from_cookie() |
| 690 | if session is not None: |
| 691 | user = session['user'] |
| 692 | self.invalidate_session(session) |
| 693 | response.delete_cookie('sid') |
| 694 | return self.login_str % (user, 'out') |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 695 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 696 | return self.no_user_str |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 697 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 698 | def do_login(self, **kw): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 699 | if len(request.parameter_list) != 2: |
| 700 | abort(400, self.bad_json_str % (request.json)) |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 701 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 702 | if not self.authenticate(*request.parameter_list): |
Brad Bishop | dc3fbfa | 2016-09-08 09:51:38 -0400 | [diff] [blame] | 703 | abort(401, self.bad_passwd_str) |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 704 | |
Alexander Filippov | d08a456 | 2018-03-20 12:02:23 +0300 | [diff] [blame^] | 705 | force = False |
| 706 | try: |
| 707 | force = request.json.get('force') |
| 708 | except (ValueError, AttributeError, KeyError, TypeError): |
| 709 | force = False |
| 710 | |
| 711 | if not force and not self.is_bmc_ready(): |
| 712 | abort(503, self.bmc_not_ready_str) |
| 713 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 714 | user = request.parameter_list[0] |
| 715 | session = self.new_session() |
| 716 | session['user'] = user |
| 717 | response.set_cookie( |
| 718 | 'sid', session['sid'], secret=self.hmac_key, |
| 719 | secure=True, |
| 720 | httponly=True) |
| 721 | return self.login_str % (user, 'in') |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 722 | |
Alexander Filippov | d08a456 | 2018-03-20 12:02:23 +0300 | [diff] [blame^] | 723 | def is_bmc_ready(self): |
| 724 | if not self.app.with_bmc_check: |
| 725 | return True |
| 726 | |
| 727 | try: |
| 728 | obj = self.bus.get_object(self.BMCSTATE_IFACE, self.BMCSTATE_PATH) |
| 729 | iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE) |
| 730 | state = iface.Get(self.BMCSTATE_IFACE, self.BMCSTATE_PROPERTY) |
| 731 | if state == self.BMCSTATE_READY: |
| 732 | return True |
| 733 | |
| 734 | except dbus.exceptions.DBusException: |
| 735 | pass |
| 736 | |
| 737 | return False |
| 738 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 739 | def find(self, **kw): |
| 740 | pass |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 741 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 742 | def setup(self, **kw): |
| 743 | pass |
| 744 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 745 | |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 746 | class ImageUploadUtils: |
| 747 | ''' Provides common utils for image upload. ''' |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 748 | |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 749 | file_loc = '/tmp/images' |
| 750 | file_prefix = 'img' |
| 751 | file_suffix = '' |
Adriana Kobylak | 5369389 | 2018-03-12 13:05:50 -0500 | [diff] [blame] | 752 | signal = None |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 753 | |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 754 | @classmethod |
| 755 | def do_upload(cls, filename=''): |
Adriana Kobylak | 5369389 | 2018-03-12 13:05:50 -0500 | [diff] [blame] | 756 | def cleanup(): |
| 757 | os.close(handle) |
| 758 | if cls.signal: |
| 759 | cls.signal.remove() |
| 760 | cls.signal = None |
| 761 | |
| 762 | def signal_callback(path, a, **kw): |
| 763 | # Just interested on the first Version interface created which is |
| 764 | # triggered when the file is uploaded. This helps avoid getting the |
| 765 | # wrong information for multiple upload requests in a row. |
| 766 | if "xyz.openbmc_project.Software.Version" in a and \ |
| 767 | "xyz.openbmc_project.Software.Activation" not in a: |
| 768 | paths.append(path) |
| 769 | |
| 770 | while cls.signal: |
| 771 | # Serialize uploads by waiting for the signal to be cleared. |
| 772 | # This makes it easier to ensure that the version information |
| 773 | # is the right one instead of the data from another upload request. |
| 774 | gevent.sleep(1) |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 775 | if not os.path.exists(cls.file_loc): |
Gunnar Mills | fb51579 | 2017-11-09 15:52:17 -0600 | [diff] [blame] | 776 | abort(500, "Error Directory not found") |
Adriana Kobylak | 5369389 | 2018-03-12 13:05:50 -0500 | [diff] [blame] | 777 | paths = [] |
| 778 | bus = dbus.SystemBus() |
| 779 | cls.signal = bus.add_signal_receiver( |
| 780 | signal_callback, |
| 781 | dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager', |
| 782 | signal_name='InterfacesAdded', |
| 783 | path=SOFTWARE_PATH) |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 784 | if not filename: |
| 785 | handle, filename = tempfile.mkstemp(cls.file_suffix, |
| 786 | cls.file_prefix, cls.file_loc) |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 787 | else: |
| 788 | filename = os.path.join(cls.file_loc, filename) |
Gunnar Mills | b66b18c | 2017-08-21 16:17:21 -0500 | [diff] [blame] | 789 | handle = os.open(filename, os.O_WRONLY | os.O_CREAT) |
Leonel Gonzalez | 0b62edf | 2017-06-08 15:10:03 -0500 | [diff] [blame] | 790 | try: |
| 791 | file_contents = request.body.read() |
| 792 | request.body.close() |
Gunnar Mills | b66b18c | 2017-08-21 16:17:21 -0500 | [diff] [blame] | 793 | os.write(handle, file_contents) |
Adriana Kobylak | 5369389 | 2018-03-12 13:05:50 -0500 | [diff] [blame] | 794 | # Close file after writing, the image manager process watches for |
| 795 | # the close event to know the upload is complete. |
Gunnar Mills | b66b18c | 2017-08-21 16:17:21 -0500 | [diff] [blame] | 796 | os.close(handle) |
Adriana Kobylak | 5369389 | 2018-03-12 13:05:50 -0500 | [diff] [blame] | 797 | except (IOError, ValueError) as e: |
| 798 | cleanup() |
| 799 | abort(400, str(e)) |
| 800 | except Exception: |
| 801 | cleanup() |
| 802 | abort(400, "Unexpected Error") |
| 803 | loop = gobject.MainLoop() |
| 804 | gcontext = loop.get_context() |
| 805 | count = 0 |
| 806 | version_id = '' |
| 807 | while loop is not None: |
| 808 | try: |
| 809 | if gcontext.pending(): |
| 810 | gcontext.iteration() |
| 811 | if not paths: |
| 812 | gevent.sleep(1) |
| 813 | else: |
| 814 | version_id = os.path.basename(paths.pop()) |
| 815 | break |
| 816 | count += 1 |
| 817 | if count == 10: |
| 818 | break |
| 819 | except Exception: |
| 820 | break |
| 821 | cls.signal.remove() |
| 822 | cls.signal = None |
Adriana Kobylak | 97fe435 | 2018-04-10 10:44:11 -0500 | [diff] [blame] | 823 | if version_id: |
| 824 | return version_id |
| 825 | else: |
| 826 | abort(400, "Version already exists or failed to be extracted") |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 827 | |
| 828 | |
| 829 | class ImagePostHandler(RouteHandler): |
| 830 | ''' Handles the /upload/image route. ''' |
| 831 | |
| 832 | verbs = ['POST'] |
| 833 | rules = ['/upload/image'] |
| 834 | content_type = 'application/octet-stream' |
| 835 | |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 836 | def __init__(self, app, bus): |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 837 | super(ImagePostHandler, self).__init__( |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 838 | app, bus, self.verbs, self.rules, self.content_type) |
| 839 | |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 840 | def do_post(self, filename=''): |
Adriana Kobylak | 5369389 | 2018-03-12 13:05:50 -0500 | [diff] [blame] | 841 | return ImageUploadUtils.do_upload() |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 842 | |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 843 | def find(self, **kw): |
| 844 | pass |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 845 | |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 846 | def setup(self, **kw): |
| 847 | pass |
| 848 | |
| 849 | |
Deepak Kodihalli | 639b502 | 2017-10-13 06:40:26 -0500 | [diff] [blame] | 850 | class EventNotifier: |
| 851 | keyNames = {} |
| 852 | keyNames['event'] = 'event' |
| 853 | keyNames['path'] = 'path' |
| 854 | keyNames['intfMap'] = 'interfaces' |
| 855 | keyNames['propMap'] = 'properties' |
| 856 | keyNames['intf'] = 'interface' |
| 857 | |
| 858 | def __init__(self, wsock, filters): |
| 859 | self.wsock = wsock |
| 860 | self.paths = filters.get("paths", []) |
| 861 | self.interfaces = filters.get("interfaces", []) |
| 862 | if not self.paths: |
| 863 | self.paths.append(None) |
| 864 | bus = dbus.SystemBus() |
| 865 | # Add a signal receiver for every path the client is interested in |
| 866 | for path in self.paths: |
| 867 | bus.add_signal_receiver( |
| 868 | self.interfaces_added_handler, |
| 869 | dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager', |
| 870 | signal_name='InterfacesAdded', |
| 871 | path=path) |
| 872 | bus.add_signal_receiver( |
| 873 | self.properties_changed_handler, |
| 874 | dbus_interface=dbus.PROPERTIES_IFACE, |
| 875 | signal_name='PropertiesChanged', |
| 876 | path=path, |
| 877 | path_keyword='path') |
| 878 | loop = gobject.MainLoop() |
| 879 | # gobject's mainloop.run() will block the entire process, so the gevent |
| 880 | # scheduler and hence greenlets won't execute. The while-loop below |
| 881 | # works around this limitation by using gevent's sleep, instead of |
| 882 | # calling loop.run() |
| 883 | gcontext = loop.get_context() |
| 884 | while loop is not None: |
| 885 | try: |
| 886 | if gcontext.pending(): |
| 887 | gcontext.iteration() |
| 888 | else: |
| 889 | # gevent.sleep puts only the current greenlet to sleep, |
| 890 | # not the entire process. |
| 891 | gevent.sleep(5) |
| 892 | except WebSocketError: |
| 893 | break |
| 894 | |
| 895 | def interfaces_added_handler(self, path, iprops, **kw): |
| 896 | ''' If the client is interested in these changes, respond to the |
| 897 | client. This handles d-bus interface additions.''' |
| 898 | if (not self.interfaces) or \ |
| 899 | (not set(iprops).isdisjoint(self.interfaces)): |
| 900 | response = {} |
| 901 | response[self.keyNames['event']] = "InterfacesAdded" |
| 902 | response[self.keyNames['path']] = path |
| 903 | response[self.keyNames['intfMap']] = iprops |
| 904 | try: |
| 905 | self.wsock.send(json.dumps(response)) |
| 906 | except WebSocketError: |
| 907 | return |
| 908 | |
| 909 | def properties_changed_handler(self, interface, new, old, **kw): |
| 910 | ''' If the client is interested in these changes, respond to the |
| 911 | client. This handles d-bus property changes. ''' |
| 912 | if (not self.interfaces) or (interface in self.interfaces): |
| 913 | path = str(kw['path']) |
| 914 | response = {} |
| 915 | response[self.keyNames['event']] = "PropertiesChanged" |
| 916 | response[self.keyNames['path']] = path |
| 917 | response[self.keyNames['intf']] = interface |
| 918 | response[self.keyNames['propMap']] = new |
| 919 | try: |
| 920 | self.wsock.send(json.dumps(response)) |
| 921 | except WebSocketError: |
| 922 | return |
| 923 | |
| 924 | |
Deepak Kodihalli | b209dd1 | 2017-10-11 01:19:17 -0500 | [diff] [blame] | 925 | class EventHandler(RouteHandler): |
| 926 | ''' Handles the /subscribe route, for clients to be able |
| 927 | to subscribe to BMC events. ''' |
| 928 | |
| 929 | verbs = ['GET'] |
| 930 | rules = ['/subscribe'] |
| 931 | |
| 932 | def __init__(self, app, bus): |
| 933 | super(EventHandler, self).__init__( |
| 934 | app, bus, self.verbs, self.rules) |
| 935 | |
| 936 | def find(self, **kw): |
| 937 | pass |
| 938 | |
| 939 | def setup(self, **kw): |
| 940 | pass |
| 941 | |
| 942 | def do_get(self): |
| 943 | wsock = request.environ.get('wsgi.websocket') |
| 944 | if not wsock: |
| 945 | abort(400, 'Expected WebSocket request.') |
Deepak Kodihalli | 639b502 | 2017-10-13 06:40:26 -0500 | [diff] [blame] | 946 | filters = wsock.receive() |
| 947 | filters = json.loads(filters) |
| 948 | notifier = EventNotifier(wsock, filters) |
Deepak Kodihalli | b209dd1 | 2017-10-11 01:19:17 -0500 | [diff] [blame] | 949 | |
| 950 | |
Deepak Kodihalli | 5c518f6 | 2018-04-23 03:26:38 -0500 | [diff] [blame] | 951 | class HostConsoleHandler(RouteHandler): |
| 952 | ''' Handles the /console route, for clients to be able |
| 953 | read/write the host serial console. The way this is |
| 954 | done is by exposing a websocket that's mirrored to an |
| 955 | abstract UNIX domain socket, which is the source for |
| 956 | the console data. ''' |
| 957 | |
| 958 | verbs = ['GET'] |
| 959 | # Naming the route console0, because the numbering will help |
| 960 | # on multi-bmc/multi-host systems. |
| 961 | rules = ['/console0'] |
| 962 | |
| 963 | def __init__(self, app, bus): |
| 964 | super(HostConsoleHandler, self).__init__( |
| 965 | app, bus, self.verbs, self.rules) |
| 966 | |
| 967 | def find(self, **kw): |
| 968 | pass |
| 969 | |
| 970 | def setup(self, **kw): |
| 971 | pass |
| 972 | |
| 973 | def read_wsock(self, wsock, sock): |
| 974 | while True: |
| 975 | try: |
| 976 | incoming = wsock.receive() |
| 977 | if incoming: |
| 978 | # Read websocket, write to UNIX socket |
| 979 | sock.send(incoming) |
| 980 | except Exception as e: |
| 981 | sock.close() |
| 982 | return |
| 983 | |
| 984 | def read_sock(self, sock, wsock): |
| 985 | max_sock_read_len = 4096 |
| 986 | while True: |
| 987 | try: |
| 988 | outgoing = sock.recv(max_sock_read_len) |
| 989 | if outgoing: |
| 990 | # Read UNIX socket, write to websocket |
| 991 | wsock.send(outgoing) |
| 992 | except Exception as e: |
| 993 | wsock.close() |
| 994 | return |
| 995 | |
| 996 | def send_ping(self, wsock) : |
| 997 | # Most webservers close websockets after 60 seconds of |
| 998 | # inactivity. Make sure to send a ping before that. |
| 999 | timeout = 45 |
| 1000 | payload = "ping" |
| 1001 | # the ping payload can be anything, the receiver has to just |
| 1002 | # return the same back. |
| 1003 | while True: |
| 1004 | gevent.sleep(timeout) |
| 1005 | wsock.send_frame(payload, wsock.OPCODE_PING) |
| 1006 | |
| 1007 | def do_get(self): |
| 1008 | wsock = request.environ.get('wsgi.websocket') |
| 1009 | if not wsock: |
| 1010 | abort(400, 'Expected WebSocket based request.') |
| 1011 | |
| 1012 | # A UNIX domain socket structure defines a 108-byte pathname. The |
| 1013 | # server in this case, obmc-console-server, expects a 108-byte path. |
| 1014 | socket_name = "\0obmc-console" |
| 1015 | trailing_bytes = "\0" * (108 - len(socket_name)) |
| 1016 | socket_path = socket_name + trailing_bytes |
| 1017 | sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 1018 | |
| 1019 | try: |
| 1020 | sock.connect(socket_path) |
| 1021 | except Exception as e: |
| 1022 | abort(500, str(e)) |
| 1023 | |
| 1024 | wsock_reader = Greenlet.spawn(self.read_wsock, wsock, sock) |
| 1025 | sock_reader = Greenlet.spawn(self.read_sock, sock, wsock) |
| 1026 | ping_sender = Greenlet.spawn(self.send_ping, wsock) |
| 1027 | gevent.joinall([wsock_reader, sock_reader, ping_sender]) |
| 1028 | |
| 1029 | |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 1030 | class ImagePutHandler(RouteHandler): |
| 1031 | ''' Handles the /upload/image/<filename> route. ''' |
| 1032 | |
| 1033 | verbs = ['PUT'] |
| 1034 | rules = ['/upload/image/<filename>'] |
| 1035 | content_type = 'application/octet-stream' |
| 1036 | |
| 1037 | def __init__(self, app, bus): |
| 1038 | super(ImagePutHandler, self).__init__( |
| 1039 | app, bus, self.verbs, self.rules, self.content_type) |
| 1040 | |
| 1041 | def do_put(self, filename=''): |
Adriana Kobylak | 5369389 | 2018-03-12 13:05:50 -0500 | [diff] [blame] | 1042 | return ImageUploadUtils.do_upload(filename) |
Deepak Kodihalli | 1af301a | 2017-04-11 07:29:01 -0500 | [diff] [blame] | 1043 | |
| 1044 | def find(self, **kw): |
| 1045 | pass |
| 1046 | |
| 1047 | def setup(self, **kw): |
| 1048 | pass |
| 1049 | |
| 1050 | |
Jayanth Othayoth | 9bc9499 | 2017-06-29 06:30:40 -0500 | [diff] [blame] | 1051 | class DownloadDumpHandler(RouteHandler): |
| 1052 | ''' Handles the /download/dump route. ''' |
| 1053 | |
| 1054 | verbs = 'GET' |
| 1055 | rules = ['/download/dump/<dumpid>'] |
| 1056 | content_type = 'application/octet-stream' |
Jayanth Othayoth | 18c3a24 | 2017-08-02 08:16:11 -0500 | [diff] [blame] | 1057 | dump_loc = '/var/lib/phosphor-debug-collector/dumps' |
Brad Bishop | 944cd04 | 2017-07-10 16:42:41 -0400 | [diff] [blame] | 1058 | suppress_json_resp = True |
Jayanth Othayoth | 9bc9499 | 2017-06-29 06:30:40 -0500 | [diff] [blame] | 1059 | |
| 1060 | def __init__(self, app, bus): |
| 1061 | super(DownloadDumpHandler, self).__init__( |
| 1062 | app, bus, self.verbs, self.rules, self.content_type) |
| 1063 | |
| 1064 | def do_get(self, dumpid): |
| 1065 | return self.do_download(dumpid) |
| 1066 | |
| 1067 | def find(self, **kw): |
| 1068 | pass |
| 1069 | |
| 1070 | def setup(self, **kw): |
| 1071 | pass |
| 1072 | |
| 1073 | def do_download(self, dumpid): |
| 1074 | dump_loc = os.path.join(self.dump_loc, dumpid) |
| 1075 | if not os.path.exists(dump_loc): |
| 1076 | abort(404, "Path not found") |
| 1077 | |
| 1078 | files = os.listdir(dump_loc) |
| 1079 | num_files = len(files) |
| 1080 | if num_files == 0: |
| 1081 | abort(404, "Dump not found") |
| 1082 | |
| 1083 | return static_file(os.path.basename(files[0]), root=dump_loc, |
| 1084 | download=True, mimetype=self.content_type) |
| 1085 | |
| 1086 | |
Matt Spinler | d41643e | 2018-02-02 13:51:38 -0600 | [diff] [blame] | 1087 | class WebHandler(RouteHandler): |
| 1088 | ''' Handles the routes for the web UI files. ''' |
| 1089 | |
| 1090 | verbs = 'GET' |
| 1091 | |
| 1092 | # Match only what we know are web files, so everything else |
| 1093 | # can get routed to the REST handlers. |
| 1094 | rules = ['//', '/<filename:re:.+\.js>', '/<filename:re:.+\.svg>', |
| 1095 | '/<filename:re:.+\.css>', '/<filename:re:.+\.ttf>', |
| 1096 | '/<filename:re:.+\.eot>', '/<filename:re:.+\.woff>', |
| 1097 | '/<filename:re:.+\.woff2>', '/<filename:re:.+\.map>', |
| 1098 | '/<filename:re:.+\.png>', '/<filename:re:.+\.html>', |
| 1099 | '/<filename:re:.+\.ico>'] |
| 1100 | |
| 1101 | # The mimetypes module knows about most types, but not these |
| 1102 | content_types = { |
| 1103 | '.eot': 'application/vnd.ms-fontobject', |
| 1104 | '.woff': 'application/x-font-woff', |
| 1105 | '.woff2': 'application/x-font-woff2', |
| 1106 | '.ttf': 'application/x-font-ttf', |
| 1107 | '.map': 'application/json' |
| 1108 | } |
| 1109 | |
| 1110 | _require_auth = None |
| 1111 | suppress_json_resp = True |
| 1112 | |
| 1113 | def __init__(self, app, bus): |
| 1114 | super(WebHandler, self).__init__( |
| 1115 | app, bus, self.verbs, self.rules) |
| 1116 | |
| 1117 | def get_type(self, filename): |
| 1118 | ''' Returns the content type and encoding for a file ''' |
| 1119 | |
| 1120 | content_type, encoding = mimetypes.guess_type(filename) |
| 1121 | |
| 1122 | # Try our own list if mimetypes didn't recognize it |
| 1123 | if content_type is None: |
| 1124 | if filename[-3:] == '.gz': |
| 1125 | filename = filename[:-3] |
| 1126 | extension = filename[filename.rfind('.'):] |
| 1127 | content_type = self.content_types.get(extension, None) |
| 1128 | |
| 1129 | return content_type, encoding |
| 1130 | |
| 1131 | def do_get(self, filename='index.html'): |
| 1132 | |
| 1133 | # If a gzipped version exists, use that instead. |
| 1134 | # Possible future enhancement: if the client doesn't |
| 1135 | # accept compressed files, unzip it ourselves before sending. |
| 1136 | if not os.path.exists(os.path.join(www_base_path, filename)): |
| 1137 | filename = filename + '.gz' |
| 1138 | |
| 1139 | # Though bottle should protect us, ensure path is valid |
| 1140 | realpath = os.path.realpath(filename) |
| 1141 | if realpath[0] == '/': |
| 1142 | realpath = realpath[1:] |
| 1143 | if not os.path.exists(os.path.join(www_base_path, realpath)): |
| 1144 | abort(404, "Path not found") |
| 1145 | |
| 1146 | mimetype, encoding = self.get_type(filename) |
| 1147 | |
| 1148 | # Couldn't find the type - let static_file() deal with it, |
| 1149 | # though this should never happen. |
| 1150 | if mimetype is None: |
| 1151 | print("Can't figure out content-type for %s" % filename) |
| 1152 | mimetype = 'auto' |
| 1153 | |
| 1154 | # This call will set several header fields for us, |
| 1155 | # including the charset if the type is text. |
| 1156 | response = static_file(filename, www_base_path, mimetype) |
| 1157 | |
| 1158 | # static_file() will only set the encoding if the |
| 1159 | # mimetype was auto, so set it here. |
| 1160 | if encoding is not None: |
| 1161 | response.set_header('Content-Encoding', encoding) |
| 1162 | |
| 1163 | return response |
| 1164 | |
| 1165 | def find(self, **kw): |
| 1166 | pass |
| 1167 | |
| 1168 | def setup(self, **kw): |
| 1169 | pass |
| 1170 | |
| 1171 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1172 | class AuthorizationPlugin(object): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1173 | ''' Invokes an optional list of authorization callbacks. ''' |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1174 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1175 | name = 'authorization' |
| 1176 | api = 2 |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1177 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1178 | class Compose: |
| 1179 | def __init__(self, validators, callback, session_mgr): |
| 1180 | self.validators = validators |
| 1181 | self.callback = callback |
| 1182 | self.session_mgr = session_mgr |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1183 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1184 | def __call__(self, *a, **kw): |
| 1185 | sid = request.get_cookie('sid', secret=self.session_mgr.hmac_key) |
| 1186 | session = self.session_mgr.get_session(sid) |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 1187 | if request.method != 'OPTIONS': |
| 1188 | for x in self.validators: |
| 1189 | x(session, *a, **kw) |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1190 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1191 | return self.callback(*a, **kw) |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1192 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1193 | def apply(self, callback, route): |
| 1194 | undecorated = route.get_undecorated_callback() |
| 1195 | if not isinstance(undecorated, RouteHandler): |
| 1196 | return callback |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1197 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1198 | auth_types = getattr( |
| 1199 | undecorated, '_require_auth', None) |
| 1200 | if not auth_types: |
| 1201 | return callback |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1202 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1203 | return self.Compose( |
| 1204 | auth_types, callback, undecorated.app.session_handler) |
| 1205 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 1206 | |
Brad Bishop | d0c404a | 2017-02-21 09:23:25 -0500 | [diff] [blame] | 1207 | class CorsPlugin(object): |
| 1208 | ''' Add CORS headers. ''' |
| 1209 | |
| 1210 | name = 'cors' |
| 1211 | api = 2 |
| 1212 | |
| 1213 | @staticmethod |
| 1214 | def process_origin(): |
| 1215 | origin = request.headers.get('Origin') |
| 1216 | if origin: |
| 1217 | response.add_header('Access-Control-Allow-Origin', origin) |
| 1218 | response.add_header( |
| 1219 | 'Access-Control-Allow-Credentials', 'true') |
| 1220 | |
| 1221 | @staticmethod |
| 1222 | def process_method_and_headers(verbs): |
| 1223 | method = request.headers.get('Access-Control-Request-Method') |
| 1224 | headers = request.headers.get('Access-Control-Request-Headers') |
| 1225 | if headers: |
| 1226 | headers = [x.lower() for x in headers.split(',')] |
| 1227 | |
| 1228 | if method in verbs \ |
| 1229 | and headers == ['content-type']: |
| 1230 | response.add_header('Access-Control-Allow-Methods', method) |
| 1231 | response.add_header( |
| 1232 | 'Access-Control-Allow-Headers', 'Content-Type') |
Ratan Gupta | 91b46f8 | 2018-01-14 12:52:23 +0530 | [diff] [blame] | 1233 | response.add_header('X-Frame-Options', 'deny') |
| 1234 | response.add_header('X-Content-Type-Options', 'nosniff') |
| 1235 | response.add_header('X-XSS-Protection', '1; mode=block') |
| 1236 | response.add_header( |
| 1237 | 'Content-Security-Policy', "default-src 'self'") |
| 1238 | response.add_header( |
| 1239 | 'Strict-Transport-Security', |
| 1240 | 'max-age=31536000; includeSubDomains; preload') |
Brad Bishop | d0c404a | 2017-02-21 09:23:25 -0500 | [diff] [blame] | 1241 | |
| 1242 | def __init__(self, app): |
| 1243 | app.install_error_callback(self.error_callback) |
| 1244 | |
| 1245 | def apply(self, callback, route): |
| 1246 | undecorated = route.get_undecorated_callback() |
| 1247 | if not isinstance(undecorated, RouteHandler): |
| 1248 | return callback |
| 1249 | |
| 1250 | if not getattr(undecorated, '_enable_cors', None): |
| 1251 | return callback |
| 1252 | |
| 1253 | def wrap(*a, **kw): |
| 1254 | self.process_origin() |
| 1255 | self.process_method_and_headers(undecorated._verbs) |
| 1256 | return callback(*a, **kw) |
| 1257 | |
| 1258 | return wrap |
| 1259 | |
| 1260 | def error_callback(self, **kw): |
| 1261 | self.process_origin() |
| 1262 | |
| 1263 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1264 | class JsonApiRequestPlugin(object): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1265 | ''' Ensures request content satisfies the OpenBMC json api format. ''' |
| 1266 | name = 'json_api_request' |
| 1267 | api = 2 |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1268 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1269 | error_str = "Expecting request format { 'data': <value> }, got '%s'" |
| 1270 | type_error_str = "Unsupported Content-Type: '%s'" |
| 1271 | json_type = "application/json" |
| 1272 | request_methods = ['PUT', 'POST', 'PATCH'] |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1273 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1274 | @staticmethod |
| 1275 | def content_expected(): |
| 1276 | return request.method in JsonApiRequestPlugin.request_methods |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1277 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1278 | def validate_request(self): |
| 1279 | if request.content_length > 0 and \ |
| 1280 | request.content_type != self.json_type: |
| 1281 | abort(415, self.type_error_str % request.content_type) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1282 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1283 | try: |
| 1284 | request.parameter_list = request.json.get('data') |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 1285 | except ValueError as e: |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1286 | abort(400, str(e)) |
| 1287 | except (AttributeError, KeyError, TypeError): |
| 1288 | abort(400, self.error_str % request.json) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1289 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1290 | def apply(self, callback, route): |
Deepak Kodihalli | fb6cd48 | 2017-04-10 07:27:09 -0500 | [diff] [blame] | 1291 | content_type = getattr( |
| 1292 | route.get_undecorated_callback(), '_content_type', None) |
| 1293 | if self.json_type != content_type: |
| 1294 | return callback |
| 1295 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1296 | verbs = getattr( |
| 1297 | route.get_undecorated_callback(), '_verbs', None) |
| 1298 | if verbs is None: |
| 1299 | return callback |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1300 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1301 | if not set(self.request_methods).intersection(verbs): |
| 1302 | return callback |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1303 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1304 | def wrap(*a, **kw): |
| 1305 | if self.content_expected(): |
| 1306 | self.validate_request() |
| 1307 | return callback(*a, **kw) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1308 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1309 | return wrap |
| 1310 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1311 | |
| 1312 | class JsonApiRequestTypePlugin(object): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1313 | ''' Ensures request content type satisfies the OpenBMC json api format. ''' |
| 1314 | name = 'json_api_method_request' |
| 1315 | api = 2 |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1316 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1317 | error_str = "Expecting request format { 'data': %s }, got '%s'" |
Deepak Kodihalli | fb6cd48 | 2017-04-10 07:27:09 -0500 | [diff] [blame] | 1318 | json_type = "application/json" |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1319 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1320 | def apply(self, callback, route): |
Deepak Kodihalli | fb6cd48 | 2017-04-10 07:27:09 -0500 | [diff] [blame] | 1321 | content_type = getattr( |
| 1322 | route.get_undecorated_callback(), '_content_type', None) |
| 1323 | if self.json_type != content_type: |
| 1324 | return callback |
| 1325 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1326 | request_type = getattr( |
| 1327 | route.get_undecorated_callback(), 'request_type', None) |
| 1328 | if request_type is None: |
| 1329 | return callback |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1330 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1331 | def validate_request(): |
| 1332 | if not isinstance(request.parameter_list, request_type): |
| 1333 | abort(400, self.error_str % (str(request_type), request.json)) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1334 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1335 | def wrap(*a, **kw): |
| 1336 | if JsonApiRequestPlugin.content_expected(): |
| 1337 | validate_request() |
| 1338 | return callback(*a, **kw) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1339 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1340 | return wrap |
| 1341 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1342 | |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1343 | class JsonErrorsPlugin(JSONPlugin): |
| 1344 | ''' Extend the Bottle JSONPlugin such that it also encodes error |
| 1345 | responses. ''' |
| 1346 | |
| 1347 | def __init__(self, app, **kw): |
| 1348 | super(JsonErrorsPlugin, self).__init__(**kw) |
| 1349 | self.json_opts = { |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 1350 | x: y for x, y in kw.items() |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1351 | if x in ['indent', 'sort_keys']} |
| 1352 | app.install_error_callback(self.error_callback) |
| 1353 | |
| 1354 | def error_callback(self, response_object, response_body, **kw): |
| 1355 | response_body['body'] = json.dumps(response_object, **self.json_opts) |
| 1356 | response.content_type = 'application/json' |
| 1357 | |
| 1358 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1359 | class JsonApiResponsePlugin(object): |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1360 | ''' Emits responses in the OpenBMC json api format. ''' |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1361 | name = 'json_api_response' |
| 1362 | api = 2 |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1363 | |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 1364 | @staticmethod |
| 1365 | def has_body(): |
| 1366 | return request.method not in ['OPTIONS'] |
| 1367 | |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1368 | def __init__(self, app): |
| 1369 | app.install_error_callback(self.error_callback) |
| 1370 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1371 | def apply(self, callback, route): |
Brad Bishop | 944cd04 | 2017-07-10 16:42:41 -0400 | [diff] [blame] | 1372 | skip = getattr( |
| 1373 | route.get_undecorated_callback(), 'suppress_json_resp', None) |
| 1374 | if skip: |
Jayanth Othayoth | 1444fd8 | 2017-06-29 05:45:07 -0500 | [diff] [blame] | 1375 | return callback |
| 1376 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1377 | def wrap(*a, **kw): |
Brad Bishop | d4c1c55 | 2017-02-21 00:07:28 -0500 | [diff] [blame] | 1378 | data = callback(*a, **kw) |
| 1379 | if self.has_body(): |
| 1380 | resp = {'data': data} |
| 1381 | resp['status'] = 'ok' |
| 1382 | resp['message'] = response.status_line |
| 1383 | return resp |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1384 | return wrap |
| 1385 | |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1386 | def error_callback(self, error, response_object, **kw): |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1387 | response_object['message'] = error.status_line |
Brad Bishop | 9c2531e | 2017-03-07 10:22:40 -0500 | [diff] [blame] | 1388 | response_object['status'] = 'error' |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1389 | response_object.setdefault('data', {})['description'] = str(error.body) |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1390 | if error.status_code == 500: |
| 1391 | response_object['data']['exception'] = repr(error.exception) |
| 1392 | response_object['data']['traceback'] = error.traceback.splitlines() |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1393 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1394 | |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1395 | class JsonpPlugin(object): |
Brad Bishop | 80fe37a | 2016-03-29 10:54:54 -0400 | [diff] [blame] | 1396 | ''' Json javascript wrapper. ''' |
| 1397 | name = 'jsonp' |
| 1398 | api = 2 |
| 1399 | |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1400 | def __init__(self, app, **kw): |
| 1401 | app.install_error_callback(self.error_callback) |
Brad Bishop | 80fe37a | 2016-03-29 10:54:54 -0400 | [diff] [blame] | 1402 | |
| 1403 | @staticmethod |
| 1404 | def to_jsonp(json): |
| 1405 | jwrapper = request.query.callback or None |
| 1406 | if(jwrapper): |
| 1407 | response.set_header('Content-Type', 'application/javascript') |
| 1408 | json = jwrapper + '(' + json + ');' |
| 1409 | return json |
| 1410 | |
| 1411 | def apply(self, callback, route): |
| 1412 | def wrap(*a, **kw): |
| 1413 | return self.to_jsonp(callback(*a, **kw)) |
| 1414 | return wrap |
| 1415 | |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1416 | def error_callback(self, response_body, **kw): |
| 1417 | response_body['body'] = self.to_jsonp(response_body['body']) |
Brad Bishop | 80fe37a | 2016-03-29 10:54:54 -0400 | [diff] [blame] | 1418 | |
| 1419 | |
Deepak Kodihalli | 461367a | 2017-04-10 07:11:38 -0500 | [diff] [blame] | 1420 | class ContentCheckerPlugin(object): |
| 1421 | ''' Ensures that a route is associated with the expected content-type |
| 1422 | header. ''' |
| 1423 | name = 'content_checker' |
| 1424 | api = 2 |
| 1425 | |
| 1426 | class Checker: |
| 1427 | def __init__(self, type, callback): |
| 1428 | self.expected_type = type |
| 1429 | self.callback = callback |
| 1430 | self.error_str = "Expecting content type '%s', got '%s'" |
| 1431 | |
| 1432 | def __call__(self, *a, **kw): |
Deepak Kodihalli | db1a21e | 2017-04-27 06:30:11 -0500 | [diff] [blame] | 1433 | if request.method in ['PUT', 'POST', 'PATCH'] and \ |
| 1434 | self.expected_type and \ |
Deepak Kodihalli | 461367a | 2017-04-10 07:11:38 -0500 | [diff] [blame] | 1435 | self.expected_type != request.content_type: |
| 1436 | abort(415, self.error_str % (self.expected_type, |
| 1437 | request.content_type)) |
| 1438 | |
| 1439 | return self.callback(*a, **kw) |
| 1440 | |
| 1441 | def apply(self, callback, route): |
| 1442 | content_type = getattr( |
| 1443 | route.get_undecorated_callback(), '_content_type', None) |
| 1444 | |
| 1445 | return self.Checker(content_type, callback) |
| 1446 | |
| 1447 | |
Brad Bishop | 2c6fc76 | 2016-08-29 15:53:25 -0400 | [diff] [blame] | 1448 | class App(Bottle): |
Deepak Kodihalli | 0fe213f | 2017-10-11 00:08:48 -0500 | [diff] [blame] | 1449 | def __init__(self, **kw): |
Brad Bishop | 2c6fc76 | 2016-08-29 15:53:25 -0400 | [diff] [blame] | 1450 | super(App, self).__init__(autojson=False) |
Deepak Kodihalli | b209dd1 | 2017-10-11 01:19:17 -0500 | [diff] [blame] | 1451 | |
| 1452 | self.have_wsock = kw.get('have_wsock', False) |
Alexander Filippov | d08a456 | 2018-03-20 12:02:23 +0300 | [diff] [blame^] | 1453 | self.with_bmc_check = '--with-bmc-check' in sys.argv |
Deepak Kodihalli | b209dd1 | 2017-10-11 01:19:17 -0500 | [diff] [blame] | 1454 | |
Brad Bishop | 2ddfa00 | 2016-08-29 15:11:55 -0400 | [diff] [blame] | 1455 | self.bus = dbus.SystemBus() |
| 1456 | self.mapper = obmc.mapper.Mapper(self.bus) |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1457 | self.error_callbacks = [] |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1458 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1459 | self.install_hooks() |
| 1460 | self.install_plugins() |
| 1461 | self.create_handlers() |
| 1462 | self.install_handlers() |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1463 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1464 | def install_plugins(self): |
| 1465 | # install json api plugins |
| 1466 | json_kw = {'indent': 2, 'sort_keys': True} |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1467 | self.install(AuthorizationPlugin()) |
Brad Bishop | d0c404a | 2017-02-21 09:23:25 -0500 | [diff] [blame] | 1468 | self.install(CorsPlugin(self)) |
Deepak Kodihalli | 461367a | 2017-04-10 07:11:38 -0500 | [diff] [blame] | 1469 | self.install(ContentCheckerPlugin()) |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1470 | self.install(JsonpPlugin(self, **json_kw)) |
| 1471 | self.install(JsonErrorsPlugin(self, **json_kw)) |
| 1472 | self.install(JsonApiResponsePlugin(self)) |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1473 | self.install(JsonApiRequestPlugin()) |
| 1474 | self.install(JsonApiRequestTypePlugin()) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1475 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1476 | def install_hooks(self): |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1477 | self.error_handler_type = type(self.default_error_handler) |
| 1478 | self.original_error_handler = self.default_error_handler |
| 1479 | self.default_error_handler = self.error_handler_type( |
| 1480 | self.custom_error_handler, self, Bottle) |
| 1481 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1482 | self.real_router_match = self.router.match |
| 1483 | self.router.match = self.custom_router_match |
| 1484 | self.add_hook('before_request', self.strip_extra_slashes) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1485 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1486 | def create_handlers(self): |
| 1487 | # create route handlers |
| 1488 | self.session_handler = SessionHandler(self, self.bus) |
Matt Spinler | d41643e | 2018-02-02 13:51:38 -0600 | [diff] [blame] | 1489 | self.web_handler = WebHandler(self, self.bus) |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1490 | self.directory_handler = DirectoryHandler(self, self.bus) |
| 1491 | self.list_names_handler = ListNamesHandler(self, self.bus) |
| 1492 | self.list_handler = ListHandler(self, self.bus) |
| 1493 | self.method_handler = MethodHandler(self, self.bus) |
| 1494 | self.property_handler = PropertyHandler(self, self.bus) |
| 1495 | self.schema_handler = SchemaHandler(self, self.bus) |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 1496 | self.image_upload_post_handler = ImagePostHandler(self, self.bus) |
| 1497 | self.image_upload_put_handler = ImagePutHandler(self, self.bus) |
Jayanth Othayoth | 9bc9499 | 2017-06-29 06:30:40 -0500 | [diff] [blame] | 1498 | self.download_dump_get_handler = DownloadDumpHandler(self, self.bus) |
Deepak Kodihalli | b209dd1 | 2017-10-11 01:19:17 -0500 | [diff] [blame] | 1499 | if self.have_wsock: |
| 1500 | self.event_handler = EventHandler(self, self.bus) |
Deepak Kodihalli | 5c518f6 | 2018-04-23 03:26:38 -0500 | [diff] [blame] | 1501 | self.host_console_handler = HostConsoleHandler(self, self.bus) |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1502 | self.instance_handler = InstanceHandler(self, self.bus) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1503 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1504 | def install_handlers(self): |
| 1505 | self.session_handler.install() |
Matt Spinler | d41643e | 2018-02-02 13:51:38 -0600 | [diff] [blame] | 1506 | self.web_handler.install() |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1507 | self.directory_handler.install() |
| 1508 | self.list_names_handler.install() |
| 1509 | self.list_handler.install() |
| 1510 | self.method_handler.install() |
| 1511 | self.property_handler.install() |
| 1512 | self.schema_handler.install() |
Deepak Kodihalli | 7ec0a4f | 2017-04-11 07:50:27 -0500 | [diff] [blame] | 1513 | self.image_upload_post_handler.install() |
| 1514 | self.image_upload_put_handler.install() |
Jayanth Othayoth | 9bc9499 | 2017-06-29 06:30:40 -0500 | [diff] [blame] | 1515 | self.download_dump_get_handler.install() |
Deepak Kodihalli | b209dd1 | 2017-10-11 01:19:17 -0500 | [diff] [blame] | 1516 | if self.have_wsock: |
| 1517 | self.event_handler.install() |
Deepak Kodihalli | 5c518f6 | 2018-04-23 03:26:38 -0500 | [diff] [blame] | 1518 | self.host_console_handler.install() |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1519 | # this has to come last, since it matches everything |
| 1520 | self.instance_handler.install() |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1521 | |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1522 | def install_error_callback(self, callback): |
| 1523 | self.error_callbacks.insert(0, callback) |
| 1524 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1525 | def custom_router_match(self, environ): |
| 1526 | ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is |
| 1527 | needed doesn't work for us since the instance rules match |
| 1528 | everything. This monkey-patch lets the route handler figure |
| 1529 | out which response is needed. This could be accomplished |
| 1530 | with a hook but that would require calling the router match |
| 1531 | function twice. |
| 1532 | ''' |
| 1533 | route, args = self.real_router_match(environ) |
| 1534 | if isinstance(route.callback, RouteHandler): |
| 1535 | route.callback._setup(**args) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1536 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1537 | return route, args |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 1538 | |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1539 | def custom_error_handler(self, res, error): |
Gunnar Mills | f01d0ba | 2017-10-25 20:37:24 -0500 | [diff] [blame] | 1540 | ''' Allow plugins to modify error responses too via this custom |
Brad Bishop | 080a48e | 2017-02-21 22:34:43 -0500 | [diff] [blame] | 1541 | error handler. ''' |
| 1542 | |
| 1543 | response_object = {} |
| 1544 | response_body = {} |
| 1545 | for x in self.error_callbacks: |
| 1546 | x(error=error, |
| 1547 | response_object=response_object, |
| 1548 | response_body=response_body) |
| 1549 | |
| 1550 | return response_body.get('body', "") |
| 1551 | |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1552 | @staticmethod |
| 1553 | def strip_extra_slashes(): |
| 1554 | path = request.environ['PATH_INFO'] |
| 1555 | trailing = ("", "/")[path[-1] == '/'] |
CamVan Nguyen | 249d132 | 2018-03-05 10:08:33 -0600 | [diff] [blame] | 1556 | parts = list(filter(bool, path.split('/'))) |
Brad Bishop | 87b63c1 | 2016-03-18 14:47:51 -0400 | [diff] [blame] | 1557 | request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing |