blob: badc550b1551da672b9408ed27025e098afc4c5a [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>/'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400293
Brad Bishop87b63c12016-03-18 14:47:51 -0400294 def __init__(self, app, bus):
295 super(DirectoryHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400296 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400297
Brad Bishop87b63c12016-03-18 14:47:51 -0400298 def find(self, path='/'):
299 return self.try_mapper_call(
300 self.mapper.get_subtree_paths, path=path, depth=1)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400301
Brad Bishop87b63c12016-03-18 14:47:51 -0400302 def setup(self, path='/'):
303 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400304
Brad Bishop87b63c12016-03-18 14:47:51 -0400305 def do_get(self, path='/'):
306 return request.route_data['map']
307
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400308
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500309class ListNamesHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400310 verbs = 'GET'
311 rules = ['/list', '<path:path>/list']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400312
Brad Bishop87b63c12016-03-18 14:47:51 -0400313 def __init__(self, app, bus):
314 super(ListNamesHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400315 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400316
Brad Bishop87b63c12016-03-18 14:47:51 -0400317 def find(self, path='/'):
CamVan Nguyen249d1322018-03-05 10:08:33 -0600318 return list(self.try_mapper_call(
319 self.mapper.get_subtree, path=path).keys())
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400320
Brad Bishop87b63c12016-03-18 14:47:51 -0400321 def setup(self, path='/'):
322 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400323
Brad Bishop87b63c12016-03-18 14:47:51 -0400324 def do_get(self, path='/'):
325 return request.route_data['map']
326
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400327
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500328class ListHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400329 verbs = 'GET'
330 rules = ['/enumerate', '<path:path>/enumerate']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400331
Brad Bishop87b63c12016-03-18 14:47:51 -0400332 def __init__(self, app, bus):
333 super(ListHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400334 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400335
Brad Bishop87b63c12016-03-18 14:47:51 -0400336 def find(self, path='/'):
337 return self.try_mapper_call(
338 self.mapper.get_subtree, path=path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400339
Brad Bishop87b63c12016-03-18 14:47:51 -0400340 def setup(self, path='/'):
341 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400342
Brad Bishop87b63c12016-03-18 14:47:51 -0400343 def do_get(self, path='/'):
Brad Bishop71527b42016-04-01 14:51:14 -0400344 return {x: y for x, y in self.mapper.enumerate_subtree(
345 path,
346 mapper_data=request.route_data['map']).dataitems()}
Brad Bishop87b63c12016-03-18 14:47:51 -0400347
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400348
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500349class MethodHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400350 verbs = 'POST'
351 rules = '<path:path>/action/<method>'
352 request_type = list
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500353 content_type = 'application/json'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400354
Brad Bishop87b63c12016-03-18 14:47:51 -0400355 def __init__(self, app, bus):
356 super(MethodHandler, self).__init__(
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500357 app, bus, self.verbs, self.rules, self.content_type)
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530358 self.service = ''
359 self.interface = ''
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400360
Brad Bishop87b63c12016-03-18 14:47:51 -0400361 def find(self, path, method):
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500362 method_list = []
Gunnar Mills313aadb2018-04-08 14:50:09 -0500363 buses = self.try_mapper_call(
Brad Bishop87b63c12016-03-18 14:47:51 -0400364 self.mapper.get_object, path=path)
Gunnar Mills313aadb2018-04-08 14:50:09 -0500365 for items in buses.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400366 m = self.find_method_on_bus(path, method, *items)
367 if m:
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500368 method_list.append(m)
Nagaraju Goruganti765c2c82017-11-13 06:17:13 -0600369 if method_list:
370 return method_list
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400371
Brad Bishop87b63c12016-03-18 14:47:51 -0400372 abort(404, _4034_msg % ('method', 'found', method))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400373
Brad Bishop87b63c12016-03-18 14:47:51 -0400374 def setup(self, path, method):
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500375 request.route_data['map'] = self.find(path, method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400376
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600377 def do_post(self, path, method, retry=True):
Brad Bishop87b63c12016-03-18 14:47:51 -0400378 try:
Nagaraju Goruganti765c2c82017-11-13 06:17:13 -0600379 args = []
380 if request.parameter_list:
381 args = request.parameter_list
382 # To see if the return type is capable of being merged
383 if len(request.route_data['map']) > 1:
384 results = None
385 for item in request.route_data['map']:
386 tmp = item(*args)
387 if not results:
388 if tmp is not None:
389 results = type(tmp)()
390 if isinstance(results, dict):
391 results = results.update(tmp)
392 elif isinstance(results, list):
393 results = results + tmp
394 elif isinstance(results, type(None)):
395 results = None
396 else:
397 abort(501, 'Don\'t know how to merge method call '
398 'results of {}'.format(type(tmp)))
399 return results
400 # There is only one method
401 return request.route_data['map'][0](*args)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400402
CamVan Nguyen249d1322018-03-05 10:08:33 -0600403 except dbus.exceptions.DBusException as e:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530404 paramlist = []
Brad Bishopb7fca9b2018-01-23 12:16:50 -0500405 if e.get_dbus_name() == DBUS_INVALID_ARGS and retry:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530406
407 signature_list = get_method_signature(self.bus, self.service,
408 path, self.interface,
409 method)
410 if not signature_list:
411 abort(400, "Failed to get method signature: %s" % str(e))
412 if len(signature_list) != len(request.parameter_list):
413 abort(400, "Invalid number of args")
414 converted_value = None
415 try:
416 for index, expected_type in enumerate(signature_list):
417 value = request.parameter_list[index]
418 converted_value = convert_type(expected_type, value)
419 paramlist.append(converted_value)
420 request.parameter_list = paramlist
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600421 self.do_post(path, method, False)
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530422 return
423 except Exception as ex:
Nagaraju Gorugantiab404fa2017-12-14 10:24:40 -0600424 abort(400, "Bad Request/Invalid Args given")
Brad Bishop87b63c12016-03-18 14:47:51 -0400425 abort(400, str(e))
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530426
Brad Bishop87b63c12016-03-18 14:47:51 -0400427 if e.get_dbus_name() == DBUS_TYPE_ERROR:
428 abort(400, str(e))
429 raise
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400430
Brad Bishop87b63c12016-03-18 14:47:51 -0400431 @staticmethod
432 def find_method_in_interface(method, obj, interface, methods):
433 if methods is None:
434 return None
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400435
CamVan Nguyen249d1322018-03-05 10:08:33 -0600436 method = obmc.utils.misc.find_case_insensitive(method, list(methods.keys()))
Brad Bishop87b63c12016-03-18 14:47:51 -0400437 if method is not None:
438 iface = dbus.Interface(obj, interface)
439 return iface.get_dbus_method(method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400440
Brad Bishop87b63c12016-03-18 14:47:51 -0400441 def find_method_on_bus(self, path, method, bus, interfaces):
442 obj = self.bus.get_object(bus, path, introspect=False)
443 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
444 data = iface.Introspect()
445 parser = IntrospectionNodeParser(
446 ElementTree.fromstring(data),
Brad Bishopaeb995d2018-04-04 22:28:42 -0400447 intf_match=lambda x: x in interfaces)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600448 for x, y in parser.get_interfaces().items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400449 m = self.find_method_in_interface(
450 method, obj, x, y.get('method'))
451 if m:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530452 self.service = bus
453 self.interface = x
Brad Bishop87b63c12016-03-18 14:47:51 -0400454 return m
455
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400456
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500457class PropertyHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400458 verbs = ['PUT', 'GET']
459 rules = '<path:path>/attr/<prop>'
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500460 content_type = 'application/json'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400461
Brad Bishop87b63c12016-03-18 14:47:51 -0400462 def __init__(self, app, bus):
463 super(PropertyHandler, self).__init__(
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500464 app, bus, self.verbs, self.rules, self.content_type)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400465
Brad Bishop87b63c12016-03-18 14:47:51 -0400466 def find(self, path, prop):
467 self.app.instance_handler.setup(path)
468 obj = self.app.instance_handler.do_get(path)
Brad Bishop56ad87f2017-02-21 23:33:29 -0500469 real_name = obmc.utils.misc.find_case_insensitive(
CamVan Nguyen249d1322018-03-05 10:08:33 -0600470 prop, list(obj.keys()))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400471
Brad Bishop56ad87f2017-02-21 23:33:29 -0500472 if not real_name:
473 if request.method == 'PUT':
474 abort(403, _4034_msg % ('property', 'created', prop))
475 else:
476 abort(404, _4034_msg % ('property', 'found', prop))
477 return real_name, {path: obj}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500478
Brad Bishop87b63c12016-03-18 14:47:51 -0400479 def setup(self, path, prop):
Brad Bishop56ad87f2017-02-21 23:33:29 -0500480 name, obj = self.find(path, prop)
481 request.route_data['obj'] = obj
482 request.route_data['name'] = name
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500483
Brad Bishop87b63c12016-03-18 14:47:51 -0400484 def do_get(self, path, prop):
Brad Bishop56ad87f2017-02-21 23:33:29 -0500485 name = request.route_data['name']
486 return request.route_data['obj'][path][name]
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500487
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600488 def do_put(self, path, prop, value=None, retry=True):
Brad Bishop87b63c12016-03-18 14:47:51 -0400489 if value is None:
490 value = request.parameter_list
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500491
Brad Bishop87b63c12016-03-18 14:47:51 -0400492 prop, iface, properties_iface = self.get_host_interface(
493 path, prop, request.route_data['map'][path])
494 try:
495 properties_iface.Set(iface, prop, value)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600496 except ValueError as e:
Brad Bishop87b63c12016-03-18 14:47:51 -0400497 abort(400, str(e))
CamVan Nguyen249d1322018-03-05 10:08:33 -0600498 except dbus.exceptions.DBusException as e:
Adriana Kobylaka8b05d12018-08-23 10:44:07 -0500499 if e.get_dbus_name() == DBUS_PROPERTY_READONLY:
500 abort(403, str(e))
Brad Bishopb7fca9b2018-01-23 12:16:50 -0500501 if e.get_dbus_name() == DBUS_INVALID_ARGS and retry:
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500502 bus_name = properties_iface.bus_name
503 expected_type = get_type_signature_by_introspection(self.bus,
504 bus_name,
505 path,
506 prop)
507 if not expected_type:
508 abort(403, "Failed to get expected type: %s" % str(e))
509 converted_value = None
510 try:
511 converted_value = convert_type(expected_type, value)
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500512 except Exception as ex:
513 abort(403, "Failed to convert %s to type %s" %
514 (value, expected_type))
Lei YU1eea5c32018-07-12 15:32:37 +0800515 try:
516 self.do_put(path, prop, converted_value, False)
517 return
518 except Exception as ex:
519 abort(403, str(ex))
520
Brad Bishop87b63c12016-03-18 14:47:51 -0400521 abort(403, str(e))
522 raise
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500523
Brad Bishop87b63c12016-03-18 14:47:51 -0400524 def get_host_interface(self, path, prop, bus_info):
CamVan Nguyen249d1322018-03-05 10:08:33 -0600525 for bus, interfaces in bus_info.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400526 obj = self.bus.get_object(bus, path, introspect=True)
527 properties_iface = dbus.Interface(
528 obj, dbus_interface=dbus.PROPERTIES_IFACE)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500529
Brad Bishop87b63c12016-03-18 14:47:51 -0400530 info = self.get_host_interface_on_bus(
531 path, prop, properties_iface, bus, interfaces)
532 if info is not None:
533 prop, iface = info
534 return prop, iface, properties_iface
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500535
Brad Bishop87b63c12016-03-18 14:47:51 -0400536 def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces):
537 for i in interfaces:
538 properties = self.try_properties_interface(iface.GetAll, i)
Brad Bishop69cb6d12017-02-21 12:01:52 -0500539 if not properties:
Brad Bishop87b63c12016-03-18 14:47:51 -0400540 continue
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500541 match = obmc.utils.misc.find_case_insensitive(
CamVan Nguyen249d1322018-03-05 10:08:33 -0600542 prop, list(properties.keys()))
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500543 if match is None:
Brad Bishop87b63c12016-03-18 14:47:51 -0400544 continue
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500545 prop = match
Brad Bishop87b63c12016-03-18 14:47:51 -0400546 return prop, i
547
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500548
Brad Bishop2503bd62015-12-16 17:56:12 -0500549class SchemaHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400550 verbs = ['GET']
551 rules = '<path:path>/schema'
Brad Bishop2503bd62015-12-16 17:56:12 -0500552
Brad Bishop87b63c12016-03-18 14:47:51 -0400553 def __init__(self, app, bus):
554 super(SchemaHandler, self).__init__(
Brad Bishop529029b2017-07-10 16:46:01 -0400555 app, bus, self.verbs, self.rules)
Brad Bishop2503bd62015-12-16 17:56:12 -0500556
Brad Bishop87b63c12016-03-18 14:47:51 -0400557 def find(self, path):
558 return self.try_mapper_call(
559 self.mapper.get_object,
560 path=path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500561
Brad Bishop87b63c12016-03-18 14:47:51 -0400562 def setup(self, path):
563 request.route_data['map'] = self.find(path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500564
Brad Bishop87b63c12016-03-18 14:47:51 -0400565 def do_get(self, path):
566 schema = {}
CamVan Nguyen249d1322018-03-05 10:08:33 -0600567 for x in request.route_data['map'].keys():
Brad Bishop87b63c12016-03-18 14:47:51 -0400568 obj = self.bus.get_object(x, path, introspect=False)
569 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
570 data = iface.Introspect()
571 parser = IntrospectionNodeParser(
572 ElementTree.fromstring(data))
CamVan Nguyen249d1322018-03-05 10:08:33 -0600573 for x, y in parser.get_interfaces().items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400574 schema[x] = y
Brad Bishop2503bd62015-12-16 17:56:12 -0500575
Brad Bishop87b63c12016-03-18 14:47:51 -0400576 return schema
577
Brad Bishop2503bd62015-12-16 17:56:12 -0500578
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500579class InstanceHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400580 verbs = ['GET', 'PUT', 'DELETE']
581 rules = '<path:path>'
582 request_type = dict
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500583
Brad Bishop87b63c12016-03-18 14:47:51 -0400584 def __init__(self, app, bus):
585 super(InstanceHandler, self).__init__(
Brad Bishop529029b2017-07-10 16:46:01 -0400586 app, bus, self.verbs, self.rules)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500587
Brad Bishop87b63c12016-03-18 14:47:51 -0400588 def find(self, path, callback=None):
589 return {path: self.try_mapper_call(
590 self.mapper.get_object,
591 callback,
592 path=path)}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500593
Brad Bishop87b63c12016-03-18 14:47:51 -0400594 def setup(self, path):
595 callback = None
596 if request.method == 'PUT':
597 def callback(e, **kw):
598 abort(403, _4034_msg % ('resource', 'created', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500599
Brad Bishop87b63c12016-03-18 14:47:51 -0400600 if request.route_data.get('map') is None:
601 request.route_data['map'] = self.find(path, callback)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500602
Brad Bishop87b63c12016-03-18 14:47:51 -0400603 def do_get(self, path):
Brad Bishop71527b42016-04-01 14:51:14 -0400604 return self.mapper.enumerate_object(
605 path,
606 mapper_data=request.route_data['map'])
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500607
Brad Bishop87b63c12016-03-18 14:47:51 -0400608 def do_put(self, path):
609 # make sure all properties exist in the request
610 obj = set(self.do_get(path).keys())
611 req = set(request.parameter_list.keys())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500612
Brad Bishop87b63c12016-03-18 14:47:51 -0400613 diff = list(obj.difference(req))
614 if diff:
615 abort(403, _4034_msg % (
616 'resource', 'removed', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500617
Brad Bishop87b63c12016-03-18 14:47:51 -0400618 diff = list(req.difference(obj))
619 if diff:
620 abort(403, _4034_msg % (
621 'resource', 'created', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500622
CamVan Nguyen249d1322018-03-05 10:08:33 -0600623 for p, v in request.parameter_list.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400624 self.app.property_handler.do_put(
625 path, p, v)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500626
Brad Bishop87b63c12016-03-18 14:47:51 -0400627 def do_delete(self, path):
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500628 deleted = False
629 for bus, interfaces in request.route_data['map'][path].items():
630 if self.bus_has_delete(interfaces):
631 self.delete_on_bus(path, bus)
632 deleted = True
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500633
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500634 #It's OK if some objects didn't have a Delete, but not all
635 if not deleted:
636 abort(403, _4034_msg % ('resource', 'removed', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500637
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500638 def bus_has_delete(self, interfaces):
639 return DELETE_IFACE in interfaces
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500640
Brad Bishop87b63c12016-03-18 14:47:51 -0400641 def delete_on_bus(self, path, bus):
642 obj = self.bus.get_object(bus, path, introspect=False)
643 delete_iface = dbus.Interface(
644 obj, dbus_interface=DELETE_IFACE)
645 delete_iface.Delete()
646
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500647
Brad Bishop2f428582015-12-02 10:56:11 -0500648class SessionHandler(MethodHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400649 ''' Handles the /login and /logout routes, manages
650 server side session store and session cookies. '''
Brad Bishop2f428582015-12-02 10:56:11 -0500651
Brad Bishop87b63c12016-03-18 14:47:51 -0400652 rules = ['/login', '/logout']
653 login_str = "User '%s' logged %s"
654 bad_passwd_str = "Invalid username or password"
655 no_user_str = "No user logged in"
656 bad_json_str = "Expecting request format { 'data': " \
657 "[<username>, <password>] }, got '%s'"
Alexander Filippovd08a4562018-03-20 12:02:23 +0300658 bmc_not_ready_str = "BMC is not ready (booting)"
Brad Bishop87b63c12016-03-18 14:47:51 -0400659 _require_auth = None
660 MAX_SESSIONS = 16
Alexander Filippovd08a4562018-03-20 12:02:23 +0300661 BMCSTATE_IFACE = 'xyz.openbmc_project.State.BMC'
662 BMCSTATE_PATH = '/xyz/openbmc_project/state/bmc0'
663 BMCSTATE_PROPERTY = 'CurrentBMCState'
664 BMCSTATE_READY = 'xyz.openbmc_project.State.BMC.BMCState.Ready'
Brad Bishop2f428582015-12-02 10:56:11 -0500665
Brad Bishop87b63c12016-03-18 14:47:51 -0400666 def __init__(self, app, bus):
667 super(SessionHandler, self).__init__(
668 app, bus)
669 self.hmac_key = os.urandom(128)
670 self.session_store = []
Brad Bishop2f428582015-12-02 10:56:11 -0500671
Brad Bishop87b63c12016-03-18 14:47:51 -0400672 @staticmethod
673 def authenticate(username, clear):
674 try:
675 encoded = spwd.getspnam(username)[1]
676 return encoded == crypt.crypt(clear, encoded)
677 except KeyError:
678 return False
Brad Bishop2f428582015-12-02 10:56:11 -0500679
Brad Bishop87b63c12016-03-18 14:47:51 -0400680 def invalidate_session(self, session):
681 try:
682 self.session_store.remove(session)
683 except ValueError:
684 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500685
Brad Bishop87b63c12016-03-18 14:47:51 -0400686 def new_session(self):
687 sid = os.urandom(32)
688 if self.MAX_SESSIONS <= len(self.session_store):
689 self.session_store.pop()
690 self.session_store.insert(0, {'sid': sid})
Brad Bishop2f428582015-12-02 10:56:11 -0500691
Brad Bishop87b63c12016-03-18 14:47:51 -0400692 return self.session_store[0]
Brad Bishop2f428582015-12-02 10:56:11 -0500693
Brad Bishop87b63c12016-03-18 14:47:51 -0400694 def get_session(self, sid):
695 sids = [x['sid'] for x in self.session_store]
696 try:
697 return self.session_store[sids.index(sid)]
698 except ValueError:
699 return None
Brad Bishop2f428582015-12-02 10:56:11 -0500700
Brad Bishop87b63c12016-03-18 14:47:51 -0400701 def get_session_from_cookie(self):
702 return self.get_session(
703 request.get_cookie(
704 'sid', secret=self.hmac_key))
Brad Bishop2f428582015-12-02 10:56:11 -0500705
Brad Bishop87b63c12016-03-18 14:47:51 -0400706 def do_post(self, **kw):
707 if request.path == '/login':
708 return self.do_login(**kw)
709 else:
710 return self.do_logout(**kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500711
Brad Bishop87b63c12016-03-18 14:47:51 -0400712 def do_logout(self, **kw):
713 session = self.get_session_from_cookie()
714 if session is not None:
715 user = session['user']
716 self.invalidate_session(session)
717 response.delete_cookie('sid')
718 return self.login_str % (user, 'out')
Brad Bishop2f428582015-12-02 10:56:11 -0500719
Brad Bishop87b63c12016-03-18 14:47:51 -0400720 return self.no_user_str
Brad Bishop2f428582015-12-02 10:56:11 -0500721
Brad Bishop87b63c12016-03-18 14:47:51 -0400722 def do_login(self, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -0400723 if len(request.parameter_list) != 2:
724 abort(400, self.bad_json_str % (request.json))
Brad Bishop2f428582015-12-02 10:56:11 -0500725
Brad Bishop87b63c12016-03-18 14:47:51 -0400726 if not self.authenticate(*request.parameter_list):
Brad Bishopdc3fbfa2016-09-08 09:51:38 -0400727 abort(401, self.bad_passwd_str)
Brad Bishop2f428582015-12-02 10:56:11 -0500728
Alexander Filippovd08a4562018-03-20 12:02:23 +0300729 force = False
730 try:
731 force = request.json.get('force')
732 except (ValueError, AttributeError, KeyError, TypeError):
733 force = False
734
735 if not force and not self.is_bmc_ready():
736 abort(503, self.bmc_not_ready_str)
737
Brad Bishop87b63c12016-03-18 14:47:51 -0400738 user = request.parameter_list[0]
739 session = self.new_session()
740 session['user'] = user
741 response.set_cookie(
742 'sid', session['sid'], secret=self.hmac_key,
743 secure=True,
744 httponly=True)
745 return self.login_str % (user, 'in')
Brad Bishop2f428582015-12-02 10:56:11 -0500746
Alexander Filippovd08a4562018-03-20 12:02:23 +0300747 def is_bmc_ready(self):
748 if not self.app.with_bmc_check:
749 return True
750
751 try:
752 obj = self.bus.get_object(self.BMCSTATE_IFACE, self.BMCSTATE_PATH)
753 iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE)
754 state = iface.Get(self.BMCSTATE_IFACE, self.BMCSTATE_PROPERTY)
755 if state == self.BMCSTATE_READY:
756 return True
757
758 except dbus.exceptions.DBusException:
759 pass
760
761 return False
762
Brad Bishop87b63c12016-03-18 14:47:51 -0400763 def find(self, **kw):
764 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500765
Brad Bishop87b63c12016-03-18 14:47:51 -0400766 def setup(self, **kw):
767 pass
768
Brad Bishop2f428582015-12-02 10:56:11 -0500769
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500770class ImageUploadUtils:
771 ''' Provides common utils for image upload. '''
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500772
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500773 file_loc = '/tmp/images'
774 file_prefix = 'img'
775 file_suffix = ''
Adriana Kobylak53693892018-03-12 13:05:50 -0500776 signal = None
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500777
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500778 @classmethod
779 def do_upload(cls, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -0500780 def cleanup():
781 os.close(handle)
782 if cls.signal:
783 cls.signal.remove()
784 cls.signal = None
785
786 def signal_callback(path, a, **kw):
787 # Just interested on the first Version interface created which is
788 # triggered when the file is uploaded. This helps avoid getting the
789 # wrong information for multiple upload requests in a row.
790 if "xyz.openbmc_project.Software.Version" in a and \
791 "xyz.openbmc_project.Software.Activation" not in a:
792 paths.append(path)
793
794 while cls.signal:
795 # Serialize uploads by waiting for the signal to be cleared.
796 # This makes it easier to ensure that the version information
797 # is the right one instead of the data from another upload request.
798 gevent.sleep(1)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500799 if not os.path.exists(cls.file_loc):
Gunnar Millsfb515792017-11-09 15:52:17 -0600800 abort(500, "Error Directory not found")
Adriana Kobylak53693892018-03-12 13:05:50 -0500801 paths = []
802 bus = dbus.SystemBus()
803 cls.signal = bus.add_signal_receiver(
804 signal_callback,
805 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
806 signal_name='InterfacesAdded',
807 path=SOFTWARE_PATH)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500808 if not filename:
809 handle, filename = tempfile.mkstemp(cls.file_suffix,
810 cls.file_prefix, cls.file_loc)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500811 else:
812 filename = os.path.join(cls.file_loc, filename)
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500813 handle = os.open(filename, os.O_WRONLY | os.O_CREAT)
Leonel Gonzalez0b62edf2017-06-08 15:10:03 -0500814 try:
815 file_contents = request.body.read()
816 request.body.close()
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500817 os.write(handle, file_contents)
Adriana Kobylak53693892018-03-12 13:05:50 -0500818 # Close file after writing, the image manager process watches for
819 # the close event to know the upload is complete.
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500820 os.close(handle)
Adriana Kobylak53693892018-03-12 13:05:50 -0500821 except (IOError, ValueError) as e:
822 cleanup()
823 abort(400, str(e))
824 except Exception:
825 cleanup()
826 abort(400, "Unexpected Error")
827 loop = gobject.MainLoop()
828 gcontext = loop.get_context()
829 count = 0
830 version_id = ''
831 while loop is not None:
832 try:
833 if gcontext.pending():
834 gcontext.iteration()
835 if not paths:
836 gevent.sleep(1)
837 else:
838 version_id = os.path.basename(paths.pop())
839 break
840 count += 1
841 if count == 10:
842 break
843 except Exception:
844 break
845 cls.signal.remove()
846 cls.signal = None
Adriana Kobylak97fe4352018-04-10 10:44:11 -0500847 if version_id:
848 return version_id
849 else:
850 abort(400, "Version already exists or failed to be extracted")
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500851
852
853class ImagePostHandler(RouteHandler):
854 ''' Handles the /upload/image route. '''
855
856 verbs = ['POST']
857 rules = ['/upload/image']
858 content_type = 'application/octet-stream'
859
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500860 def __init__(self, app, bus):
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500861 super(ImagePostHandler, self).__init__(
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500862 app, bus, self.verbs, self.rules, self.content_type)
863
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500864 def do_post(self, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -0500865 return ImageUploadUtils.do_upload()
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500866
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500867 def find(self, **kw):
868 pass
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500869
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500870 def setup(self, **kw):
871 pass
872
873
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500874class EventNotifier:
875 keyNames = {}
876 keyNames['event'] = 'event'
877 keyNames['path'] = 'path'
878 keyNames['intfMap'] = 'interfaces'
879 keyNames['propMap'] = 'properties'
880 keyNames['intf'] = 'interface'
881
882 def __init__(self, wsock, filters):
883 self.wsock = wsock
884 self.paths = filters.get("paths", [])
885 self.interfaces = filters.get("interfaces", [])
886 if not self.paths:
887 self.paths.append(None)
888 bus = dbus.SystemBus()
889 # Add a signal receiver for every path the client is interested in
890 for path in self.paths:
891 bus.add_signal_receiver(
892 self.interfaces_added_handler,
893 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
894 signal_name='InterfacesAdded',
895 path=path)
896 bus.add_signal_receiver(
897 self.properties_changed_handler,
898 dbus_interface=dbus.PROPERTIES_IFACE,
899 signal_name='PropertiesChanged',
900 path=path,
901 path_keyword='path')
902 loop = gobject.MainLoop()
903 # gobject's mainloop.run() will block the entire process, so the gevent
904 # scheduler and hence greenlets won't execute. The while-loop below
905 # works around this limitation by using gevent's sleep, instead of
906 # calling loop.run()
907 gcontext = loop.get_context()
908 while loop is not None:
909 try:
910 if gcontext.pending():
911 gcontext.iteration()
912 else:
913 # gevent.sleep puts only the current greenlet to sleep,
914 # not the entire process.
915 gevent.sleep(5)
916 except WebSocketError:
917 break
918
919 def interfaces_added_handler(self, path, iprops, **kw):
920 ''' If the client is interested in these changes, respond to the
921 client. This handles d-bus interface additions.'''
922 if (not self.interfaces) or \
923 (not set(iprops).isdisjoint(self.interfaces)):
924 response = {}
925 response[self.keyNames['event']] = "InterfacesAdded"
926 response[self.keyNames['path']] = path
927 response[self.keyNames['intfMap']] = iprops
928 try:
929 self.wsock.send(json.dumps(response))
930 except WebSocketError:
931 return
932
933 def properties_changed_handler(self, interface, new, old, **kw):
934 ''' If the client is interested in these changes, respond to the
935 client. This handles d-bus property changes. '''
936 if (not self.interfaces) or (interface in self.interfaces):
937 path = str(kw['path'])
938 response = {}
939 response[self.keyNames['event']] = "PropertiesChanged"
940 response[self.keyNames['path']] = path
941 response[self.keyNames['intf']] = interface
942 response[self.keyNames['propMap']] = new
943 try:
944 self.wsock.send(json.dumps(response))
945 except WebSocketError:
946 return
947
948
Deepak Kodihallib209dd12017-10-11 01:19:17 -0500949class EventHandler(RouteHandler):
950 ''' Handles the /subscribe route, for clients to be able
951 to subscribe to BMC events. '''
952
953 verbs = ['GET']
954 rules = ['/subscribe']
955
956 def __init__(self, app, bus):
957 super(EventHandler, self).__init__(
958 app, bus, self.verbs, self.rules)
959
960 def find(self, **kw):
961 pass
962
963 def setup(self, **kw):
964 pass
965
966 def do_get(self):
967 wsock = request.environ.get('wsgi.websocket')
968 if not wsock:
969 abort(400, 'Expected WebSocket request.')
Jayashankar Padathbec10c22018-05-29 18:22:59 +0530970 ping_sender = Greenlet.spawn(send_ws_ping, wsock, WEBSOCKET_TIMEOUT)
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500971 filters = wsock.receive()
972 filters = json.loads(filters)
973 notifier = EventNotifier(wsock, filters)
Deepak Kodihallib209dd12017-10-11 01:19:17 -0500974
Deepak Kodihalli5c518f62018-04-23 03:26:38 -0500975class HostConsoleHandler(RouteHandler):
976 ''' Handles the /console route, for clients to be able
977 read/write the host serial console. The way this is
978 done is by exposing a websocket that's mirrored to an
979 abstract UNIX domain socket, which is the source for
980 the console data. '''
981
982 verbs = ['GET']
983 # Naming the route console0, because the numbering will help
984 # on multi-bmc/multi-host systems.
985 rules = ['/console0']
986
987 def __init__(self, app, bus):
988 super(HostConsoleHandler, self).__init__(
989 app, bus, self.verbs, self.rules)
990
991 def find(self, **kw):
992 pass
993
994 def setup(self, **kw):
995 pass
996
997 def read_wsock(self, wsock, sock):
998 while True:
999 try:
1000 incoming = wsock.receive()
1001 if incoming:
1002 # Read websocket, write to UNIX socket
1003 sock.send(incoming)
1004 except Exception as e:
1005 sock.close()
1006 return
1007
1008 def read_sock(self, sock, wsock):
1009 max_sock_read_len = 4096
1010 while True:
1011 try:
1012 outgoing = sock.recv(max_sock_read_len)
1013 if outgoing:
1014 # Read UNIX socket, write to websocket
1015 wsock.send(outgoing)
1016 except Exception as e:
1017 wsock.close()
1018 return
1019
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001020 def do_get(self):
1021 wsock = request.environ.get('wsgi.websocket')
1022 if not wsock:
1023 abort(400, 'Expected WebSocket based request.')
1024
1025 # A UNIX domain socket structure defines a 108-byte pathname. The
1026 # server in this case, obmc-console-server, expects a 108-byte path.
1027 socket_name = "\0obmc-console"
1028 trailing_bytes = "\0" * (108 - len(socket_name))
1029 socket_path = socket_name + trailing_bytes
1030 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1031
1032 try:
1033 sock.connect(socket_path)
1034 except Exception as e:
1035 abort(500, str(e))
1036
1037 wsock_reader = Greenlet.spawn(self.read_wsock, wsock, sock)
1038 sock_reader = Greenlet.spawn(self.read_sock, sock, wsock)
Jayashankar Padathbec10c22018-05-29 18:22:59 +05301039 ping_sender = Greenlet.spawn(send_ws_ping, wsock, WEBSOCKET_TIMEOUT)
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001040 gevent.joinall([wsock_reader, sock_reader, ping_sender])
1041
1042
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001043class ImagePutHandler(RouteHandler):
1044 ''' Handles the /upload/image/<filename> route. '''
1045
1046 verbs = ['PUT']
1047 rules = ['/upload/image/<filename>']
1048 content_type = 'application/octet-stream'
1049
1050 def __init__(self, app, bus):
1051 super(ImagePutHandler, self).__init__(
1052 app, bus, self.verbs, self.rules, self.content_type)
1053
1054 def do_put(self, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -05001055 return ImageUploadUtils.do_upload(filename)
Deepak Kodihalli1af301a2017-04-11 07:29:01 -05001056
1057 def find(self, **kw):
1058 pass
1059
1060 def setup(self, **kw):
1061 pass
1062
1063
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001064class DownloadDumpHandler(RouteHandler):
1065 ''' Handles the /download/dump route. '''
1066
1067 verbs = 'GET'
1068 rules = ['/download/dump/<dumpid>']
1069 content_type = 'application/octet-stream'
Jayanth Othayoth18c3a242017-08-02 08:16:11 -05001070 dump_loc = '/var/lib/phosphor-debug-collector/dumps'
Brad Bishop944cd042017-07-10 16:42:41 -04001071 suppress_json_resp = True
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001072
1073 def __init__(self, app, bus):
1074 super(DownloadDumpHandler, self).__init__(
1075 app, bus, self.verbs, self.rules, self.content_type)
1076
1077 def do_get(self, dumpid):
1078 return self.do_download(dumpid)
1079
1080 def find(self, **kw):
1081 pass
1082
1083 def setup(self, **kw):
1084 pass
1085
1086 def do_download(self, dumpid):
1087 dump_loc = os.path.join(self.dump_loc, dumpid)
1088 if not os.path.exists(dump_loc):
1089 abort(404, "Path not found")
1090
1091 files = os.listdir(dump_loc)
1092 num_files = len(files)
1093 if num_files == 0:
1094 abort(404, "Dump not found")
1095
1096 return static_file(os.path.basename(files[0]), root=dump_loc,
1097 download=True, mimetype=self.content_type)
1098
1099
Matt Spinlerd41643e2018-02-02 13:51:38 -06001100class WebHandler(RouteHandler):
1101 ''' Handles the routes for the web UI files. '''
1102
1103 verbs = 'GET'
1104
1105 # Match only what we know are web files, so everything else
1106 # can get routed to the REST handlers.
1107 rules = ['//', '/<filename:re:.+\.js>', '/<filename:re:.+\.svg>',
1108 '/<filename:re:.+\.css>', '/<filename:re:.+\.ttf>',
1109 '/<filename:re:.+\.eot>', '/<filename:re:.+\.woff>',
1110 '/<filename:re:.+\.woff2>', '/<filename:re:.+\.map>',
1111 '/<filename:re:.+\.png>', '/<filename:re:.+\.html>',
1112 '/<filename:re:.+\.ico>']
1113
1114 # The mimetypes module knows about most types, but not these
1115 content_types = {
1116 '.eot': 'application/vnd.ms-fontobject',
1117 '.woff': 'application/x-font-woff',
1118 '.woff2': 'application/x-font-woff2',
1119 '.ttf': 'application/x-font-ttf',
1120 '.map': 'application/json'
1121 }
1122
1123 _require_auth = None
1124 suppress_json_resp = True
1125
1126 def __init__(self, app, bus):
1127 super(WebHandler, self).__init__(
1128 app, bus, self.verbs, self.rules)
1129
1130 def get_type(self, filename):
1131 ''' Returns the content type and encoding for a file '''
1132
1133 content_type, encoding = mimetypes.guess_type(filename)
1134
1135 # Try our own list if mimetypes didn't recognize it
1136 if content_type is None:
1137 if filename[-3:] == '.gz':
1138 filename = filename[:-3]
1139 extension = filename[filename.rfind('.'):]
1140 content_type = self.content_types.get(extension, None)
1141
1142 return content_type, encoding
1143
1144 def do_get(self, filename='index.html'):
1145
1146 # If a gzipped version exists, use that instead.
1147 # Possible future enhancement: if the client doesn't
1148 # accept compressed files, unzip it ourselves before sending.
1149 if not os.path.exists(os.path.join(www_base_path, filename)):
1150 filename = filename + '.gz'
1151
1152 # Though bottle should protect us, ensure path is valid
1153 realpath = os.path.realpath(filename)
1154 if realpath[0] == '/':
1155 realpath = realpath[1:]
1156 if not os.path.exists(os.path.join(www_base_path, realpath)):
1157 abort(404, "Path not found")
1158
1159 mimetype, encoding = self.get_type(filename)
1160
1161 # Couldn't find the type - let static_file() deal with it,
1162 # though this should never happen.
1163 if mimetype is None:
1164 print("Can't figure out content-type for %s" % filename)
1165 mimetype = 'auto'
1166
1167 # This call will set several header fields for us,
1168 # including the charset if the type is text.
1169 response = static_file(filename, www_base_path, mimetype)
1170
1171 # static_file() will only set the encoding if the
1172 # mimetype was auto, so set it here.
1173 if encoding is not None:
1174 response.set_header('Content-Encoding', encoding)
1175
1176 return response
1177
1178 def find(self, **kw):
1179 pass
1180
1181 def setup(self, **kw):
1182 pass
1183
1184
Brad Bishop2f428582015-12-02 10:56:11 -05001185class AuthorizationPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001186 ''' Invokes an optional list of authorization callbacks. '''
Brad Bishop2f428582015-12-02 10:56:11 -05001187
Brad Bishop87b63c12016-03-18 14:47:51 -04001188 name = 'authorization'
1189 api = 2
Brad Bishop2f428582015-12-02 10:56:11 -05001190
Brad Bishop87b63c12016-03-18 14:47:51 -04001191 class Compose:
1192 def __init__(self, validators, callback, session_mgr):
1193 self.validators = validators
1194 self.callback = callback
1195 self.session_mgr = session_mgr
Brad Bishop2f428582015-12-02 10:56:11 -05001196
Brad Bishop87b63c12016-03-18 14:47:51 -04001197 def __call__(self, *a, **kw):
1198 sid = request.get_cookie('sid', secret=self.session_mgr.hmac_key)
1199 session = self.session_mgr.get_session(sid)
Brad Bishopd4c1c552017-02-21 00:07:28 -05001200 if request.method != 'OPTIONS':
1201 for x in self.validators:
1202 x(session, *a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -05001203
Brad Bishop87b63c12016-03-18 14:47:51 -04001204 return self.callback(*a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -05001205
Brad Bishop87b63c12016-03-18 14:47:51 -04001206 def apply(self, callback, route):
1207 undecorated = route.get_undecorated_callback()
1208 if not isinstance(undecorated, RouteHandler):
1209 return callback
Brad Bishop2f428582015-12-02 10:56:11 -05001210
Brad Bishop87b63c12016-03-18 14:47:51 -04001211 auth_types = getattr(
1212 undecorated, '_require_auth', None)
1213 if not auth_types:
1214 return callback
Brad Bishop2f428582015-12-02 10:56:11 -05001215
Brad Bishop87b63c12016-03-18 14:47:51 -04001216 return self.Compose(
1217 auth_types, callback, undecorated.app.session_handler)
1218
Brad Bishop2f428582015-12-02 10:56:11 -05001219
Brad Bishopd0c404a2017-02-21 09:23:25 -05001220class CorsPlugin(object):
1221 ''' Add CORS headers. '''
1222
1223 name = 'cors'
1224 api = 2
1225
1226 @staticmethod
1227 def process_origin():
1228 origin = request.headers.get('Origin')
1229 if origin:
1230 response.add_header('Access-Control-Allow-Origin', origin)
1231 response.add_header(
1232 'Access-Control-Allow-Credentials', 'true')
1233
1234 @staticmethod
1235 def process_method_and_headers(verbs):
1236 method = request.headers.get('Access-Control-Request-Method')
1237 headers = request.headers.get('Access-Control-Request-Headers')
1238 if headers:
1239 headers = [x.lower() for x in headers.split(',')]
1240
1241 if method in verbs \
1242 and headers == ['content-type']:
1243 response.add_header('Access-Control-Allow-Methods', method)
1244 response.add_header(
1245 'Access-Control-Allow-Headers', 'Content-Type')
Ratan Gupta91b46f82018-01-14 12:52:23 +05301246 response.add_header('X-Frame-Options', 'deny')
1247 response.add_header('X-Content-Type-Options', 'nosniff')
1248 response.add_header('X-XSS-Protection', '1; mode=block')
1249 response.add_header(
1250 'Content-Security-Policy', "default-src 'self'")
1251 response.add_header(
1252 'Strict-Transport-Security',
1253 'max-age=31536000; includeSubDomains; preload')
Brad Bishopd0c404a2017-02-21 09:23:25 -05001254
1255 def __init__(self, app):
1256 app.install_error_callback(self.error_callback)
1257
1258 def apply(self, callback, route):
1259 undecorated = route.get_undecorated_callback()
1260 if not isinstance(undecorated, RouteHandler):
1261 return callback
1262
1263 if not getattr(undecorated, '_enable_cors', None):
1264 return callback
1265
1266 def wrap(*a, **kw):
1267 self.process_origin()
1268 self.process_method_and_headers(undecorated._verbs)
1269 return callback(*a, **kw)
1270
1271 return wrap
1272
1273 def error_callback(self, **kw):
1274 self.process_origin()
1275
1276
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001277class JsonApiRequestPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001278 ''' Ensures request content satisfies the OpenBMC json api format. '''
1279 name = 'json_api_request'
1280 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001281
Brad Bishop87b63c12016-03-18 14:47:51 -04001282 error_str = "Expecting request format { 'data': <value> }, got '%s'"
1283 type_error_str = "Unsupported Content-Type: '%s'"
1284 json_type = "application/json"
1285 request_methods = ['PUT', 'POST', 'PATCH']
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001286
Brad Bishop87b63c12016-03-18 14:47:51 -04001287 @staticmethod
1288 def content_expected():
1289 return request.method in JsonApiRequestPlugin.request_methods
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001290
Brad Bishop87b63c12016-03-18 14:47:51 -04001291 def validate_request(self):
1292 if request.content_length > 0 and \
1293 request.content_type != self.json_type:
1294 abort(415, self.type_error_str % request.content_type)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001295
Brad Bishop87b63c12016-03-18 14:47:51 -04001296 try:
1297 request.parameter_list = request.json.get('data')
CamVan Nguyen249d1322018-03-05 10:08:33 -06001298 except ValueError as e:
Brad Bishop87b63c12016-03-18 14:47:51 -04001299 abort(400, str(e))
1300 except (AttributeError, KeyError, TypeError):
1301 abort(400, self.error_str % request.json)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001302
Brad Bishop87b63c12016-03-18 14:47:51 -04001303 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001304 content_type = getattr(
1305 route.get_undecorated_callback(), '_content_type', None)
1306 if self.json_type != content_type:
1307 return callback
1308
Brad Bishop87b63c12016-03-18 14:47:51 -04001309 verbs = getattr(
1310 route.get_undecorated_callback(), '_verbs', None)
1311 if verbs is None:
1312 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001313
Brad Bishop87b63c12016-03-18 14:47:51 -04001314 if not set(self.request_methods).intersection(verbs):
1315 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001316
Brad Bishop87b63c12016-03-18 14:47:51 -04001317 def wrap(*a, **kw):
1318 if self.content_expected():
1319 self.validate_request()
1320 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001321
Brad Bishop87b63c12016-03-18 14:47:51 -04001322 return wrap
1323
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001324
1325class JsonApiRequestTypePlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001326 ''' Ensures request content type satisfies the OpenBMC json api format. '''
1327 name = 'json_api_method_request'
1328 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001329
Brad Bishop87b63c12016-03-18 14:47:51 -04001330 error_str = "Expecting request format { 'data': %s }, got '%s'"
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001331 json_type = "application/json"
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001332
Brad Bishop87b63c12016-03-18 14:47:51 -04001333 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001334 content_type = getattr(
1335 route.get_undecorated_callback(), '_content_type', None)
1336 if self.json_type != content_type:
1337 return callback
1338
Brad Bishop87b63c12016-03-18 14:47:51 -04001339 request_type = getattr(
1340 route.get_undecorated_callback(), 'request_type', None)
1341 if request_type is None:
1342 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001343
Brad Bishop87b63c12016-03-18 14:47:51 -04001344 def validate_request():
1345 if not isinstance(request.parameter_list, request_type):
1346 abort(400, self.error_str % (str(request_type), request.json))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001347
Brad Bishop87b63c12016-03-18 14:47:51 -04001348 def wrap(*a, **kw):
1349 if JsonApiRequestPlugin.content_expected():
1350 validate_request()
1351 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001352
Brad Bishop87b63c12016-03-18 14:47:51 -04001353 return wrap
1354
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001355
Brad Bishop080a48e2017-02-21 22:34:43 -05001356class JsonErrorsPlugin(JSONPlugin):
1357 ''' Extend the Bottle JSONPlugin such that it also encodes error
1358 responses. '''
1359
1360 def __init__(self, app, **kw):
1361 super(JsonErrorsPlugin, self).__init__(**kw)
1362 self.json_opts = {
CamVan Nguyen249d1322018-03-05 10:08:33 -06001363 x: y for x, y in kw.items()
Brad Bishop080a48e2017-02-21 22:34:43 -05001364 if x in ['indent', 'sort_keys']}
1365 app.install_error_callback(self.error_callback)
1366
1367 def error_callback(self, response_object, response_body, **kw):
1368 response_body['body'] = json.dumps(response_object, **self.json_opts)
1369 response.content_type = 'application/json'
1370
1371
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001372class JsonApiResponsePlugin(object):
Brad Bishop080a48e2017-02-21 22:34:43 -05001373 ''' Emits responses in the OpenBMC json api format. '''
Brad Bishop87b63c12016-03-18 14:47:51 -04001374 name = 'json_api_response'
1375 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001376
Brad Bishopd4c1c552017-02-21 00:07:28 -05001377 @staticmethod
1378 def has_body():
1379 return request.method not in ['OPTIONS']
1380
Brad Bishop080a48e2017-02-21 22:34:43 -05001381 def __init__(self, app):
1382 app.install_error_callback(self.error_callback)
1383
Matt Spinler6691e7c2018-06-25 14:11:58 -05001384 @staticmethod
1385 def dbus_boolean_to_bool(data):
1386 ''' Convert all dbus.Booleans to true/false instead of 1/0 as
1387 the JSON encoder thinks they're ints. Note that unlike
1388 dicts and lists, tuples (from a dbus.Struct) are immutable
1389 so they need special handling. '''
1390
1391 def walkdict(data):
1392 for key, value in data.items():
1393 if isinstance(value, dbus.Boolean):
1394 data[key] = bool(value)
1395 elif isinstance(value, tuple):
1396 data[key] = walktuple(value)
1397 else:
1398 JsonApiResponsePlugin.dbus_boolean_to_bool(value)
1399
1400 def walklist(data):
1401 for i in range(len(data)):
1402 if isinstance(data[i], dbus.Boolean):
1403 data[i] = bool(data[i])
1404 elif isinstance(data[i], tuple):
1405 data[i] = walktuple(data[i])
1406 else:
1407 JsonApiResponsePlugin.dbus_boolean_to_bool(data[i])
1408
1409 def walktuple(data):
1410 new = []
1411 for item in data:
1412 if isinstance(item, dbus.Boolean):
1413 item = bool(item)
1414 else:
1415 JsonApiResponsePlugin.dbus_boolean_to_bool(item)
1416 new.append(item)
1417 return tuple(new)
1418
1419 if isinstance(data, dict):
1420 walkdict(data)
1421 elif isinstance(data, list):
1422 walklist(data)
1423
Brad Bishop87b63c12016-03-18 14:47:51 -04001424 def apply(self, callback, route):
Brad Bishop944cd042017-07-10 16:42:41 -04001425 skip = getattr(
1426 route.get_undecorated_callback(), 'suppress_json_resp', None)
1427 if skip:
Jayanth Othayoth1444fd82017-06-29 05:45:07 -05001428 return callback
1429
Brad Bishop87b63c12016-03-18 14:47:51 -04001430 def wrap(*a, **kw):
Brad Bishopd4c1c552017-02-21 00:07:28 -05001431 data = callback(*a, **kw)
Matt Spinler6691e7c2018-06-25 14:11:58 -05001432 JsonApiResponsePlugin.dbus_boolean_to_bool(data)
Brad Bishopd4c1c552017-02-21 00:07:28 -05001433 if self.has_body():
1434 resp = {'data': data}
1435 resp['status'] = 'ok'
1436 resp['message'] = response.status_line
1437 return resp
Brad Bishop87b63c12016-03-18 14:47:51 -04001438 return wrap
1439
Brad Bishop080a48e2017-02-21 22:34:43 -05001440 def error_callback(self, error, response_object, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -04001441 response_object['message'] = error.status_line
Brad Bishop9c2531e2017-03-07 10:22:40 -05001442 response_object['status'] = 'error'
Brad Bishop080a48e2017-02-21 22:34:43 -05001443 response_object.setdefault('data', {})['description'] = str(error.body)
Brad Bishop87b63c12016-03-18 14:47:51 -04001444 if error.status_code == 500:
1445 response_object['data']['exception'] = repr(error.exception)
1446 response_object['data']['traceback'] = error.traceback.splitlines()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001447
Brad Bishop87b63c12016-03-18 14:47:51 -04001448
Brad Bishop080a48e2017-02-21 22:34:43 -05001449class JsonpPlugin(object):
Brad Bishop80fe37a2016-03-29 10:54:54 -04001450 ''' Json javascript wrapper. '''
1451 name = 'jsonp'
1452 api = 2
1453
Brad Bishop080a48e2017-02-21 22:34:43 -05001454 def __init__(self, app, **kw):
1455 app.install_error_callback(self.error_callback)
Brad Bishop80fe37a2016-03-29 10:54:54 -04001456
1457 @staticmethod
1458 def to_jsonp(json):
1459 jwrapper = request.query.callback or None
1460 if(jwrapper):
1461 response.set_header('Content-Type', 'application/javascript')
1462 json = jwrapper + '(' + json + ');'
1463 return json
1464
1465 def apply(self, callback, route):
1466 def wrap(*a, **kw):
1467 return self.to_jsonp(callback(*a, **kw))
1468 return wrap
1469
Brad Bishop080a48e2017-02-21 22:34:43 -05001470 def error_callback(self, response_body, **kw):
1471 response_body['body'] = self.to_jsonp(response_body['body'])
Brad Bishop80fe37a2016-03-29 10:54:54 -04001472
1473
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001474class ContentCheckerPlugin(object):
1475 ''' Ensures that a route is associated with the expected content-type
1476 header. '''
1477 name = 'content_checker'
1478 api = 2
1479
1480 class Checker:
1481 def __init__(self, type, callback):
1482 self.expected_type = type
1483 self.callback = callback
1484 self.error_str = "Expecting content type '%s', got '%s'"
1485
1486 def __call__(self, *a, **kw):
Deepak Kodihallidb1a21e2017-04-27 06:30:11 -05001487 if request.method in ['PUT', 'POST', 'PATCH'] and \
1488 self.expected_type and \
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001489 self.expected_type != request.content_type:
1490 abort(415, self.error_str % (self.expected_type,
1491 request.content_type))
1492
1493 return self.callback(*a, **kw)
1494
1495 def apply(self, callback, route):
1496 content_type = getattr(
1497 route.get_undecorated_callback(), '_content_type', None)
1498
1499 return self.Checker(content_type, callback)
1500
1501
Brad Bishop2c6fc762016-08-29 15:53:25 -04001502class App(Bottle):
Deepak Kodihalli0fe213f2017-10-11 00:08:48 -05001503 def __init__(self, **kw):
Brad Bishop2c6fc762016-08-29 15:53:25 -04001504 super(App, self).__init__(autojson=False)
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001505
1506 self.have_wsock = kw.get('have_wsock', False)
Alexander Filippovd08a4562018-03-20 12:02:23 +03001507 self.with_bmc_check = '--with-bmc-check' in sys.argv
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001508
Brad Bishop2ddfa002016-08-29 15:11:55 -04001509 self.bus = dbus.SystemBus()
1510 self.mapper = obmc.mapper.Mapper(self.bus)
Brad Bishop080a48e2017-02-21 22:34:43 -05001511 self.error_callbacks = []
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001512
Brad Bishop87b63c12016-03-18 14:47:51 -04001513 self.install_hooks()
1514 self.install_plugins()
1515 self.create_handlers()
1516 self.install_handlers()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001517
Brad Bishop87b63c12016-03-18 14:47:51 -04001518 def install_plugins(self):
1519 # install json api plugins
1520 json_kw = {'indent': 2, 'sort_keys': True}
Brad Bishop87b63c12016-03-18 14:47:51 -04001521 self.install(AuthorizationPlugin())
Brad Bishopd0c404a2017-02-21 09:23:25 -05001522 self.install(CorsPlugin(self))
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001523 self.install(ContentCheckerPlugin())
Brad Bishop080a48e2017-02-21 22:34:43 -05001524 self.install(JsonpPlugin(self, **json_kw))
1525 self.install(JsonErrorsPlugin(self, **json_kw))
1526 self.install(JsonApiResponsePlugin(self))
Brad Bishop87b63c12016-03-18 14:47:51 -04001527 self.install(JsonApiRequestPlugin())
1528 self.install(JsonApiRequestTypePlugin())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001529
Brad Bishop87b63c12016-03-18 14:47:51 -04001530 def install_hooks(self):
Brad Bishop080a48e2017-02-21 22:34:43 -05001531 self.error_handler_type = type(self.default_error_handler)
1532 self.original_error_handler = self.default_error_handler
1533 self.default_error_handler = self.error_handler_type(
1534 self.custom_error_handler, self, Bottle)
1535
Brad Bishop87b63c12016-03-18 14:47:51 -04001536 self.real_router_match = self.router.match
1537 self.router.match = self.custom_router_match
1538 self.add_hook('before_request', self.strip_extra_slashes)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001539
Brad Bishop87b63c12016-03-18 14:47:51 -04001540 def create_handlers(self):
1541 # create route handlers
1542 self.session_handler = SessionHandler(self, self.bus)
Matt Spinlerd41643e2018-02-02 13:51:38 -06001543 self.web_handler = WebHandler(self, self.bus)
Brad Bishop87b63c12016-03-18 14:47:51 -04001544 self.directory_handler = DirectoryHandler(self, self.bus)
1545 self.list_names_handler = ListNamesHandler(self, self.bus)
1546 self.list_handler = ListHandler(self, self.bus)
1547 self.method_handler = MethodHandler(self, self.bus)
1548 self.property_handler = PropertyHandler(self, self.bus)
1549 self.schema_handler = SchemaHandler(self, self.bus)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001550 self.image_upload_post_handler = ImagePostHandler(self, self.bus)
1551 self.image_upload_put_handler = ImagePutHandler(self, self.bus)
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001552 self.download_dump_get_handler = DownloadDumpHandler(self, self.bus)
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001553 if self.have_wsock:
1554 self.event_handler = EventHandler(self, self.bus)
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001555 self.host_console_handler = HostConsoleHandler(self, self.bus)
Brad Bishop87b63c12016-03-18 14:47:51 -04001556 self.instance_handler = InstanceHandler(self, self.bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001557
Brad Bishop87b63c12016-03-18 14:47:51 -04001558 def install_handlers(self):
1559 self.session_handler.install()
Matt Spinlerd41643e2018-02-02 13:51:38 -06001560 self.web_handler.install()
Brad Bishop87b63c12016-03-18 14:47:51 -04001561 self.directory_handler.install()
1562 self.list_names_handler.install()
1563 self.list_handler.install()
1564 self.method_handler.install()
1565 self.property_handler.install()
1566 self.schema_handler.install()
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001567 self.image_upload_post_handler.install()
1568 self.image_upload_put_handler.install()
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001569 self.download_dump_get_handler.install()
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001570 if self.have_wsock:
1571 self.event_handler.install()
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001572 self.host_console_handler.install()
Brad Bishop87b63c12016-03-18 14:47:51 -04001573 # this has to come last, since it matches everything
1574 self.instance_handler.install()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001575
Brad Bishop080a48e2017-02-21 22:34:43 -05001576 def install_error_callback(self, callback):
1577 self.error_callbacks.insert(0, callback)
1578
Brad Bishop87b63c12016-03-18 14:47:51 -04001579 def custom_router_match(self, environ):
1580 ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is
1581 needed doesn't work for us since the instance rules match
1582 everything. This monkey-patch lets the route handler figure
1583 out which response is needed. This could be accomplished
1584 with a hook but that would require calling the router match
1585 function twice.
1586 '''
1587 route, args = self.real_router_match(environ)
1588 if isinstance(route.callback, RouteHandler):
1589 route.callback._setup(**args)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001590
Brad Bishop87b63c12016-03-18 14:47:51 -04001591 return route, args
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001592
Brad Bishop080a48e2017-02-21 22:34:43 -05001593 def custom_error_handler(self, res, error):
Gunnar Millsf01d0ba2017-10-25 20:37:24 -05001594 ''' Allow plugins to modify error responses too via this custom
Brad Bishop080a48e2017-02-21 22:34:43 -05001595 error handler. '''
1596
1597 response_object = {}
1598 response_body = {}
1599 for x in self.error_callbacks:
1600 x(error=error,
1601 response_object=response_object,
1602 response_body=response_body)
1603
1604 return response_body.get('body', "")
1605
Brad Bishop87b63c12016-03-18 14:47:51 -04001606 @staticmethod
1607 def strip_extra_slashes():
1608 path = request.environ['PATH_INFO']
1609 trailing = ("", "/")[path[-1] == '/']
CamVan Nguyen249d1322018-03-05 10:08:33 -06001610 parts = list(filter(bool, path.split('/')))
Brad Bishop87b63c12016-03-18 14:47:51 -04001611 request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing