blob: 0893d0beba32c2784867aac054ae73c2945624ca [file] [log] [blame]
Brad Bishop68caa1e2016-03-04 15:42:08 -05001# 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 Bishopb1cbdaf2015-11-13 21:28:16 -050017import os
Alexander Filippovd08a4562018-03-20 12:02:23 +030018import sys
Brad Bishopaa65f6e2015-10-27 16:28:51 -040019import dbus
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050020import dbus.exceptions
21import json
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050022from xml.etree import ElementTree
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050023from bottle import Bottle, abort, request, response, JSONPlugin, HTTPError
Jayanth Othayoth9bc94992017-06-29 06:30:40 -050024from bottle import static_file
Brad Bishopb103d2d2016-03-04 16:19:14 -050025import obmc.utils.misc
Brad Bishopb103d2d2016-03-04 16:19:14 -050026from obmc.dbuslib.introspection import IntrospectionNodeParser
27import obmc.mapper
Brad Bishop2f428582015-12-02 10:56:11 -050028import spwd
29import grp
30import crypt
Deepak Kodihalli1af301a2017-04-11 07:29:01 -050031import tempfile
Leonel Gonzalez0bdef952017-04-18 08:17:49 -050032import re
Matt Spinlerd41643e2018-02-02 13:51:38 -060033import mimetypes
Deepak Kodihalli639b5022017-10-13 06:40:26 -050034have_wsock = True
35try:
36 from geventwebsocket import WebSocketError
37except ImportError:
38 have_wsock = False
39if have_wsock:
40 from dbus.mainloop.glib import DBusGMainLoop
41 DBusGMainLoop(set_as_default=True)
CamVan Nguyen249d1322018-03-05 10:08:33 -060042 # 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 Kodihalli639b5022017-10-13 06:40:26 -050047 import gevent
Deepak Kodihalli5c518f62018-04-23 03:26:38 -050048 from gevent import socket
49 from gevent import Greenlet
Brad Bishopaa65f6e2015-10-27 16:28:51 -040050
Adriana Kobylakf92cf4d2017-12-13 11:46:50 -060051DBUS_UNKNOWN_INTERFACE = 'org.freedesktop.DBus.Error.UnknownInterface'
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050052DBUS_UNKNOWN_METHOD = 'org.freedesktop.DBus.Error.UnknownMethod'
Adriana Kobylaka8b05d12018-08-23 10:44:07 -050053DBUS_PROPERTY_READONLY = 'org.freedesktop.DBus.Error.PropertyReadOnly'
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050054DBUS_INVALID_ARGS = 'org.freedesktop.DBus.Error.InvalidArgs'
Brad Bishopd4578922015-12-02 11:10:36 -050055DBUS_TYPE_ERROR = 'org.freedesktop.DBus.Python.TypeError'
Deepak Kodihalli6075bb42017-04-04 05:49:17 -050056DELETE_IFACE = 'xyz.openbmc_project.Object.Delete'
Adriana Kobylak53693892018-03-12 13:05:50 -050057SOFTWARE_PATH = '/xyz/openbmc_project/software'
Jayashankar Padathbec10c22018-05-29 18:22:59 +053058WEBSOCKET_TIMEOUT = 45
Brad Bishop9ee57c42015-11-03 14:59:29 -050059
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050060_4034_msg = "The specified %s cannot be %s: '%s'"
Brad Bishopaa65f6e2015-10-27 16:28:51 -040061
Matt Spinlerd41643e2018-02-02 13:51:38 -060062www_base_path = '/usr/share/www/'
63
Brad Bishop87b63c12016-03-18 14:47:51 -040064
Brad Bishop2f428582015-12-02 10:56:11 -050065def valid_user(session, *a, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -040066 ''' Authorization plugin callback that checks
67 that the user is logged in. '''
68 if session is None:
Brad Bishopdc3fbfa2016-09-08 09:51:38 -040069 abort(401, 'Login required')
Brad Bishop87b63c12016-03-18 14:47:51 -040070
Brad Bishop2f428582015-12-02 10:56:11 -050071
Leonel Gonzalez0bdef952017-04-18 08:17:49 -050072def get_type_signature_by_introspection(bus, service, object_path,
73 property_name):
74 obj = bus.get_object(service, object_path)
75 iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable')
76 xml_string = iface.Introspect()
77 for child in ElementTree.fromstring(xml_string):
78 # Iterate over each interfaces's properties to find
79 # matching property_name, and return its signature string
80 if child.tag == 'interface':
81 for i in child.iter():
82 if ('name' in i.attrib) and \
83 (i.attrib['name'] == property_name):
84 type_signature = i.attrib['type']
85 return type_signature
86
87
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +053088def get_method_signature(bus, service, object_path, interface, method):
89 obj = bus.get_object(service, object_path)
90 iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable')
91 xml_string = iface.Introspect()
92 arglist = []
93
94 root = ElementTree.fromstring(xml_string)
95 for dbus_intf in root.findall('interface'):
96 if (dbus_intf.get('name') == interface):
97 for dbus_method in dbus_intf.findall('method'):
98 if(dbus_method.get('name') == method):
99 for arg in dbus_method.findall('arg'):
100 arglist.append(arg.get('type'))
101 return arglist
102
103
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500104def split_struct_signature(signature):
105 struct_regex = r'(b|y|n|i|x|q|u|t|d|s|a\(.+?\)|\(.+?\))|a\{.+?\}+?'
106 struct_matches = re.findall(struct_regex, signature)
107 return struct_matches
108
109
110def convert_type(signature, value):
111 # Basic Types
112 converted_value = None
113 converted_container = None
CamVan Nguyen249d1322018-03-05 10:08:33 -0600114 # TODO: openbmc/openbmc#2994 remove python 2 support
115 try: # python 2
116 basic_types = {'b': bool, 'y': dbus.Byte, 'n': dbus.Int16, 'i': int,
117 'x': long, 'q': dbus.UInt16, 'u': dbus.UInt32,
118 't': dbus.UInt64, 'd': float, 's': str}
119 except NameError: # python 3
120 basic_types = {'b': bool, 'y': dbus.Byte, 'n': dbus.Int16, 'i': int,
121 'x': int, 'q': dbus.UInt16, 'u': dbus.UInt32,
122 't': dbus.UInt64, 'd': float, 's': str}
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500123 array_matches = re.match(r'a\((\S+)\)', signature)
124 struct_matches = re.match(r'\((\S+)\)', signature)
125 dictionary_matches = re.match(r'a{(\S+)}', signature)
126 if signature in basic_types:
127 converted_value = basic_types[signature](value)
128 return converted_value
129 # Array
130 if array_matches:
131 element_type = array_matches.group(1)
132 converted_container = list()
133 # Test if value is a list
134 # to avoid iterating over each character in a string.
135 # Iterate over each item and convert type
136 if isinstance(value, list):
137 for i in value:
138 converted_element = convert_type(element_type, i)
139 converted_container.append(converted_element)
140 # Convert non-sequence to expected type, and append to list
141 else:
142 converted_element = convert_type(element_type, value)
143 converted_container.append(converted_element)
144 return converted_container
145 # Struct
146 if struct_matches:
147 element_types = struct_matches.group(1)
148 split_element_types = split_struct_signature(element_types)
149 converted_container = list()
150 # Test if value is a list
151 if isinstance(value, list):
152 for index, val in enumerate(value):
153 converted_element = convert_type(split_element_types[index],
154 value[index])
155 converted_container.append(converted_element)
156 else:
157 converted_element = convert_type(element_types, value)
158 converted_container.append(converted_element)
159 return tuple(converted_container)
160 # Dictionary
161 if dictionary_matches:
162 element_types = dictionary_matches.group(1)
163 split_element_types = split_struct_signature(element_types)
164 converted_container = dict()
165 # Convert each element of dict
CamVan Nguyen249d1322018-03-05 10:08:33 -0600166 for key, val in value.items():
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500167 converted_key = convert_type(split_element_types[0], key)
168 converted_val = convert_type(split_element_types[1], val)
169 converted_container[converted_key] = converted_val
170 return converted_container
171
172
Jayashankar Padathbec10c22018-05-29 18:22:59 +0530173def send_ws_ping(wsock, timeout) :
174 # Most webservers close websockets after 60 seconds of
175 # inactivity. Make sure to send a ping before that.
176 payload = "ping"
177 # the ping payload can be anything, the receiver has to just
178 # return the same back.
179 while True:
180 gevent.sleep(timeout)
181 try:
182 if wsock:
183 wsock.send_frame(payload, wsock.OPCODE_PING)
184 except Exception as e:
185 wsock.close()
186 return
187
188
Brad Bishop2f428582015-12-02 10:56:11 -0500189class UserInGroup:
Brad Bishop87b63c12016-03-18 14:47:51 -0400190 ''' Authorization plugin callback that checks that the user is logged in
191 and a member of a group. '''
192 def __init__(self, group):
193 self.group = group
Brad Bishop2f428582015-12-02 10:56:11 -0500194
Brad Bishop87b63c12016-03-18 14:47:51 -0400195 def __call__(self, session, *a, **kw):
196 valid_user(session, *a, **kw)
197 res = False
Brad Bishop2f428582015-12-02 10:56:11 -0500198
Brad Bishop87b63c12016-03-18 14:47:51 -0400199 try:
200 res = session['user'] in grp.getgrnam(self.group)[3]
201 except KeyError:
202 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500203
Brad Bishop87b63c12016-03-18 14:47:51 -0400204 if not res:
205 abort(403, 'Insufficient access')
206
Brad Bishop2f428582015-12-02 10:56:11 -0500207
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500208class RouteHandler(object):
Brad Bishop6d190602016-04-15 13:09:39 -0400209 _require_auth = obmc.utils.misc.makelist(valid_user)
Brad Bishopd0c404a2017-02-21 09:23:25 -0500210 _enable_cors = True
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400211
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500212 def __init__(self, app, bus, verbs, rules, content_type=''):
Brad Bishop87b63c12016-03-18 14:47:51 -0400213 self.app = app
214 self.bus = bus
Brad Bishopb103d2d2016-03-04 16:19:14 -0500215 self.mapper = obmc.mapper.Mapper(bus)
Brad Bishop6d190602016-04-15 13:09:39 -0400216 self._verbs = obmc.utils.misc.makelist(verbs)
Brad Bishop87b63c12016-03-18 14:47:51 -0400217 self._rules = rules
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500218 self._content_type = content_type
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400219
Brad Bishop88c76a42017-02-21 00:02:02 -0500220 if 'GET' in self._verbs:
221 self._verbs = list(set(self._verbs + ['HEAD']))
Brad Bishopd4c1c552017-02-21 00:07:28 -0500222 if 'OPTIONS' not in self._verbs:
223 self._verbs.append('OPTIONS')
Brad Bishop88c76a42017-02-21 00:02:02 -0500224
Brad Bishop87b63c12016-03-18 14:47:51 -0400225 def _setup(self, **kw):
226 request.route_data = {}
Brad Bishopd4c1c552017-02-21 00:07:28 -0500227
Brad Bishop87b63c12016-03-18 14:47:51 -0400228 if request.method in self._verbs:
Brad Bishopd4c1c552017-02-21 00:07:28 -0500229 if request.method != 'OPTIONS':
230 return self.setup(**kw)
Brad Bishop88c76a42017-02-21 00:02:02 -0500231
Brad Bishopd4c1c552017-02-21 00:07:28 -0500232 # Javascript implementations will not send credentials
233 # with an OPTIONS request. Don't help malicious clients
234 # by checking the path here and returning a 404 if the
235 # path doesn't exist.
236 return None
Brad Bishop88c76a42017-02-21 00:02:02 -0500237
Brad Bishopd4c1c552017-02-21 00:07:28 -0500238 # Return 405
Brad Bishop88c76a42017-02-21 00:02:02 -0500239 raise HTTPError(
240 405, "Method not allowed.", Allow=','.join(self._verbs))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400241
Brad Bishop87b63c12016-03-18 14:47:51 -0400242 def __call__(self, **kw):
243 return getattr(self, 'do_' + request.method.lower())(**kw)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400244
Brad Bishop88c76a42017-02-21 00:02:02 -0500245 def do_head(self, **kw):
246 return self.do_get(**kw)
247
Brad Bishopd4c1c552017-02-21 00:07:28 -0500248 def do_options(self, **kw):
249 for v in self._verbs:
250 response.set_header(
251 'Allow',
252 ','.join(self._verbs))
253 return None
254
Brad Bishop87b63c12016-03-18 14:47:51 -0400255 def install(self):
256 self.app.route(
257 self._rules, callback=self,
Brad Bishopd4c1c552017-02-21 00:07:28 -0500258 method=['OPTIONS', 'GET', 'PUT', 'PATCH', 'POST', 'DELETE'])
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400259
Brad Bishop87b63c12016-03-18 14:47:51 -0400260 @staticmethod
261 def try_mapper_call(f, callback=None, **kw):
262 try:
263 return f(**kw)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600264 except dbus.exceptions.DBusException as e:
Brad Bishopfce77562016-11-28 15:44:18 -0500265 if e.get_dbus_name() == \
266 'org.freedesktop.DBus.Error.ObjectPathInUse':
267 abort(503, str(e))
Brad Bishopb103d2d2016-03-04 16:19:14 -0500268 if e.get_dbus_name() != obmc.mapper.MAPPER_NOT_FOUND:
Brad Bishop87b63c12016-03-18 14:47:51 -0400269 raise
270 if callback is None:
271 def callback(e, **kw):
272 abort(404, str(e))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400273
Brad Bishop87b63c12016-03-18 14:47:51 -0400274 callback(e, **kw)
275
276 @staticmethod
277 def try_properties_interface(f, *a):
278 try:
279 return f(*a)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600280 except dbus.exceptions.DBusException as e:
Adriana Kobylakf92cf4d2017-12-13 11:46:50 -0600281 if DBUS_UNKNOWN_INTERFACE in e.get_dbus_name():
Brad Bishopf4e74982016-04-01 14:53:05 -0400282 # interface doesn't have any properties
283 return None
Brad Bishop87b63c12016-03-18 14:47:51 -0400284 if DBUS_UNKNOWN_METHOD == e.get_dbus_name():
285 # properties interface not implemented at all
286 return None
287 raise
288
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400289
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500290class DirectoryHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400291 verbs = 'GET'
292 rules = '<path:path>/'
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -0500293 suppress_logging = True
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400294
Brad Bishop87b63c12016-03-18 14:47:51 -0400295 def __init__(self, app, bus):
296 super(DirectoryHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400297 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400298
Brad Bishop87b63c12016-03-18 14:47:51 -0400299 def find(self, path='/'):
300 return self.try_mapper_call(
301 self.mapper.get_subtree_paths, path=path, depth=1)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400302
Brad Bishop87b63c12016-03-18 14:47:51 -0400303 def setup(self, path='/'):
304 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400305
Brad Bishop87b63c12016-03-18 14:47:51 -0400306 def do_get(self, path='/'):
307 return request.route_data['map']
308
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400309
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500310class ListNamesHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400311 verbs = 'GET'
312 rules = ['/list', '<path:path>/list']
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -0500313 suppress_logging = True
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400314
Brad Bishop87b63c12016-03-18 14:47:51 -0400315 def __init__(self, app, bus):
316 super(ListNamesHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400317 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400318
Brad Bishop87b63c12016-03-18 14:47:51 -0400319 def find(self, path='/'):
CamVan Nguyen249d1322018-03-05 10:08:33 -0600320 return list(self.try_mapper_call(
321 self.mapper.get_subtree, path=path).keys())
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400322
Brad Bishop87b63c12016-03-18 14:47:51 -0400323 def setup(self, path='/'):
324 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400325
Brad Bishop87b63c12016-03-18 14:47:51 -0400326 def do_get(self, path='/'):
327 return request.route_data['map']
328
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400329
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500330class ListHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400331 verbs = 'GET'
332 rules = ['/enumerate', '<path:path>/enumerate']
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -0500333 suppress_logging = True
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400334
Brad Bishop87b63c12016-03-18 14:47:51 -0400335 def __init__(self, app, bus):
336 super(ListHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400337 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400338
Brad Bishop87b63c12016-03-18 14:47:51 -0400339 def find(self, path='/'):
340 return self.try_mapper_call(
341 self.mapper.get_subtree, path=path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400342
Brad Bishop87b63c12016-03-18 14:47:51 -0400343 def setup(self, path='/'):
344 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400345
Brad Bishop87b63c12016-03-18 14:47:51 -0400346 def do_get(self, path='/'):
Brad Bishop71527b42016-04-01 14:51:14 -0400347 return {x: y for x, y in self.mapper.enumerate_subtree(
348 path,
349 mapper_data=request.route_data['map']).dataitems()}
Brad Bishop87b63c12016-03-18 14:47:51 -0400350
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400351
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500352class MethodHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400353 verbs = 'POST'
354 rules = '<path:path>/action/<method>'
355 request_type = list
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500356 content_type = 'application/json'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400357
Brad Bishop87b63c12016-03-18 14:47:51 -0400358 def __init__(self, app, bus):
359 super(MethodHandler, self).__init__(
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500360 app, bus, self.verbs, self.rules, self.content_type)
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530361 self.service = ''
362 self.interface = ''
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400363
Brad Bishop87b63c12016-03-18 14:47:51 -0400364 def find(self, path, method):
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500365 method_list = []
Gunnar Mills313aadb2018-04-08 14:50:09 -0500366 buses = self.try_mapper_call(
Brad Bishop87b63c12016-03-18 14:47:51 -0400367 self.mapper.get_object, path=path)
Gunnar Mills313aadb2018-04-08 14:50:09 -0500368 for items in buses.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400369 m = self.find_method_on_bus(path, method, *items)
370 if m:
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500371 method_list.append(m)
Nagaraju Goruganti765c2c82017-11-13 06:17:13 -0600372 if method_list:
373 return method_list
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400374
Brad Bishop87b63c12016-03-18 14:47:51 -0400375 abort(404, _4034_msg % ('method', 'found', method))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400376
Brad Bishop87b63c12016-03-18 14:47:51 -0400377 def setup(self, path, method):
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500378 request.route_data['map'] = self.find(path, method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400379
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600380 def do_post(self, path, method, retry=True):
Brad Bishop87b63c12016-03-18 14:47:51 -0400381 try:
Nagaraju Goruganti765c2c82017-11-13 06:17:13 -0600382 args = []
383 if request.parameter_list:
384 args = request.parameter_list
385 # To see if the return type is capable of being merged
386 if len(request.route_data['map']) > 1:
387 results = None
388 for item in request.route_data['map']:
389 tmp = item(*args)
390 if not results:
391 if tmp is not None:
392 results = type(tmp)()
393 if isinstance(results, dict):
394 results = results.update(tmp)
395 elif isinstance(results, list):
396 results = results + tmp
397 elif isinstance(results, type(None)):
398 results = None
399 else:
400 abort(501, 'Don\'t know how to merge method call '
401 'results of {}'.format(type(tmp)))
402 return results
403 # There is only one method
404 return request.route_data['map'][0](*args)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400405
CamVan Nguyen249d1322018-03-05 10:08:33 -0600406 except dbus.exceptions.DBusException as e:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530407 paramlist = []
Brad Bishopb7fca9b2018-01-23 12:16:50 -0500408 if e.get_dbus_name() == DBUS_INVALID_ARGS and retry:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530409
410 signature_list = get_method_signature(self.bus, self.service,
411 path, self.interface,
412 method)
413 if not signature_list:
414 abort(400, "Failed to get method signature: %s" % str(e))
415 if len(signature_list) != len(request.parameter_list):
416 abort(400, "Invalid number of args")
417 converted_value = None
418 try:
419 for index, expected_type in enumerate(signature_list):
420 value = request.parameter_list[index]
421 converted_value = convert_type(expected_type, value)
422 paramlist.append(converted_value)
423 request.parameter_list = paramlist
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600424 self.do_post(path, method, False)
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530425 return
426 except Exception as ex:
Nagaraju Gorugantiab404fa2017-12-14 10:24:40 -0600427 abort(400, "Bad Request/Invalid Args given")
Brad Bishop87b63c12016-03-18 14:47:51 -0400428 abort(400, str(e))
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530429
Brad Bishop87b63c12016-03-18 14:47:51 -0400430 if e.get_dbus_name() == DBUS_TYPE_ERROR:
431 abort(400, str(e))
432 raise
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400433
Brad Bishop87b63c12016-03-18 14:47:51 -0400434 @staticmethod
435 def find_method_in_interface(method, obj, interface, methods):
436 if methods is None:
437 return None
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400438
CamVan Nguyen249d1322018-03-05 10:08:33 -0600439 method = obmc.utils.misc.find_case_insensitive(method, list(methods.keys()))
Brad Bishop87b63c12016-03-18 14:47:51 -0400440 if method is not None:
441 iface = dbus.Interface(obj, interface)
442 return iface.get_dbus_method(method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400443
Brad Bishop87b63c12016-03-18 14:47:51 -0400444 def find_method_on_bus(self, path, method, bus, interfaces):
445 obj = self.bus.get_object(bus, path, introspect=False)
446 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
447 data = iface.Introspect()
448 parser = IntrospectionNodeParser(
449 ElementTree.fromstring(data),
Brad Bishopaeb995d2018-04-04 22:28:42 -0400450 intf_match=lambda x: x in interfaces)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600451 for x, y in parser.get_interfaces().items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400452 m = self.find_method_in_interface(
453 method, obj, x, y.get('method'))
454 if m:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530455 self.service = bus
456 self.interface = x
Brad Bishop87b63c12016-03-18 14:47:51 -0400457 return m
458
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400459
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500460class PropertyHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400461 verbs = ['PUT', 'GET']
462 rules = '<path:path>/attr/<prop>'
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500463 content_type = 'application/json'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400464
Brad Bishop87b63c12016-03-18 14:47:51 -0400465 def __init__(self, app, bus):
466 super(PropertyHandler, self).__init__(
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500467 app, bus, self.verbs, self.rules, self.content_type)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400468
Brad Bishop87b63c12016-03-18 14:47:51 -0400469 def find(self, path, prop):
470 self.app.instance_handler.setup(path)
471 obj = self.app.instance_handler.do_get(path)
Brad Bishop56ad87f2017-02-21 23:33:29 -0500472 real_name = obmc.utils.misc.find_case_insensitive(
CamVan Nguyen249d1322018-03-05 10:08:33 -0600473 prop, list(obj.keys()))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400474
Brad Bishop56ad87f2017-02-21 23:33:29 -0500475 if not real_name:
476 if request.method == 'PUT':
477 abort(403, _4034_msg % ('property', 'created', prop))
478 else:
479 abort(404, _4034_msg % ('property', 'found', prop))
480 return real_name, {path: obj}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500481
Brad Bishop87b63c12016-03-18 14:47:51 -0400482 def setup(self, path, prop):
Brad Bishop56ad87f2017-02-21 23:33:29 -0500483 name, obj = self.find(path, prop)
484 request.route_data['obj'] = obj
485 request.route_data['name'] = name
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500486
Brad Bishop87b63c12016-03-18 14:47:51 -0400487 def do_get(self, path, prop):
Brad Bishop56ad87f2017-02-21 23:33:29 -0500488 name = request.route_data['name']
489 return request.route_data['obj'][path][name]
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500490
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600491 def do_put(self, path, prop, value=None, retry=True):
Brad Bishop87b63c12016-03-18 14:47:51 -0400492 if value is None:
493 value = request.parameter_list
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500494
Brad Bishop87b63c12016-03-18 14:47:51 -0400495 prop, iface, properties_iface = self.get_host_interface(
496 path, prop, request.route_data['map'][path])
497 try:
498 properties_iface.Set(iface, prop, value)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600499 except ValueError as e:
Brad Bishop87b63c12016-03-18 14:47:51 -0400500 abort(400, str(e))
CamVan Nguyen249d1322018-03-05 10:08:33 -0600501 except dbus.exceptions.DBusException as e:
Adriana Kobylaka8b05d12018-08-23 10:44:07 -0500502 if e.get_dbus_name() == DBUS_PROPERTY_READONLY:
503 abort(403, str(e))
Brad Bishopb7fca9b2018-01-23 12:16:50 -0500504 if e.get_dbus_name() == DBUS_INVALID_ARGS and retry:
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500505 bus_name = properties_iface.bus_name
506 expected_type = get_type_signature_by_introspection(self.bus,
507 bus_name,
508 path,
509 prop)
510 if not expected_type:
511 abort(403, "Failed to get expected type: %s" % str(e))
512 converted_value = None
513 try:
514 converted_value = convert_type(expected_type, value)
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500515 except Exception as ex:
516 abort(403, "Failed to convert %s to type %s" %
517 (value, expected_type))
Lei YU1eea5c32018-07-12 15:32:37 +0800518 try:
519 self.do_put(path, prop, converted_value, False)
520 return
521 except Exception as ex:
522 abort(403, str(ex))
523
Brad Bishop87b63c12016-03-18 14:47:51 -0400524 abort(403, str(e))
525 raise
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500526
Brad Bishop87b63c12016-03-18 14:47:51 -0400527 def get_host_interface(self, path, prop, bus_info):
CamVan Nguyen249d1322018-03-05 10:08:33 -0600528 for bus, interfaces in bus_info.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400529 obj = self.bus.get_object(bus, path, introspect=True)
530 properties_iface = dbus.Interface(
531 obj, dbus_interface=dbus.PROPERTIES_IFACE)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500532
Brad Bishop87b63c12016-03-18 14:47:51 -0400533 info = self.get_host_interface_on_bus(
534 path, prop, properties_iface, bus, interfaces)
535 if info is not None:
536 prop, iface = info
537 return prop, iface, properties_iface
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500538
Brad Bishop87b63c12016-03-18 14:47:51 -0400539 def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces):
540 for i in interfaces:
541 properties = self.try_properties_interface(iface.GetAll, i)
Brad Bishop69cb6d12017-02-21 12:01:52 -0500542 if not properties:
Brad Bishop87b63c12016-03-18 14:47:51 -0400543 continue
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500544 match = obmc.utils.misc.find_case_insensitive(
CamVan Nguyen249d1322018-03-05 10:08:33 -0600545 prop, list(properties.keys()))
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500546 if match is None:
Brad Bishop87b63c12016-03-18 14:47:51 -0400547 continue
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500548 prop = match
Brad Bishop87b63c12016-03-18 14:47:51 -0400549 return prop, i
550
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500551
Brad Bishop2503bd62015-12-16 17:56:12 -0500552class SchemaHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400553 verbs = ['GET']
554 rules = '<path:path>/schema'
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -0500555 suppress_logging = True
Brad Bishop2503bd62015-12-16 17:56:12 -0500556
Brad Bishop87b63c12016-03-18 14:47:51 -0400557 def __init__(self, app, bus):
558 super(SchemaHandler, self).__init__(
Brad Bishop529029b2017-07-10 16:46:01 -0400559 app, bus, self.verbs, self.rules)
Brad Bishop2503bd62015-12-16 17:56:12 -0500560
Brad Bishop87b63c12016-03-18 14:47:51 -0400561 def find(self, path):
562 return self.try_mapper_call(
563 self.mapper.get_object,
564 path=path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500565
Brad Bishop87b63c12016-03-18 14:47:51 -0400566 def setup(self, path):
567 request.route_data['map'] = self.find(path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500568
Brad Bishop87b63c12016-03-18 14:47:51 -0400569 def do_get(self, path):
570 schema = {}
CamVan Nguyen249d1322018-03-05 10:08:33 -0600571 for x in request.route_data['map'].keys():
Brad Bishop87b63c12016-03-18 14:47:51 -0400572 obj = self.bus.get_object(x, path, introspect=False)
573 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
574 data = iface.Introspect()
575 parser = IntrospectionNodeParser(
576 ElementTree.fromstring(data))
CamVan Nguyen249d1322018-03-05 10:08:33 -0600577 for x, y in parser.get_interfaces().items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400578 schema[x] = y
Brad Bishop2503bd62015-12-16 17:56:12 -0500579
Brad Bishop87b63c12016-03-18 14:47:51 -0400580 return schema
581
Brad Bishop2503bd62015-12-16 17:56:12 -0500582
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500583class InstanceHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400584 verbs = ['GET', 'PUT', 'DELETE']
585 rules = '<path:path>'
586 request_type = dict
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500587
Brad Bishop87b63c12016-03-18 14:47:51 -0400588 def __init__(self, app, bus):
589 super(InstanceHandler, self).__init__(
Brad Bishop529029b2017-07-10 16:46:01 -0400590 app, bus, self.verbs, self.rules)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500591
Brad Bishop87b63c12016-03-18 14:47:51 -0400592 def find(self, path, callback=None):
593 return {path: self.try_mapper_call(
594 self.mapper.get_object,
595 callback,
596 path=path)}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500597
Brad Bishop87b63c12016-03-18 14:47:51 -0400598 def setup(self, path):
599 callback = None
600 if request.method == 'PUT':
601 def callback(e, **kw):
602 abort(403, _4034_msg % ('resource', 'created', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500603
Brad Bishop87b63c12016-03-18 14:47:51 -0400604 if request.route_data.get('map') is None:
605 request.route_data['map'] = self.find(path, callback)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500606
Brad Bishop87b63c12016-03-18 14:47:51 -0400607 def do_get(self, path):
Brad Bishop71527b42016-04-01 14:51:14 -0400608 return self.mapper.enumerate_object(
609 path,
610 mapper_data=request.route_data['map'])
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500611
Brad Bishop87b63c12016-03-18 14:47:51 -0400612 def do_put(self, path):
613 # make sure all properties exist in the request
614 obj = set(self.do_get(path).keys())
615 req = set(request.parameter_list.keys())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500616
Brad Bishop87b63c12016-03-18 14:47:51 -0400617 diff = list(obj.difference(req))
618 if diff:
619 abort(403, _4034_msg % (
620 'resource', 'removed', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500621
Brad Bishop87b63c12016-03-18 14:47:51 -0400622 diff = list(req.difference(obj))
623 if diff:
624 abort(403, _4034_msg % (
625 'resource', 'created', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500626
CamVan Nguyen249d1322018-03-05 10:08:33 -0600627 for p, v in request.parameter_list.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400628 self.app.property_handler.do_put(
629 path, p, v)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500630
Brad Bishop87b63c12016-03-18 14:47:51 -0400631 def do_delete(self, path):
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500632 deleted = False
633 for bus, interfaces in request.route_data['map'][path].items():
634 if self.bus_has_delete(interfaces):
635 self.delete_on_bus(path, bus)
636 deleted = True
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500637
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500638 #It's OK if some objects didn't have a Delete, but not all
639 if not deleted:
640 abort(403, _4034_msg % ('resource', 'removed', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500641
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500642 def bus_has_delete(self, interfaces):
643 return DELETE_IFACE in interfaces
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500644
Brad Bishop87b63c12016-03-18 14:47:51 -0400645 def delete_on_bus(self, path, bus):
646 obj = self.bus.get_object(bus, path, introspect=False)
647 delete_iface = dbus.Interface(
648 obj, dbus_interface=DELETE_IFACE)
649 delete_iface.Delete()
650
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500651
Brad Bishop2f428582015-12-02 10:56:11 -0500652class SessionHandler(MethodHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400653 ''' Handles the /login and /logout routes, manages
654 server side session store and session cookies. '''
Brad Bishop2f428582015-12-02 10:56:11 -0500655
Brad Bishop87b63c12016-03-18 14:47:51 -0400656 rules = ['/login', '/logout']
657 login_str = "User '%s' logged %s"
658 bad_passwd_str = "Invalid username or password"
659 no_user_str = "No user logged in"
660 bad_json_str = "Expecting request format { 'data': " \
661 "[<username>, <password>] }, got '%s'"
Alexander Filippovd08a4562018-03-20 12:02:23 +0300662 bmc_not_ready_str = "BMC is not ready (booting)"
Brad Bishop87b63c12016-03-18 14:47:51 -0400663 _require_auth = None
664 MAX_SESSIONS = 16
Alexander Filippovd08a4562018-03-20 12:02:23 +0300665 BMCSTATE_IFACE = 'xyz.openbmc_project.State.BMC'
666 BMCSTATE_PATH = '/xyz/openbmc_project/state/bmc0'
667 BMCSTATE_PROPERTY = 'CurrentBMCState'
668 BMCSTATE_READY = 'xyz.openbmc_project.State.BMC.BMCState.Ready'
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -0500669 suppress_json_logging = True
Brad Bishop2f428582015-12-02 10:56:11 -0500670
Brad Bishop87b63c12016-03-18 14:47:51 -0400671 def __init__(self, app, bus):
672 super(SessionHandler, self).__init__(
673 app, bus)
674 self.hmac_key = os.urandom(128)
675 self.session_store = []
Brad Bishop2f428582015-12-02 10:56:11 -0500676
Brad Bishop87b63c12016-03-18 14:47:51 -0400677 @staticmethod
678 def authenticate(username, clear):
679 try:
680 encoded = spwd.getspnam(username)[1]
681 return encoded == crypt.crypt(clear, encoded)
682 except KeyError:
683 return False
Brad Bishop2f428582015-12-02 10:56:11 -0500684
Brad Bishop87b63c12016-03-18 14:47:51 -0400685 def invalidate_session(self, session):
686 try:
687 self.session_store.remove(session)
688 except ValueError:
689 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500690
Brad Bishop87b63c12016-03-18 14:47:51 -0400691 def new_session(self):
692 sid = os.urandom(32)
693 if self.MAX_SESSIONS <= len(self.session_store):
694 self.session_store.pop()
695 self.session_store.insert(0, {'sid': sid})
Brad Bishop2f428582015-12-02 10:56:11 -0500696
Brad Bishop87b63c12016-03-18 14:47:51 -0400697 return self.session_store[0]
Brad Bishop2f428582015-12-02 10:56:11 -0500698
Brad Bishop87b63c12016-03-18 14:47:51 -0400699 def get_session(self, sid):
700 sids = [x['sid'] for x in self.session_store]
701 try:
702 return self.session_store[sids.index(sid)]
703 except ValueError:
704 return None
Brad Bishop2f428582015-12-02 10:56:11 -0500705
Brad Bishop87b63c12016-03-18 14:47:51 -0400706 def get_session_from_cookie(self):
707 return self.get_session(
708 request.get_cookie(
709 'sid', secret=self.hmac_key))
Brad Bishop2f428582015-12-02 10:56:11 -0500710
Brad Bishop87b63c12016-03-18 14:47:51 -0400711 def do_post(self, **kw):
712 if request.path == '/login':
713 return self.do_login(**kw)
714 else:
715 return self.do_logout(**kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500716
Brad Bishop87b63c12016-03-18 14:47:51 -0400717 def do_logout(self, **kw):
718 session = self.get_session_from_cookie()
719 if session is not None:
720 user = session['user']
721 self.invalidate_session(session)
722 response.delete_cookie('sid')
723 return self.login_str % (user, 'out')
Brad Bishop2f428582015-12-02 10:56:11 -0500724
Brad Bishop87b63c12016-03-18 14:47:51 -0400725 return self.no_user_str
Brad Bishop2f428582015-12-02 10:56:11 -0500726
Brad Bishop87b63c12016-03-18 14:47:51 -0400727 def do_login(self, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -0400728 if len(request.parameter_list) != 2:
729 abort(400, self.bad_json_str % (request.json))
Brad Bishop2f428582015-12-02 10:56:11 -0500730
Brad Bishop87b63c12016-03-18 14:47:51 -0400731 if not self.authenticate(*request.parameter_list):
Brad Bishopdc3fbfa2016-09-08 09:51:38 -0400732 abort(401, self.bad_passwd_str)
Brad Bishop2f428582015-12-02 10:56:11 -0500733
Alexander Filippovd08a4562018-03-20 12:02:23 +0300734 force = False
735 try:
736 force = request.json.get('force')
737 except (ValueError, AttributeError, KeyError, TypeError):
738 force = False
739
740 if not force and not self.is_bmc_ready():
741 abort(503, self.bmc_not_ready_str)
742
Brad Bishop87b63c12016-03-18 14:47:51 -0400743 user = request.parameter_list[0]
744 session = self.new_session()
745 session['user'] = user
746 response.set_cookie(
747 'sid', session['sid'], secret=self.hmac_key,
748 secure=True,
749 httponly=True)
750 return self.login_str % (user, 'in')
Brad Bishop2f428582015-12-02 10:56:11 -0500751
Alexander Filippovd08a4562018-03-20 12:02:23 +0300752 def is_bmc_ready(self):
753 if not self.app.with_bmc_check:
754 return True
755
756 try:
757 obj = self.bus.get_object(self.BMCSTATE_IFACE, self.BMCSTATE_PATH)
758 iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE)
759 state = iface.Get(self.BMCSTATE_IFACE, self.BMCSTATE_PROPERTY)
760 if state == self.BMCSTATE_READY:
761 return True
762
763 except dbus.exceptions.DBusException:
764 pass
765
766 return False
767
Brad Bishop87b63c12016-03-18 14:47:51 -0400768 def find(self, **kw):
769 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500770
Brad Bishop87b63c12016-03-18 14:47:51 -0400771 def setup(self, **kw):
772 pass
773
Brad Bishop2f428582015-12-02 10:56:11 -0500774
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500775class ImageUploadUtils:
776 ''' Provides common utils for image upload. '''
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500777
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500778 file_loc = '/tmp/images'
779 file_prefix = 'img'
780 file_suffix = ''
Adriana Kobylak53693892018-03-12 13:05:50 -0500781 signal = None
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500782
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500783 @classmethod
784 def do_upload(cls, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -0500785 def cleanup():
786 os.close(handle)
787 if cls.signal:
788 cls.signal.remove()
789 cls.signal = None
790
791 def signal_callback(path, a, **kw):
792 # Just interested on the first Version interface created which is
793 # triggered when the file is uploaded. This helps avoid getting the
794 # wrong information for multiple upload requests in a row.
795 if "xyz.openbmc_project.Software.Version" in a and \
796 "xyz.openbmc_project.Software.Activation" not in a:
797 paths.append(path)
798
799 while cls.signal:
800 # Serialize uploads by waiting for the signal to be cleared.
801 # This makes it easier to ensure that the version information
802 # is the right one instead of the data from another upload request.
803 gevent.sleep(1)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500804 if not os.path.exists(cls.file_loc):
Gunnar Millsfb515792017-11-09 15:52:17 -0600805 abort(500, "Error Directory not found")
Adriana Kobylak53693892018-03-12 13:05:50 -0500806 paths = []
807 bus = dbus.SystemBus()
808 cls.signal = bus.add_signal_receiver(
809 signal_callback,
810 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
811 signal_name='InterfacesAdded',
812 path=SOFTWARE_PATH)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500813 if not filename:
814 handle, filename = tempfile.mkstemp(cls.file_suffix,
815 cls.file_prefix, cls.file_loc)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500816 else:
817 filename = os.path.join(cls.file_loc, filename)
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500818 handle = os.open(filename, os.O_WRONLY | os.O_CREAT)
Leonel Gonzalez0b62edf2017-06-08 15:10:03 -0500819 try:
820 file_contents = request.body.read()
821 request.body.close()
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500822 os.write(handle, file_contents)
Adriana Kobylak53693892018-03-12 13:05:50 -0500823 # Close file after writing, the image manager process watches for
824 # the close event to know the upload is complete.
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500825 os.close(handle)
Adriana Kobylak53693892018-03-12 13:05:50 -0500826 except (IOError, ValueError) as e:
827 cleanup()
828 abort(400, str(e))
829 except Exception:
830 cleanup()
831 abort(400, "Unexpected Error")
832 loop = gobject.MainLoop()
833 gcontext = loop.get_context()
834 count = 0
835 version_id = ''
836 while loop is not None:
837 try:
838 if gcontext.pending():
839 gcontext.iteration()
840 if not paths:
841 gevent.sleep(1)
842 else:
843 version_id = os.path.basename(paths.pop())
844 break
845 count += 1
846 if count == 10:
847 break
848 except Exception:
849 break
850 cls.signal.remove()
851 cls.signal = None
Adriana Kobylak97fe4352018-04-10 10:44:11 -0500852 if version_id:
853 return version_id
854 else:
855 abort(400, "Version already exists or failed to be extracted")
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500856
857
858class ImagePostHandler(RouteHandler):
859 ''' Handles the /upload/image route. '''
860
861 verbs = ['POST']
862 rules = ['/upload/image']
863 content_type = 'application/octet-stream'
864
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500865 def __init__(self, app, bus):
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500866 super(ImagePostHandler, self).__init__(
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500867 app, bus, self.verbs, self.rules, self.content_type)
868
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500869 def do_post(self, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -0500870 return ImageUploadUtils.do_upload()
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500871
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500872 def find(self, **kw):
873 pass
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500874
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500875 def setup(self, **kw):
876 pass
877
878
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500879class CertificateHandler:
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500880 file_suffix = '.pem'
881 file_prefix = 'cert_'
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500882 CERT_PATH = '/xyz/openbmc_project/certs'
883 CERT_IFACE = 'xyz.openbmc_project.Certs.Install'
884
Deepak Kodihallia324acd2018-09-30 06:57:57 -0500885 def __init__(self, route_handler, cert_type, service):
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500886 if not service:
887 abort(500, "Missing service")
888 if not cert_type:
889 abort(500, "Missing certificate type")
Deepak Kodihallia324acd2018-09-30 06:57:57 -0500890 bus = dbus.SystemBus()
891 certPath = self.CERT_PATH + "/" + cert_type + "/" + service
892 intfs = route_handler.try_mapper_call(
893 route_handler.mapper.get_object, path=certPath)
894 for busName,intf in intfs.items():
895 if self.CERT_IFACE in intf:
896 self.obj = bus.get_object(busName, certPath)
897 return
898 abort(404, "Path not found")
899
900 def do_upload(self):
901 def cleanup():
902 if os.path.exists(temp.name):
903 os.remove(temp.name)
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500904
905 with tempfile.NamedTemporaryFile(
Deepak Kodihallia324acd2018-09-30 06:57:57 -0500906 suffix=self.file_suffix,
907 prefix=self.file_prefix,
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500908 delete=False) as temp:
909 try:
910 file_contents = request.body.read()
911 request.body.close()
912 temp.write(file_contents)
913 except (IOError, ValueError) as e:
914 cleanup()
915 abort(500, str(e))
916 except Exception:
917 cleanup()
918 abort(500, "Unexpected Error")
919
920 try:
Deepak Kodihallia324acd2018-09-30 06:57:57 -0500921 iface = dbus.Interface(self.obj, self.CERT_IFACE)
922 iface.Install(temp.name)
Deepak Kodihallic043cdd2018-10-02 06:27:57 -0500923 except Exception as e:
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500924 cleanup()
Deepak Kodihalli844bb4e2018-10-03 04:59:26 -0500925 abort(400, str(e))
Deepak Kodihallia324acd2018-09-30 06:57:57 -0500926 cleanup()
927
928 def do_delete(self):
929 delete_iface = dbus.Interface(
930 self.obj, dbus_interface=DELETE_IFACE)
931 delete_iface.Delete()
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500932
933
934class CertificatePutHandler(RouteHandler):
935 ''' Handles the /xyz/openbmc_project/certs/<cert_type>/<service> route. '''
936
Deepak Kodihallia324acd2018-09-30 06:57:57 -0500937 verbs = ['PUT', 'DELETE']
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500938 rules = ['/xyz/openbmc_project/certs/<cert_type>/<service>']
939 content_type = 'application/octet-stream'
940
941 def __init__(self, app, bus):
942 super(CertificatePutHandler, self).__init__(
943 app, bus, self.verbs, self.rules, self.content_type)
944
945 def do_put(self, cert_type, service):
Deepak Kodihallia324acd2018-09-30 06:57:57 -0500946 return CertificateHandler(self, cert_type, service).do_upload()
947
948 def do_delete(self, cert_type, service):
949 return CertificateHandler(self, cert_type, service).do_delete()
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -0500950
951 def find(self, **kw):
952 pass
953
954 def setup(self, **kw):
955 pass
956
957
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500958class EventNotifier:
959 keyNames = {}
960 keyNames['event'] = 'event'
961 keyNames['path'] = 'path'
962 keyNames['intfMap'] = 'interfaces'
963 keyNames['propMap'] = 'properties'
964 keyNames['intf'] = 'interface'
965
966 def __init__(self, wsock, filters):
967 self.wsock = wsock
968 self.paths = filters.get("paths", [])
969 self.interfaces = filters.get("interfaces", [])
Andrew Geissler0f7019d2018-10-10 15:00:17 -0500970 self.signals = []
971 self.socket_error = False
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500972 if not self.paths:
973 self.paths.append(None)
974 bus = dbus.SystemBus()
975 # Add a signal receiver for every path the client is interested in
976 for path in self.paths:
Andrew Geissler0f7019d2018-10-10 15:00:17 -0500977 add_sig = bus.add_signal_receiver(
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500978 self.interfaces_added_handler,
979 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
980 signal_name='InterfacesAdded',
981 path=path)
Andrew Geissler0f7019d2018-10-10 15:00:17 -0500982 chg_sig = bus.add_signal_receiver(
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500983 self.properties_changed_handler,
984 dbus_interface=dbus.PROPERTIES_IFACE,
985 signal_name='PropertiesChanged',
986 path=path,
987 path_keyword='path')
Andrew Geissler0f7019d2018-10-10 15:00:17 -0500988 self.signals.append(add_sig)
989 self.signals.append(chg_sig)
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500990 loop = gobject.MainLoop()
991 # gobject's mainloop.run() will block the entire process, so the gevent
992 # scheduler and hence greenlets won't execute. The while-loop below
993 # works around this limitation by using gevent's sleep, instead of
994 # calling loop.run()
995 gcontext = loop.get_context()
996 while loop is not None:
997 try:
Andrew Geissler0f7019d2018-10-10 15:00:17 -0500998 if self.socket_error:
999 for signal in self.signals:
1000 signal.remove()
1001 loop.quit()
1002 break;
Deepak Kodihalli639b5022017-10-13 06:40:26 -05001003 if gcontext.pending():
1004 gcontext.iteration()
1005 else:
1006 # gevent.sleep puts only the current greenlet to sleep,
1007 # not the entire process.
1008 gevent.sleep(5)
1009 except WebSocketError:
1010 break
1011
1012 def interfaces_added_handler(self, path, iprops, **kw):
1013 ''' If the client is interested in these changes, respond to the
1014 client. This handles d-bus interface additions.'''
1015 if (not self.interfaces) or \
1016 (not set(iprops).isdisjoint(self.interfaces)):
1017 response = {}
1018 response[self.keyNames['event']] = "InterfacesAdded"
1019 response[self.keyNames['path']] = path
1020 response[self.keyNames['intfMap']] = iprops
1021 try:
1022 self.wsock.send(json.dumps(response))
Andrew Geissler0f7019d2018-10-10 15:00:17 -05001023 except:
1024 self.socket_error = True
Deepak Kodihalli639b5022017-10-13 06:40:26 -05001025 return
1026
1027 def properties_changed_handler(self, interface, new, old, **kw):
1028 ''' If the client is interested in these changes, respond to the
1029 client. This handles d-bus property changes. '''
1030 if (not self.interfaces) or (interface in self.interfaces):
1031 path = str(kw['path'])
1032 response = {}
1033 response[self.keyNames['event']] = "PropertiesChanged"
1034 response[self.keyNames['path']] = path
1035 response[self.keyNames['intf']] = interface
1036 response[self.keyNames['propMap']] = new
1037 try:
1038 self.wsock.send(json.dumps(response))
Andrew Geissler0f7019d2018-10-10 15:00:17 -05001039 except:
1040 self.socket_error = True
Deepak Kodihalli639b5022017-10-13 06:40:26 -05001041 return
1042
1043
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001044class EventHandler(RouteHandler):
1045 ''' Handles the /subscribe route, for clients to be able
1046 to subscribe to BMC events. '''
1047
1048 verbs = ['GET']
1049 rules = ['/subscribe']
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001050 suppress_logging = True
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001051
1052 def __init__(self, app, bus):
1053 super(EventHandler, self).__init__(
1054 app, bus, self.verbs, self.rules)
1055
1056 def find(self, **kw):
1057 pass
1058
1059 def setup(self, **kw):
1060 pass
1061
1062 def do_get(self):
1063 wsock = request.environ.get('wsgi.websocket')
1064 if not wsock:
1065 abort(400, 'Expected WebSocket request.')
Jayashankar Padathbec10c22018-05-29 18:22:59 +05301066 ping_sender = Greenlet.spawn(send_ws_ping, wsock, WEBSOCKET_TIMEOUT)
Deepak Kodihalli639b5022017-10-13 06:40:26 -05001067 filters = wsock.receive()
1068 filters = json.loads(filters)
1069 notifier = EventNotifier(wsock, filters)
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001070
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001071class HostConsoleHandler(RouteHandler):
1072 ''' Handles the /console route, for clients to be able
1073 read/write the host serial console. The way this is
1074 done is by exposing a websocket that's mirrored to an
1075 abstract UNIX domain socket, which is the source for
1076 the console data. '''
1077
1078 verbs = ['GET']
1079 # Naming the route console0, because the numbering will help
1080 # on multi-bmc/multi-host systems.
1081 rules = ['/console0']
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001082 suppress_logging = True
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001083
1084 def __init__(self, app, bus):
1085 super(HostConsoleHandler, self).__init__(
1086 app, bus, self.verbs, self.rules)
1087
1088 def find(self, **kw):
1089 pass
1090
1091 def setup(self, **kw):
1092 pass
1093
1094 def read_wsock(self, wsock, sock):
1095 while True:
1096 try:
1097 incoming = wsock.receive()
1098 if incoming:
1099 # Read websocket, write to UNIX socket
1100 sock.send(incoming)
1101 except Exception as e:
1102 sock.close()
1103 return
1104
1105 def read_sock(self, sock, wsock):
1106 max_sock_read_len = 4096
1107 while True:
1108 try:
1109 outgoing = sock.recv(max_sock_read_len)
1110 if outgoing:
1111 # Read UNIX socket, write to websocket
1112 wsock.send(outgoing)
1113 except Exception as e:
1114 wsock.close()
1115 return
1116
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001117 def do_get(self):
1118 wsock = request.environ.get('wsgi.websocket')
1119 if not wsock:
1120 abort(400, 'Expected WebSocket based request.')
1121
Vernon Mauerydbc46912018-12-19 10:33:46 -08001122 # An abstract Unix socket path must be less than or equal to 108 bytes
1123 # and does not need to be nul-terminated or padded out to 108 bytes
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001124 socket_name = "\0obmc-console"
Vernon Mauerydbc46912018-12-19 10:33:46 -08001125 socket_path = socket_name
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001126 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1127
1128 try:
1129 sock.connect(socket_path)
1130 except Exception as e:
1131 abort(500, str(e))
1132
1133 wsock_reader = Greenlet.spawn(self.read_wsock, wsock, sock)
1134 sock_reader = Greenlet.spawn(self.read_sock, sock, wsock)
Jayashankar Padathbec10c22018-05-29 18:22:59 +05301135 ping_sender = Greenlet.spawn(send_ws_ping, wsock, WEBSOCKET_TIMEOUT)
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001136 gevent.joinall([wsock_reader, sock_reader, ping_sender])
1137
1138
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001139class ImagePutHandler(RouteHandler):
1140 ''' Handles the /upload/image/<filename> route. '''
1141
1142 verbs = ['PUT']
1143 rules = ['/upload/image/<filename>']
1144 content_type = 'application/octet-stream'
1145
1146 def __init__(self, app, bus):
1147 super(ImagePutHandler, self).__init__(
1148 app, bus, self.verbs, self.rules, self.content_type)
1149
1150 def do_put(self, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -05001151 return ImageUploadUtils.do_upload(filename)
Deepak Kodihalli1af301a2017-04-11 07:29:01 -05001152
1153 def find(self, **kw):
1154 pass
1155
1156 def setup(self, **kw):
1157 pass
1158
1159
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001160class DownloadDumpHandler(RouteHandler):
1161 ''' Handles the /download/dump route. '''
1162
1163 verbs = 'GET'
1164 rules = ['/download/dump/<dumpid>']
1165 content_type = 'application/octet-stream'
Jayanth Othayoth18c3a242017-08-02 08:16:11 -05001166 dump_loc = '/var/lib/phosphor-debug-collector/dumps'
Brad Bishop944cd042017-07-10 16:42:41 -04001167 suppress_json_resp = True
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001168 suppress_logging = True
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001169
1170 def __init__(self, app, bus):
1171 super(DownloadDumpHandler, self).__init__(
1172 app, bus, self.verbs, self.rules, self.content_type)
1173
1174 def do_get(self, dumpid):
1175 return self.do_download(dumpid)
1176
1177 def find(self, **kw):
1178 pass
1179
1180 def setup(self, **kw):
1181 pass
1182
1183 def do_download(self, dumpid):
1184 dump_loc = os.path.join(self.dump_loc, dumpid)
1185 if not os.path.exists(dump_loc):
1186 abort(404, "Path not found")
1187
1188 files = os.listdir(dump_loc)
1189 num_files = len(files)
1190 if num_files == 0:
1191 abort(404, "Dump not found")
1192
1193 return static_file(os.path.basename(files[0]), root=dump_loc,
1194 download=True, mimetype=self.content_type)
1195
1196
Matt Spinlerd41643e2018-02-02 13:51:38 -06001197class WebHandler(RouteHandler):
1198 ''' Handles the routes for the web UI files. '''
1199
1200 verbs = 'GET'
1201
1202 # Match only what we know are web files, so everything else
1203 # can get routed to the REST handlers.
1204 rules = ['//', '/<filename:re:.+\.js>', '/<filename:re:.+\.svg>',
1205 '/<filename:re:.+\.css>', '/<filename:re:.+\.ttf>',
1206 '/<filename:re:.+\.eot>', '/<filename:re:.+\.woff>',
1207 '/<filename:re:.+\.woff2>', '/<filename:re:.+\.map>',
1208 '/<filename:re:.+\.png>', '/<filename:re:.+\.html>',
1209 '/<filename:re:.+\.ico>']
1210
1211 # The mimetypes module knows about most types, but not these
1212 content_types = {
1213 '.eot': 'application/vnd.ms-fontobject',
1214 '.woff': 'application/x-font-woff',
1215 '.woff2': 'application/x-font-woff2',
1216 '.ttf': 'application/x-font-ttf',
1217 '.map': 'application/json'
1218 }
1219
1220 _require_auth = None
1221 suppress_json_resp = True
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001222 suppress_logging = True
Matt Spinlerd41643e2018-02-02 13:51:38 -06001223
1224 def __init__(self, app, bus):
1225 super(WebHandler, self).__init__(
1226 app, bus, self.verbs, self.rules)
1227
1228 def get_type(self, filename):
1229 ''' Returns the content type and encoding for a file '''
1230
1231 content_type, encoding = mimetypes.guess_type(filename)
1232
1233 # Try our own list if mimetypes didn't recognize it
1234 if content_type is None:
1235 if filename[-3:] == '.gz':
1236 filename = filename[:-3]
1237 extension = filename[filename.rfind('.'):]
1238 content_type = self.content_types.get(extension, None)
1239
1240 return content_type, encoding
1241
1242 def do_get(self, filename='index.html'):
1243
1244 # If a gzipped version exists, use that instead.
1245 # Possible future enhancement: if the client doesn't
1246 # accept compressed files, unzip it ourselves before sending.
1247 if not os.path.exists(os.path.join(www_base_path, filename)):
1248 filename = filename + '.gz'
1249
1250 # Though bottle should protect us, ensure path is valid
1251 realpath = os.path.realpath(filename)
1252 if realpath[0] == '/':
1253 realpath = realpath[1:]
1254 if not os.path.exists(os.path.join(www_base_path, realpath)):
1255 abort(404, "Path not found")
1256
1257 mimetype, encoding = self.get_type(filename)
1258
1259 # Couldn't find the type - let static_file() deal with it,
1260 # though this should never happen.
1261 if mimetype is None:
1262 print("Can't figure out content-type for %s" % filename)
1263 mimetype = 'auto'
1264
1265 # This call will set several header fields for us,
1266 # including the charset if the type is text.
1267 response = static_file(filename, www_base_path, mimetype)
1268
1269 # static_file() will only set the encoding if the
1270 # mimetype was auto, so set it here.
1271 if encoding is not None:
1272 response.set_header('Content-Encoding', encoding)
1273
1274 return response
1275
1276 def find(self, **kw):
1277 pass
1278
1279 def setup(self, **kw):
1280 pass
1281
1282
Brad Bishop2f428582015-12-02 10:56:11 -05001283class AuthorizationPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001284 ''' Invokes an optional list of authorization callbacks. '''
Brad Bishop2f428582015-12-02 10:56:11 -05001285
Brad Bishop87b63c12016-03-18 14:47:51 -04001286 name = 'authorization'
1287 api = 2
Brad Bishop2f428582015-12-02 10:56:11 -05001288
Brad Bishop87b63c12016-03-18 14:47:51 -04001289 class Compose:
1290 def __init__(self, validators, callback, session_mgr):
1291 self.validators = validators
1292 self.callback = callback
1293 self.session_mgr = session_mgr
Brad Bishop2f428582015-12-02 10:56:11 -05001294
Brad Bishop87b63c12016-03-18 14:47:51 -04001295 def __call__(self, *a, **kw):
1296 sid = request.get_cookie('sid', secret=self.session_mgr.hmac_key)
1297 session = self.session_mgr.get_session(sid)
Brad Bishopd4c1c552017-02-21 00:07:28 -05001298 if request.method != 'OPTIONS':
1299 for x in self.validators:
1300 x(session, *a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -05001301
Brad Bishop87b63c12016-03-18 14:47:51 -04001302 return self.callback(*a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -05001303
Brad Bishop87b63c12016-03-18 14:47:51 -04001304 def apply(self, callback, route):
1305 undecorated = route.get_undecorated_callback()
1306 if not isinstance(undecorated, RouteHandler):
1307 return callback
Brad Bishop2f428582015-12-02 10:56:11 -05001308
Brad Bishop87b63c12016-03-18 14:47:51 -04001309 auth_types = getattr(
1310 undecorated, '_require_auth', None)
1311 if not auth_types:
1312 return callback
Brad Bishop2f428582015-12-02 10:56:11 -05001313
Brad Bishop87b63c12016-03-18 14:47:51 -04001314 return self.Compose(
1315 auth_types, callback, undecorated.app.session_handler)
1316
Brad Bishop2f428582015-12-02 10:56:11 -05001317
Brad Bishopd0c404a2017-02-21 09:23:25 -05001318class CorsPlugin(object):
1319 ''' Add CORS headers. '''
1320
1321 name = 'cors'
1322 api = 2
1323
1324 @staticmethod
1325 def process_origin():
1326 origin = request.headers.get('Origin')
1327 if origin:
1328 response.add_header('Access-Control-Allow-Origin', origin)
1329 response.add_header(
1330 'Access-Control-Allow-Credentials', 'true')
1331
1332 @staticmethod
1333 def process_method_and_headers(verbs):
1334 method = request.headers.get('Access-Control-Request-Method')
1335 headers = request.headers.get('Access-Control-Request-Headers')
1336 if headers:
1337 headers = [x.lower() for x in headers.split(',')]
1338
1339 if method in verbs \
1340 and headers == ['content-type']:
1341 response.add_header('Access-Control-Allow-Methods', method)
1342 response.add_header(
1343 'Access-Control-Allow-Headers', 'Content-Type')
Ratan Gupta91b46f82018-01-14 12:52:23 +05301344 response.add_header('X-Frame-Options', 'deny')
1345 response.add_header('X-Content-Type-Options', 'nosniff')
1346 response.add_header('X-XSS-Protection', '1; mode=block')
1347 response.add_header(
1348 'Content-Security-Policy', "default-src 'self'")
1349 response.add_header(
1350 'Strict-Transport-Security',
1351 'max-age=31536000; includeSubDomains; preload')
Brad Bishopd0c404a2017-02-21 09:23:25 -05001352
1353 def __init__(self, app):
1354 app.install_error_callback(self.error_callback)
1355
1356 def apply(self, callback, route):
1357 undecorated = route.get_undecorated_callback()
1358 if not isinstance(undecorated, RouteHandler):
1359 return callback
1360
1361 if not getattr(undecorated, '_enable_cors', None):
1362 return callback
1363
1364 def wrap(*a, **kw):
1365 self.process_origin()
1366 self.process_method_and_headers(undecorated._verbs)
1367 return callback(*a, **kw)
1368
1369 return wrap
1370
1371 def error_callback(self, **kw):
1372 self.process_origin()
1373
1374
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001375class JsonApiRequestPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001376 ''' Ensures request content satisfies the OpenBMC json api format. '''
1377 name = 'json_api_request'
1378 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001379
Brad Bishop87b63c12016-03-18 14:47:51 -04001380 error_str = "Expecting request format { 'data': <value> }, got '%s'"
1381 type_error_str = "Unsupported Content-Type: '%s'"
1382 json_type = "application/json"
1383 request_methods = ['PUT', 'POST', 'PATCH']
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001384
Brad Bishop87b63c12016-03-18 14:47:51 -04001385 @staticmethod
1386 def content_expected():
1387 return request.method in JsonApiRequestPlugin.request_methods
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001388
Brad Bishop87b63c12016-03-18 14:47:51 -04001389 def validate_request(self):
1390 if request.content_length > 0 and \
1391 request.content_type != self.json_type:
1392 abort(415, self.type_error_str % request.content_type)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001393
Brad Bishop87b63c12016-03-18 14:47:51 -04001394 try:
1395 request.parameter_list = request.json.get('data')
CamVan Nguyen249d1322018-03-05 10:08:33 -06001396 except ValueError as e:
Brad Bishop87b63c12016-03-18 14:47:51 -04001397 abort(400, str(e))
1398 except (AttributeError, KeyError, TypeError):
1399 abort(400, self.error_str % request.json)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001400
Brad Bishop87b63c12016-03-18 14:47:51 -04001401 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001402 content_type = getattr(
1403 route.get_undecorated_callback(), '_content_type', None)
1404 if self.json_type != content_type:
1405 return callback
1406
Brad Bishop87b63c12016-03-18 14:47:51 -04001407 verbs = getattr(
1408 route.get_undecorated_callback(), '_verbs', None)
1409 if verbs is None:
1410 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001411
Brad Bishop87b63c12016-03-18 14:47:51 -04001412 if not set(self.request_methods).intersection(verbs):
1413 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001414
Brad Bishop87b63c12016-03-18 14:47:51 -04001415 def wrap(*a, **kw):
1416 if self.content_expected():
1417 self.validate_request()
1418 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001419
Brad Bishop87b63c12016-03-18 14:47:51 -04001420 return wrap
1421
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001422
1423class JsonApiRequestTypePlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001424 ''' Ensures request content type satisfies the OpenBMC json api format. '''
1425 name = 'json_api_method_request'
1426 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001427
Brad Bishop87b63c12016-03-18 14:47:51 -04001428 error_str = "Expecting request format { 'data': %s }, got '%s'"
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001429 json_type = "application/json"
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001430
Brad Bishop87b63c12016-03-18 14:47:51 -04001431 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001432 content_type = getattr(
1433 route.get_undecorated_callback(), '_content_type', None)
1434 if self.json_type != content_type:
1435 return callback
1436
Brad Bishop87b63c12016-03-18 14:47:51 -04001437 request_type = getattr(
1438 route.get_undecorated_callback(), 'request_type', None)
1439 if request_type is None:
1440 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001441
Brad Bishop87b63c12016-03-18 14:47:51 -04001442 def validate_request():
1443 if not isinstance(request.parameter_list, request_type):
1444 abort(400, self.error_str % (str(request_type), request.json))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001445
Brad Bishop87b63c12016-03-18 14:47:51 -04001446 def wrap(*a, **kw):
1447 if JsonApiRequestPlugin.content_expected():
1448 validate_request()
1449 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001450
Brad Bishop87b63c12016-03-18 14:47:51 -04001451 return wrap
1452
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001453
Brad Bishop080a48e2017-02-21 22:34:43 -05001454class JsonErrorsPlugin(JSONPlugin):
1455 ''' Extend the Bottle JSONPlugin such that it also encodes error
1456 responses. '''
1457
1458 def __init__(self, app, **kw):
1459 super(JsonErrorsPlugin, self).__init__(**kw)
1460 self.json_opts = {
CamVan Nguyen249d1322018-03-05 10:08:33 -06001461 x: y for x, y in kw.items()
Brad Bishop080a48e2017-02-21 22:34:43 -05001462 if x in ['indent', 'sort_keys']}
1463 app.install_error_callback(self.error_callback)
1464
1465 def error_callback(self, response_object, response_body, **kw):
1466 response_body['body'] = json.dumps(response_object, **self.json_opts)
1467 response.content_type = 'application/json'
1468
1469
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001470class JsonApiResponsePlugin(object):
Brad Bishop080a48e2017-02-21 22:34:43 -05001471 ''' Emits responses in the OpenBMC json api format. '''
Brad Bishop87b63c12016-03-18 14:47:51 -04001472 name = 'json_api_response'
1473 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001474
Brad Bishopd4c1c552017-02-21 00:07:28 -05001475 @staticmethod
1476 def has_body():
1477 return request.method not in ['OPTIONS']
1478
Brad Bishop080a48e2017-02-21 22:34:43 -05001479 def __init__(self, app):
1480 app.install_error_callback(self.error_callback)
1481
Matt Spinler6691e7c2018-06-25 14:11:58 -05001482 @staticmethod
1483 def dbus_boolean_to_bool(data):
1484 ''' Convert all dbus.Booleans to true/false instead of 1/0 as
1485 the JSON encoder thinks they're ints. Note that unlike
1486 dicts and lists, tuples (from a dbus.Struct) are immutable
1487 so they need special handling. '''
1488
1489 def walkdict(data):
1490 for key, value in data.items():
1491 if isinstance(value, dbus.Boolean):
1492 data[key] = bool(value)
1493 elif isinstance(value, tuple):
1494 data[key] = walktuple(value)
1495 else:
1496 JsonApiResponsePlugin.dbus_boolean_to_bool(value)
1497
1498 def walklist(data):
1499 for i in range(len(data)):
1500 if isinstance(data[i], dbus.Boolean):
1501 data[i] = bool(data[i])
1502 elif isinstance(data[i], tuple):
1503 data[i] = walktuple(data[i])
1504 else:
1505 JsonApiResponsePlugin.dbus_boolean_to_bool(data[i])
1506
1507 def walktuple(data):
1508 new = []
1509 for item in data:
1510 if isinstance(item, dbus.Boolean):
1511 item = bool(item)
1512 else:
1513 JsonApiResponsePlugin.dbus_boolean_to_bool(item)
1514 new.append(item)
1515 return tuple(new)
1516
1517 if isinstance(data, dict):
1518 walkdict(data)
1519 elif isinstance(data, list):
1520 walklist(data)
1521
Brad Bishop87b63c12016-03-18 14:47:51 -04001522 def apply(self, callback, route):
Brad Bishop944cd042017-07-10 16:42:41 -04001523 skip = getattr(
1524 route.get_undecorated_callback(), 'suppress_json_resp', None)
1525 if skip:
Jayanth Othayoth1444fd82017-06-29 05:45:07 -05001526 return callback
1527
Brad Bishop87b63c12016-03-18 14:47:51 -04001528 def wrap(*a, **kw):
Brad Bishopd4c1c552017-02-21 00:07:28 -05001529 data = callback(*a, **kw)
Matt Spinler6691e7c2018-06-25 14:11:58 -05001530 JsonApiResponsePlugin.dbus_boolean_to_bool(data)
Brad Bishopd4c1c552017-02-21 00:07:28 -05001531 if self.has_body():
1532 resp = {'data': data}
1533 resp['status'] = 'ok'
1534 resp['message'] = response.status_line
1535 return resp
Brad Bishop87b63c12016-03-18 14:47:51 -04001536 return wrap
1537
Brad Bishop080a48e2017-02-21 22:34:43 -05001538 def error_callback(self, error, response_object, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -04001539 response_object['message'] = error.status_line
Brad Bishop9c2531e2017-03-07 10:22:40 -05001540 response_object['status'] = 'error'
Brad Bishop080a48e2017-02-21 22:34:43 -05001541 response_object.setdefault('data', {})['description'] = str(error.body)
Brad Bishop87b63c12016-03-18 14:47:51 -04001542 if error.status_code == 500:
1543 response_object['data']['exception'] = repr(error.exception)
1544 response_object['data']['traceback'] = error.traceback.splitlines()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001545
Brad Bishop87b63c12016-03-18 14:47:51 -04001546
Brad Bishop080a48e2017-02-21 22:34:43 -05001547class JsonpPlugin(object):
Brad Bishop80fe37a2016-03-29 10:54:54 -04001548 ''' Json javascript wrapper. '''
1549 name = 'jsonp'
1550 api = 2
1551
Brad Bishop080a48e2017-02-21 22:34:43 -05001552 def __init__(self, app, **kw):
1553 app.install_error_callback(self.error_callback)
Brad Bishop80fe37a2016-03-29 10:54:54 -04001554
1555 @staticmethod
1556 def to_jsonp(json):
1557 jwrapper = request.query.callback or None
1558 if(jwrapper):
1559 response.set_header('Content-Type', 'application/javascript')
1560 json = jwrapper + '(' + json + ');'
1561 return json
1562
1563 def apply(self, callback, route):
1564 def wrap(*a, **kw):
1565 return self.to_jsonp(callback(*a, **kw))
1566 return wrap
1567
Brad Bishop080a48e2017-02-21 22:34:43 -05001568 def error_callback(self, response_body, **kw):
1569 response_body['body'] = self.to_jsonp(response_body['body'])
Brad Bishop80fe37a2016-03-29 10:54:54 -04001570
1571
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001572class ContentCheckerPlugin(object):
1573 ''' Ensures that a route is associated with the expected content-type
1574 header. '''
1575 name = 'content_checker'
1576 api = 2
1577
1578 class Checker:
1579 def __init__(self, type, callback):
1580 self.expected_type = type
1581 self.callback = callback
1582 self.error_str = "Expecting content type '%s', got '%s'"
1583
1584 def __call__(self, *a, **kw):
Deepak Kodihallidb1a21e2017-04-27 06:30:11 -05001585 if request.method in ['PUT', 'POST', 'PATCH'] and \
1586 self.expected_type and \
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001587 self.expected_type != request.content_type:
1588 abort(415, self.error_str % (self.expected_type,
1589 request.content_type))
1590
1591 return self.callback(*a, **kw)
1592
1593 def apply(self, callback, route):
1594 content_type = getattr(
1595 route.get_undecorated_callback(), '_content_type', None)
1596
1597 return self.Checker(content_type, callback)
1598
1599
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001600class LoggingPlugin(object):
1601 ''' Wraps a request in order to emit a log after the request is handled. '''
1602 name = 'loggingp'
1603 api = 2
1604
1605 class Logger:
1606 def __init__(self, suppress_json_logging, callback, app):
1607 self.suppress_json_logging = suppress_json_logging
1608 self.callback = callback
1609 self.app = app
Deepak Kodihalli95803682018-09-07 03:13:59 -05001610 self.logging_enabled = None
1611 self.bus = dbus.SystemBus()
1612 self.dbus_path = '/xyz/openbmc_project/logging/rest_api_logs'
Deepak Kodihalli4b412ac2018-10-15 12:45:18 -05001613 self.no_json = [
1614 '/xyz/openbmc_project/user/ldap/action/CreateConfig'
1615 ]
Deepak Kodihalli95803682018-09-07 03:13:59 -05001616 self.bus.add_signal_receiver(
1617 self.properties_changed_handler,
1618 dbus_interface=dbus.PROPERTIES_IFACE,
1619 signal_name='PropertiesChanged',
1620 path=self.dbus_path)
1621 Greenlet.spawn(self.dbus_loop)
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001622
1623 def __call__(self, *a, **kw):
1624 resp = self.callback(*a, **kw)
Deepak Kodihalli95803682018-09-07 03:13:59 -05001625 if not self.enabled():
Deepak Kodihalli4aa10002018-09-13 11:48:45 -05001626 return resp
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001627 if request.method == 'GET':
Deepak Kodihalli4aa10002018-09-13 11:48:45 -05001628 return resp
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001629 json = request.json
1630 if self.suppress_json_logging:
1631 json = None
Deepak Kodihalli4b412ac2018-10-15 12:45:18 -05001632 elif any(substring in request.url for substring in self.no_json):
1633 json = None
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001634 session = self.app.session_handler.get_session_from_cookie()
1635 user = None
1636 if "/login" in request.url:
1637 user = request.parameter_list[0]
1638 elif session is not None:
1639 user = session['user']
1640 print("{remote} user:{user} {method} {url} json:{json} {status}" \
1641 .format(
1642 user=user,
1643 remote=request.remote_addr,
1644 method=request.method,
1645 url=request.url,
1646 json=json,
1647 status=response.status))
Deepak Kodihalli4aa10002018-09-13 11:48:45 -05001648 return resp
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001649
Deepak Kodihalli95803682018-09-07 03:13:59 -05001650 def enabled(self):
1651 if self.logging_enabled is None:
1652 try:
1653 obj = self.bus.get_object(
1654 'xyz.openbmc_project.Settings',
1655 self.dbus_path)
1656 iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE)
1657 logging_enabled = iface.Get(
1658 'xyz.openbmc_project.Object.Enable',
1659 'Enabled')
1660 self.logging_enabled = logging_enabled
1661 except dbus.exceptions.DBusException:
1662 self.logging_enabled = False
1663 return self.logging_enabled
1664
1665 def dbus_loop(self):
1666 loop = gobject.MainLoop()
1667 gcontext = loop.get_context()
1668 while loop is not None:
1669 try:
1670 if gcontext.pending():
1671 gcontext.iteration()
1672 else:
1673 gevent.sleep(5)
1674 except Exception as e:
1675 break
1676
1677 def properties_changed_handler(self, interface, new, old, **kw):
1678 self.logging_enabled = new.values()[0]
1679
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001680 def apply(self, callback, route):
1681 cb = route.get_undecorated_callback()
1682 skip = getattr(
1683 cb, 'suppress_logging', None)
1684 if skip:
1685 return callback
1686
1687 suppress_json_logging = getattr(
1688 cb, 'suppress_json_logging', None)
1689 return self.Logger(suppress_json_logging, callback, cb.app)
1690
1691
Brad Bishop2c6fc762016-08-29 15:53:25 -04001692class App(Bottle):
Deepak Kodihalli0fe213f2017-10-11 00:08:48 -05001693 def __init__(self, **kw):
Brad Bishop2c6fc762016-08-29 15:53:25 -04001694 super(App, self).__init__(autojson=False)
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001695
1696 self.have_wsock = kw.get('have_wsock', False)
Alexander Filippovd08a4562018-03-20 12:02:23 +03001697 self.with_bmc_check = '--with-bmc-check' in sys.argv
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001698
Brad Bishop2ddfa002016-08-29 15:11:55 -04001699 self.bus = dbus.SystemBus()
1700 self.mapper = obmc.mapper.Mapper(self.bus)
Brad Bishop080a48e2017-02-21 22:34:43 -05001701 self.error_callbacks = []
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001702
Brad Bishop87b63c12016-03-18 14:47:51 -04001703 self.install_hooks()
1704 self.install_plugins()
1705 self.create_handlers()
1706 self.install_handlers()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001707
Brad Bishop87b63c12016-03-18 14:47:51 -04001708 def install_plugins(self):
1709 # install json api plugins
1710 json_kw = {'indent': 2, 'sort_keys': True}
Brad Bishop87b63c12016-03-18 14:47:51 -04001711 self.install(AuthorizationPlugin())
Brad Bishopd0c404a2017-02-21 09:23:25 -05001712 self.install(CorsPlugin(self))
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001713 self.install(ContentCheckerPlugin())
Brad Bishop080a48e2017-02-21 22:34:43 -05001714 self.install(JsonpPlugin(self, **json_kw))
1715 self.install(JsonErrorsPlugin(self, **json_kw))
1716 self.install(JsonApiResponsePlugin(self))
Brad Bishop87b63c12016-03-18 14:47:51 -04001717 self.install(JsonApiRequestPlugin())
1718 self.install(JsonApiRequestTypePlugin())
Deepak Kodihalli6e1ca532018-09-04 03:51:04 -05001719 self.install(LoggingPlugin())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001720
Brad Bishop87b63c12016-03-18 14:47:51 -04001721 def install_hooks(self):
Brad Bishop080a48e2017-02-21 22:34:43 -05001722 self.error_handler_type = type(self.default_error_handler)
1723 self.original_error_handler = self.default_error_handler
1724 self.default_error_handler = self.error_handler_type(
1725 self.custom_error_handler, self, Bottle)
1726
Brad Bishop87b63c12016-03-18 14:47:51 -04001727 self.real_router_match = self.router.match
1728 self.router.match = self.custom_router_match
1729 self.add_hook('before_request', self.strip_extra_slashes)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001730
Brad Bishop87b63c12016-03-18 14:47:51 -04001731 def create_handlers(self):
1732 # create route handlers
1733 self.session_handler = SessionHandler(self, self.bus)
Matt Spinlerd41643e2018-02-02 13:51:38 -06001734 self.web_handler = WebHandler(self, self.bus)
Brad Bishop87b63c12016-03-18 14:47:51 -04001735 self.directory_handler = DirectoryHandler(self, self.bus)
1736 self.list_names_handler = ListNamesHandler(self, self.bus)
1737 self.list_handler = ListHandler(self, self.bus)
1738 self.method_handler = MethodHandler(self, self.bus)
1739 self.property_handler = PropertyHandler(self, self.bus)
1740 self.schema_handler = SchemaHandler(self, self.bus)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001741 self.image_upload_post_handler = ImagePostHandler(self, self.bus)
1742 self.image_upload_put_handler = ImagePutHandler(self, self.bus)
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001743 self.download_dump_get_handler = DownloadDumpHandler(self, self.bus)
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -05001744 self.certificate_put_handler = CertificatePutHandler(self, self.bus)
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001745 if self.have_wsock:
1746 self.event_handler = EventHandler(self, self.bus)
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001747 self.host_console_handler = HostConsoleHandler(self, self.bus)
Brad Bishop87b63c12016-03-18 14:47:51 -04001748 self.instance_handler = InstanceHandler(self, self.bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001749
Brad Bishop87b63c12016-03-18 14:47:51 -04001750 def install_handlers(self):
1751 self.session_handler.install()
Matt Spinlerd41643e2018-02-02 13:51:38 -06001752 self.web_handler.install()
Brad Bishop87b63c12016-03-18 14:47:51 -04001753 self.directory_handler.install()
1754 self.list_names_handler.install()
1755 self.list_handler.install()
1756 self.method_handler.install()
1757 self.property_handler.install()
1758 self.schema_handler.install()
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001759 self.image_upload_post_handler.install()
1760 self.image_upload_put_handler.install()
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001761 self.download_dump_get_handler.install()
Dhruvaraj Subhashchandrandee2ef52018-09-05 05:36:31 -05001762 self.certificate_put_handler.install()
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001763 if self.have_wsock:
1764 self.event_handler.install()
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001765 self.host_console_handler.install()
Brad Bishop87b63c12016-03-18 14:47:51 -04001766 # this has to come last, since it matches everything
1767 self.instance_handler.install()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001768
Brad Bishop080a48e2017-02-21 22:34:43 -05001769 def install_error_callback(self, callback):
1770 self.error_callbacks.insert(0, callback)
1771
Brad Bishop87b63c12016-03-18 14:47:51 -04001772 def custom_router_match(self, environ):
1773 ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is
1774 needed doesn't work for us since the instance rules match
1775 everything. This monkey-patch lets the route handler figure
1776 out which response is needed. This could be accomplished
1777 with a hook but that would require calling the router match
1778 function twice.
1779 '''
1780 route, args = self.real_router_match(environ)
1781 if isinstance(route.callback, RouteHandler):
1782 route.callback._setup(**args)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001783
Brad Bishop87b63c12016-03-18 14:47:51 -04001784 return route, args
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001785
Brad Bishop080a48e2017-02-21 22:34:43 -05001786 def custom_error_handler(self, res, error):
Gunnar Millsf01d0ba2017-10-25 20:37:24 -05001787 ''' Allow plugins to modify error responses too via this custom
Brad Bishop080a48e2017-02-21 22:34:43 -05001788 error handler. '''
1789
1790 response_object = {}
1791 response_body = {}
1792 for x in self.error_callbacks:
1793 x(error=error,
1794 response_object=response_object,
1795 response_body=response_body)
1796
1797 return response_body.get('body', "")
1798
Brad Bishop87b63c12016-03-18 14:47:51 -04001799 @staticmethod
1800 def strip_extra_slashes():
1801 path = request.environ['PATH_INFO']
1802 trailing = ("", "/")[path[-1] == '/']
CamVan Nguyen249d1322018-03-05 10:08:33 -06001803 parts = list(filter(bool, path.split('/')))
Brad Bishop87b63c12016-03-18 14:47:51 -04001804 request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing