blob: f92a67a3fed4acf96de746e76a6931c276e5d2d8 [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'
53DBUS_INVALID_ARGS = 'org.freedesktop.DBus.Error.InvalidArgs'
Brad Bishopd4578922015-12-02 11:10:36 -050054DBUS_TYPE_ERROR = 'org.freedesktop.DBus.Python.TypeError'
Deepak Kodihalli6075bb42017-04-04 05:49:17 -050055DELETE_IFACE = 'xyz.openbmc_project.Object.Delete'
Adriana Kobylak53693892018-03-12 13:05:50 -050056SOFTWARE_PATH = '/xyz/openbmc_project/software'
Jayashankar Padathbec10c22018-05-29 18:22:59 +053057WEBSOCKET_TIMEOUT = 45
Brad Bishop9ee57c42015-11-03 14:59:29 -050058
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050059_4034_msg = "The specified %s cannot be %s: '%s'"
Brad Bishopaa65f6e2015-10-27 16:28:51 -040060
Matt Spinlerd41643e2018-02-02 13:51:38 -060061www_base_path = '/usr/share/www/'
62
Brad Bishop87b63c12016-03-18 14:47:51 -040063
Brad Bishop2f428582015-12-02 10:56:11 -050064def valid_user(session, *a, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -040065 ''' Authorization plugin callback that checks
66 that the user is logged in. '''
67 if session is None:
Brad Bishopdc3fbfa2016-09-08 09:51:38 -040068 abort(401, 'Login required')
Brad Bishop87b63c12016-03-18 14:47:51 -040069
Brad Bishop2f428582015-12-02 10:56:11 -050070
Leonel Gonzalez0bdef952017-04-18 08:17:49 -050071def get_type_signature_by_introspection(bus, service, object_path,
72 property_name):
73 obj = bus.get_object(service, object_path)
74 iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable')
75 xml_string = iface.Introspect()
76 for child in ElementTree.fromstring(xml_string):
77 # Iterate over each interfaces's properties to find
78 # matching property_name, and return its signature string
79 if child.tag == 'interface':
80 for i in child.iter():
81 if ('name' in i.attrib) and \
82 (i.attrib['name'] == property_name):
83 type_signature = i.attrib['type']
84 return type_signature
85
86
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +053087def get_method_signature(bus, service, object_path, interface, method):
88 obj = bus.get_object(service, object_path)
89 iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable')
90 xml_string = iface.Introspect()
91 arglist = []
92
93 root = ElementTree.fromstring(xml_string)
94 for dbus_intf in root.findall('interface'):
95 if (dbus_intf.get('name') == interface):
96 for dbus_method in dbus_intf.findall('method'):
97 if(dbus_method.get('name') == method):
98 for arg in dbus_method.findall('arg'):
99 arglist.append(arg.get('type'))
100 return arglist
101
102
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500103def split_struct_signature(signature):
104 struct_regex = r'(b|y|n|i|x|q|u|t|d|s|a\(.+?\)|\(.+?\))|a\{.+?\}+?'
105 struct_matches = re.findall(struct_regex, signature)
106 return struct_matches
107
108
109def convert_type(signature, value):
110 # Basic Types
111 converted_value = None
112 converted_container = None
CamVan Nguyen249d1322018-03-05 10:08:33 -0600113 # TODO: openbmc/openbmc#2994 remove python 2 support
114 try: # python 2
115 basic_types = {'b': bool, 'y': dbus.Byte, 'n': dbus.Int16, 'i': int,
116 'x': long, 'q': dbus.UInt16, 'u': dbus.UInt32,
117 't': dbus.UInt64, 'd': float, 's': str}
118 except NameError: # python 3
119 basic_types = {'b': bool, 'y': dbus.Byte, 'n': dbus.Int16, 'i': int,
120 'x': int, 'q': dbus.UInt16, 'u': dbus.UInt32,
121 't': dbus.UInt64, 'd': float, 's': str}
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500122 array_matches = re.match(r'a\((\S+)\)', signature)
123 struct_matches = re.match(r'\((\S+)\)', signature)
124 dictionary_matches = re.match(r'a{(\S+)}', signature)
125 if signature in basic_types:
126 converted_value = basic_types[signature](value)
127 return converted_value
128 # Array
129 if array_matches:
130 element_type = array_matches.group(1)
131 converted_container = list()
132 # Test if value is a list
133 # to avoid iterating over each character in a string.
134 # Iterate over each item and convert type
135 if isinstance(value, list):
136 for i in value:
137 converted_element = convert_type(element_type, i)
138 converted_container.append(converted_element)
139 # Convert non-sequence to expected type, and append to list
140 else:
141 converted_element = convert_type(element_type, value)
142 converted_container.append(converted_element)
143 return converted_container
144 # Struct
145 if struct_matches:
146 element_types = struct_matches.group(1)
147 split_element_types = split_struct_signature(element_types)
148 converted_container = list()
149 # Test if value is a list
150 if isinstance(value, list):
151 for index, val in enumerate(value):
152 converted_element = convert_type(split_element_types[index],
153 value[index])
154 converted_container.append(converted_element)
155 else:
156 converted_element = convert_type(element_types, value)
157 converted_container.append(converted_element)
158 return tuple(converted_container)
159 # Dictionary
160 if dictionary_matches:
161 element_types = dictionary_matches.group(1)
162 split_element_types = split_struct_signature(element_types)
163 converted_container = dict()
164 # Convert each element of dict
CamVan Nguyen249d1322018-03-05 10:08:33 -0600165 for key, val in value.items():
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500166 converted_key = convert_type(split_element_types[0], key)
167 converted_val = convert_type(split_element_types[1], val)
168 converted_container[converted_key] = converted_val
169 return converted_container
170
171
Jayashankar Padathbec10c22018-05-29 18:22:59 +0530172def send_ws_ping(wsock, timeout) :
173 # Most webservers close websockets after 60 seconds of
174 # inactivity. Make sure to send a ping before that.
175 payload = "ping"
176 # the ping payload can be anything, the receiver has to just
177 # return the same back.
178 while True:
179 gevent.sleep(timeout)
180 try:
181 if wsock:
182 wsock.send_frame(payload, wsock.OPCODE_PING)
183 except Exception as e:
184 wsock.close()
185 return
186
187
Brad Bishop2f428582015-12-02 10:56:11 -0500188class UserInGroup:
Brad Bishop87b63c12016-03-18 14:47:51 -0400189 ''' Authorization plugin callback that checks that the user is logged in
190 and a member of a group. '''
191 def __init__(self, group):
192 self.group = group
Brad Bishop2f428582015-12-02 10:56:11 -0500193
Brad Bishop87b63c12016-03-18 14:47:51 -0400194 def __call__(self, session, *a, **kw):
195 valid_user(session, *a, **kw)
196 res = False
Brad Bishop2f428582015-12-02 10:56:11 -0500197
Brad Bishop87b63c12016-03-18 14:47:51 -0400198 try:
199 res = session['user'] in grp.getgrnam(self.group)[3]
200 except KeyError:
201 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500202
Brad Bishop87b63c12016-03-18 14:47:51 -0400203 if not res:
204 abort(403, 'Insufficient access')
205
Brad Bishop2f428582015-12-02 10:56:11 -0500206
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500207class RouteHandler(object):
Brad Bishop6d190602016-04-15 13:09:39 -0400208 _require_auth = obmc.utils.misc.makelist(valid_user)
Brad Bishopd0c404a2017-02-21 09:23:25 -0500209 _enable_cors = True
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400210
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500211 def __init__(self, app, bus, verbs, rules, content_type=''):
Brad Bishop87b63c12016-03-18 14:47:51 -0400212 self.app = app
213 self.bus = bus
Brad Bishopb103d2d2016-03-04 16:19:14 -0500214 self.mapper = obmc.mapper.Mapper(bus)
Brad Bishop6d190602016-04-15 13:09:39 -0400215 self._verbs = obmc.utils.misc.makelist(verbs)
Brad Bishop87b63c12016-03-18 14:47:51 -0400216 self._rules = rules
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500217 self._content_type = content_type
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400218
Brad Bishop88c76a42017-02-21 00:02:02 -0500219 if 'GET' in self._verbs:
220 self._verbs = list(set(self._verbs + ['HEAD']))
Brad Bishopd4c1c552017-02-21 00:07:28 -0500221 if 'OPTIONS' not in self._verbs:
222 self._verbs.append('OPTIONS')
Brad Bishop88c76a42017-02-21 00:02:02 -0500223
Brad Bishop87b63c12016-03-18 14:47:51 -0400224 def _setup(self, **kw):
225 request.route_data = {}
Brad Bishopd4c1c552017-02-21 00:07:28 -0500226
Brad Bishop87b63c12016-03-18 14:47:51 -0400227 if request.method in self._verbs:
Brad Bishopd4c1c552017-02-21 00:07:28 -0500228 if request.method != 'OPTIONS':
229 return self.setup(**kw)
Brad Bishop88c76a42017-02-21 00:02:02 -0500230
Brad Bishopd4c1c552017-02-21 00:07:28 -0500231 # Javascript implementations will not send credentials
232 # with an OPTIONS request. Don't help malicious clients
233 # by checking the path here and returning a 404 if the
234 # path doesn't exist.
235 return None
Brad Bishop88c76a42017-02-21 00:02:02 -0500236
Brad Bishopd4c1c552017-02-21 00:07:28 -0500237 # Return 405
Brad Bishop88c76a42017-02-21 00:02:02 -0500238 raise HTTPError(
239 405, "Method not allowed.", Allow=','.join(self._verbs))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400240
Brad Bishop87b63c12016-03-18 14:47:51 -0400241 def __call__(self, **kw):
242 return getattr(self, 'do_' + request.method.lower())(**kw)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400243
Brad Bishop88c76a42017-02-21 00:02:02 -0500244 def do_head(self, **kw):
245 return self.do_get(**kw)
246
Brad Bishopd4c1c552017-02-21 00:07:28 -0500247 def do_options(self, **kw):
248 for v in self._verbs:
249 response.set_header(
250 'Allow',
251 ','.join(self._verbs))
252 return None
253
Brad Bishop87b63c12016-03-18 14:47:51 -0400254 def install(self):
255 self.app.route(
256 self._rules, callback=self,
Brad Bishopd4c1c552017-02-21 00:07:28 -0500257 method=['OPTIONS', 'GET', 'PUT', 'PATCH', 'POST', 'DELETE'])
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400258
Brad Bishop87b63c12016-03-18 14:47:51 -0400259 @staticmethod
260 def try_mapper_call(f, callback=None, **kw):
261 try:
262 return f(**kw)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600263 except dbus.exceptions.DBusException as e:
Brad Bishopfce77562016-11-28 15:44:18 -0500264 if e.get_dbus_name() == \
265 'org.freedesktop.DBus.Error.ObjectPathInUse':
266 abort(503, str(e))
Brad Bishopb103d2d2016-03-04 16:19:14 -0500267 if e.get_dbus_name() != obmc.mapper.MAPPER_NOT_FOUND:
Brad Bishop87b63c12016-03-18 14:47:51 -0400268 raise
269 if callback is None:
270 def callback(e, **kw):
271 abort(404, str(e))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400272
Brad Bishop87b63c12016-03-18 14:47:51 -0400273 callback(e, **kw)
274
275 @staticmethod
276 def try_properties_interface(f, *a):
277 try:
278 return f(*a)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600279 except dbus.exceptions.DBusException as e:
Adriana Kobylakf92cf4d2017-12-13 11:46:50 -0600280 if DBUS_UNKNOWN_INTERFACE in e.get_dbus_name():
Brad Bishopf4e74982016-04-01 14:53:05 -0400281 # interface doesn't have any properties
282 return None
Brad Bishop87b63c12016-03-18 14:47:51 -0400283 if DBUS_UNKNOWN_METHOD == e.get_dbus_name():
284 # properties interface not implemented at all
285 return None
286 raise
287
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400288
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500289class DirectoryHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400290 verbs = 'GET'
291 rules = '<path:path>/'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400292
Brad Bishop87b63c12016-03-18 14:47:51 -0400293 def __init__(self, app, bus):
294 super(DirectoryHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400295 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400296
Brad Bishop87b63c12016-03-18 14:47:51 -0400297 def find(self, path='/'):
298 return self.try_mapper_call(
299 self.mapper.get_subtree_paths, path=path, depth=1)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400300
Brad Bishop87b63c12016-03-18 14:47:51 -0400301 def setup(self, path='/'):
302 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400303
Brad Bishop87b63c12016-03-18 14:47:51 -0400304 def do_get(self, path='/'):
305 return request.route_data['map']
306
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400307
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500308class ListNamesHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400309 verbs = 'GET'
310 rules = ['/list', '<path:path>/list']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400311
Brad Bishop87b63c12016-03-18 14:47:51 -0400312 def __init__(self, app, bus):
313 super(ListNamesHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400314 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400315
Brad Bishop87b63c12016-03-18 14:47:51 -0400316 def find(self, path='/'):
CamVan Nguyen249d1322018-03-05 10:08:33 -0600317 return list(self.try_mapper_call(
318 self.mapper.get_subtree, path=path).keys())
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400319
Brad Bishop87b63c12016-03-18 14:47:51 -0400320 def setup(self, path='/'):
321 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400322
Brad Bishop87b63c12016-03-18 14:47:51 -0400323 def do_get(self, path='/'):
324 return request.route_data['map']
325
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400326
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500327class ListHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400328 verbs = 'GET'
329 rules = ['/enumerate', '<path:path>/enumerate']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400330
Brad Bishop87b63c12016-03-18 14:47:51 -0400331 def __init__(self, app, bus):
332 super(ListHandler, self).__init__(
Brad Bishopc431e1a2017-07-10 16:44:51 -0400333 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400334
Brad Bishop87b63c12016-03-18 14:47:51 -0400335 def find(self, path='/'):
336 return self.try_mapper_call(
337 self.mapper.get_subtree, path=path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400338
Brad Bishop87b63c12016-03-18 14:47:51 -0400339 def setup(self, path='/'):
340 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400341
Brad Bishop87b63c12016-03-18 14:47:51 -0400342 def do_get(self, path='/'):
Brad Bishop71527b42016-04-01 14:51:14 -0400343 return {x: y for x, y in self.mapper.enumerate_subtree(
344 path,
345 mapper_data=request.route_data['map']).dataitems()}
Brad Bishop87b63c12016-03-18 14:47:51 -0400346
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400347
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500348class MethodHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400349 verbs = 'POST'
350 rules = '<path:path>/action/<method>'
351 request_type = list
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500352 content_type = 'application/json'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400353
Brad Bishop87b63c12016-03-18 14:47:51 -0400354 def __init__(self, app, bus):
355 super(MethodHandler, self).__init__(
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500356 app, bus, self.verbs, self.rules, self.content_type)
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530357 self.service = ''
358 self.interface = ''
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400359
Brad Bishop87b63c12016-03-18 14:47:51 -0400360 def find(self, path, method):
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500361 method_list = []
Gunnar Mills313aadb2018-04-08 14:50:09 -0500362 buses = self.try_mapper_call(
Brad Bishop87b63c12016-03-18 14:47:51 -0400363 self.mapper.get_object, path=path)
Gunnar Mills313aadb2018-04-08 14:50:09 -0500364 for items in buses.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400365 m = self.find_method_on_bus(path, method, *items)
366 if m:
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500367 method_list.append(m)
Nagaraju Goruganti765c2c82017-11-13 06:17:13 -0600368 if method_list:
369 return method_list
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400370
Brad Bishop87b63c12016-03-18 14:47:51 -0400371 abort(404, _4034_msg % ('method', 'found', method))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400372
Brad Bishop87b63c12016-03-18 14:47:51 -0400373 def setup(self, path, method):
Saqib Khan3a00b1f2017-11-04 15:56:21 -0500374 request.route_data['map'] = self.find(path, method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400375
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600376 def do_post(self, path, method, retry=True):
Brad Bishop87b63c12016-03-18 14:47:51 -0400377 try:
Nagaraju Goruganti765c2c82017-11-13 06:17:13 -0600378 args = []
379 if request.parameter_list:
380 args = request.parameter_list
381 # To see if the return type is capable of being merged
382 if len(request.route_data['map']) > 1:
383 results = None
384 for item in request.route_data['map']:
385 tmp = item(*args)
386 if not results:
387 if tmp is not None:
388 results = type(tmp)()
389 if isinstance(results, dict):
390 results = results.update(tmp)
391 elif isinstance(results, list):
392 results = results + tmp
393 elif isinstance(results, type(None)):
394 results = None
395 else:
396 abort(501, 'Don\'t know how to merge method call '
397 'results of {}'.format(type(tmp)))
398 return results
399 # There is only one method
400 return request.route_data['map'][0](*args)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400401
CamVan Nguyen249d1322018-03-05 10:08:33 -0600402 except dbus.exceptions.DBusException as e:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530403 paramlist = []
Brad Bishopb7fca9b2018-01-23 12:16:50 -0500404 if e.get_dbus_name() == DBUS_INVALID_ARGS and retry:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530405
406 signature_list = get_method_signature(self.bus, self.service,
407 path, self.interface,
408 method)
409 if not signature_list:
410 abort(400, "Failed to get method signature: %s" % str(e))
411 if len(signature_list) != len(request.parameter_list):
412 abort(400, "Invalid number of args")
413 converted_value = None
414 try:
415 for index, expected_type in enumerate(signature_list):
416 value = request.parameter_list[index]
417 converted_value = convert_type(expected_type, value)
418 paramlist.append(converted_value)
419 request.parameter_list = paramlist
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600420 self.do_post(path, method, False)
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530421 return
422 except Exception as ex:
Nagaraju Gorugantiab404fa2017-12-14 10:24:40 -0600423 abort(400, "Bad Request/Invalid Args given")
Brad Bishop87b63c12016-03-18 14:47:51 -0400424 abort(400, str(e))
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530425
Brad Bishop87b63c12016-03-18 14:47:51 -0400426 if e.get_dbus_name() == DBUS_TYPE_ERROR:
427 abort(400, str(e))
428 raise
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400429
Brad Bishop87b63c12016-03-18 14:47:51 -0400430 @staticmethod
431 def find_method_in_interface(method, obj, interface, methods):
432 if methods is None:
433 return None
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400434
CamVan Nguyen249d1322018-03-05 10:08:33 -0600435 method = obmc.utils.misc.find_case_insensitive(method, list(methods.keys()))
Brad Bishop87b63c12016-03-18 14:47:51 -0400436 if method is not None:
437 iface = dbus.Interface(obj, interface)
438 return iface.get_dbus_method(method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400439
Brad Bishop87b63c12016-03-18 14:47:51 -0400440 def find_method_on_bus(self, path, method, bus, interfaces):
441 obj = self.bus.get_object(bus, path, introspect=False)
442 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
443 data = iface.Introspect()
444 parser = IntrospectionNodeParser(
445 ElementTree.fromstring(data),
Brad Bishopaeb995d2018-04-04 22:28:42 -0400446 intf_match=lambda x: x in interfaces)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600447 for x, y in parser.get_interfaces().items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400448 m = self.find_method_in_interface(
449 method, obj, x, y.get('method'))
450 if m:
Ratan Guptaa6a8a4c2017-08-07 08:18:44 +0530451 self.service = bus
452 self.interface = x
Brad Bishop87b63c12016-03-18 14:47:51 -0400453 return m
454
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400455
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500456class PropertyHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400457 verbs = ['PUT', 'GET']
458 rules = '<path:path>/attr/<prop>'
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500459 content_type = 'application/json'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400460
Brad Bishop87b63c12016-03-18 14:47:51 -0400461 def __init__(self, app, bus):
462 super(PropertyHandler, self).__init__(
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500463 app, bus, self.verbs, self.rules, self.content_type)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400464
Brad Bishop87b63c12016-03-18 14:47:51 -0400465 def find(self, path, prop):
466 self.app.instance_handler.setup(path)
467 obj = self.app.instance_handler.do_get(path)
Brad Bishop56ad87f2017-02-21 23:33:29 -0500468 real_name = obmc.utils.misc.find_case_insensitive(
CamVan Nguyen249d1322018-03-05 10:08:33 -0600469 prop, list(obj.keys()))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400470
Brad Bishop56ad87f2017-02-21 23:33:29 -0500471 if not real_name:
472 if request.method == 'PUT':
473 abort(403, _4034_msg % ('property', 'created', prop))
474 else:
475 abort(404, _4034_msg % ('property', 'found', prop))
476 return real_name, {path: obj}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500477
Brad Bishop87b63c12016-03-18 14:47:51 -0400478 def setup(self, path, prop):
Brad Bishop56ad87f2017-02-21 23:33:29 -0500479 name, obj = self.find(path, prop)
480 request.route_data['obj'] = obj
481 request.route_data['name'] = name
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500482
Brad Bishop87b63c12016-03-18 14:47:51 -0400483 def do_get(self, path, prop):
Brad Bishop56ad87f2017-02-21 23:33:29 -0500484 name = request.route_data['name']
485 return request.route_data['obj'][path][name]
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500486
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600487 def do_put(self, path, prop, value=None, retry=True):
Brad Bishop87b63c12016-03-18 14:47:51 -0400488 if value is None:
489 value = request.parameter_list
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500490
Brad Bishop87b63c12016-03-18 14:47:51 -0400491 prop, iface, properties_iface = self.get_host_interface(
492 path, prop, request.route_data['map'][path])
493 try:
494 properties_iface.Set(iface, prop, value)
CamVan Nguyen249d1322018-03-05 10:08:33 -0600495 except ValueError as e:
Brad Bishop87b63c12016-03-18 14:47:51 -0400496 abort(400, str(e))
CamVan Nguyen249d1322018-03-05 10:08:33 -0600497 except dbus.exceptions.DBusException as e:
Brad Bishopb7fca9b2018-01-23 12:16:50 -0500498 if e.get_dbus_name() == DBUS_INVALID_ARGS and retry:
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500499 bus_name = properties_iface.bus_name
500 expected_type = get_type_signature_by_introspection(self.bus,
501 bus_name,
502 path,
503 prop)
504 if not expected_type:
505 abort(403, "Failed to get expected type: %s" % str(e))
506 converted_value = None
507 try:
508 converted_value = convert_type(expected_type, value)
Marri Devender Raobc0c6732017-11-20 00:15:47 -0600509 self.do_put(path, prop, converted_value, False)
Leonel Gonzalez0bdef952017-04-18 08:17:49 -0500510 return
511 except Exception as ex:
512 abort(403, "Failed to convert %s to type %s" %
513 (value, expected_type))
Brad Bishop87b63c12016-03-18 14:47:51 -0400514 abort(403, str(e))
515 raise
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500516
Brad Bishop87b63c12016-03-18 14:47:51 -0400517 def get_host_interface(self, path, prop, bus_info):
CamVan Nguyen249d1322018-03-05 10:08:33 -0600518 for bus, interfaces in bus_info.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400519 obj = self.bus.get_object(bus, path, introspect=True)
520 properties_iface = dbus.Interface(
521 obj, dbus_interface=dbus.PROPERTIES_IFACE)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500522
Brad Bishop87b63c12016-03-18 14:47:51 -0400523 info = self.get_host_interface_on_bus(
524 path, prop, properties_iface, bus, interfaces)
525 if info is not None:
526 prop, iface = info
527 return prop, iface, properties_iface
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500528
Brad Bishop87b63c12016-03-18 14:47:51 -0400529 def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces):
530 for i in interfaces:
531 properties = self.try_properties_interface(iface.GetAll, i)
Brad Bishop69cb6d12017-02-21 12:01:52 -0500532 if not properties:
Brad Bishop87b63c12016-03-18 14:47:51 -0400533 continue
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500534 match = obmc.utils.misc.find_case_insensitive(
CamVan Nguyen249d1322018-03-05 10:08:33 -0600535 prop, list(properties.keys()))
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500536 if match is None:
Brad Bishop87b63c12016-03-18 14:47:51 -0400537 continue
Leonel Gonzalez409f6712017-05-24 09:51:55 -0500538 prop = match
Brad Bishop87b63c12016-03-18 14:47:51 -0400539 return prop, i
540
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500541
Brad Bishop2503bd62015-12-16 17:56:12 -0500542class SchemaHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400543 verbs = ['GET']
544 rules = '<path:path>/schema'
Brad Bishop2503bd62015-12-16 17:56:12 -0500545
Brad Bishop87b63c12016-03-18 14:47:51 -0400546 def __init__(self, app, bus):
547 super(SchemaHandler, self).__init__(
Brad Bishop529029b2017-07-10 16:46:01 -0400548 app, bus, self.verbs, self.rules)
Brad Bishop2503bd62015-12-16 17:56:12 -0500549
Brad Bishop87b63c12016-03-18 14:47:51 -0400550 def find(self, path):
551 return self.try_mapper_call(
552 self.mapper.get_object,
553 path=path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500554
Brad Bishop87b63c12016-03-18 14:47:51 -0400555 def setup(self, path):
556 request.route_data['map'] = self.find(path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500557
Brad Bishop87b63c12016-03-18 14:47:51 -0400558 def do_get(self, path):
559 schema = {}
CamVan Nguyen249d1322018-03-05 10:08:33 -0600560 for x in request.route_data['map'].keys():
Brad Bishop87b63c12016-03-18 14:47:51 -0400561 obj = self.bus.get_object(x, path, introspect=False)
562 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
563 data = iface.Introspect()
564 parser = IntrospectionNodeParser(
565 ElementTree.fromstring(data))
CamVan Nguyen249d1322018-03-05 10:08:33 -0600566 for x, y in parser.get_interfaces().items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400567 schema[x] = y
Brad Bishop2503bd62015-12-16 17:56:12 -0500568
Brad Bishop87b63c12016-03-18 14:47:51 -0400569 return schema
570
Brad Bishop2503bd62015-12-16 17:56:12 -0500571
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500572class InstanceHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400573 verbs = ['GET', 'PUT', 'DELETE']
574 rules = '<path:path>'
575 request_type = dict
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500576
Brad Bishop87b63c12016-03-18 14:47:51 -0400577 def __init__(self, app, bus):
578 super(InstanceHandler, self).__init__(
Brad Bishop529029b2017-07-10 16:46:01 -0400579 app, bus, self.verbs, self.rules)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500580
Brad Bishop87b63c12016-03-18 14:47:51 -0400581 def find(self, path, callback=None):
582 return {path: self.try_mapper_call(
583 self.mapper.get_object,
584 callback,
585 path=path)}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500586
Brad Bishop87b63c12016-03-18 14:47:51 -0400587 def setup(self, path):
588 callback = None
589 if request.method == 'PUT':
590 def callback(e, **kw):
591 abort(403, _4034_msg % ('resource', 'created', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500592
Brad Bishop87b63c12016-03-18 14:47:51 -0400593 if request.route_data.get('map') is None:
594 request.route_data['map'] = self.find(path, callback)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500595
Brad Bishop87b63c12016-03-18 14:47:51 -0400596 def do_get(self, path):
Brad Bishop71527b42016-04-01 14:51:14 -0400597 return self.mapper.enumerate_object(
598 path,
599 mapper_data=request.route_data['map'])
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500600
Brad Bishop87b63c12016-03-18 14:47:51 -0400601 def do_put(self, path):
602 # make sure all properties exist in the request
603 obj = set(self.do_get(path).keys())
604 req = set(request.parameter_list.keys())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500605
Brad Bishop87b63c12016-03-18 14:47:51 -0400606 diff = list(obj.difference(req))
607 if diff:
608 abort(403, _4034_msg % (
609 'resource', 'removed', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500610
Brad Bishop87b63c12016-03-18 14:47:51 -0400611 diff = list(req.difference(obj))
612 if diff:
613 abort(403, _4034_msg % (
614 'resource', 'created', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500615
CamVan Nguyen249d1322018-03-05 10:08:33 -0600616 for p, v in request.parameter_list.items():
Brad Bishop87b63c12016-03-18 14:47:51 -0400617 self.app.property_handler.do_put(
618 path, p, v)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500619
Brad Bishop87b63c12016-03-18 14:47:51 -0400620 def do_delete(self, path):
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500621 deleted = False
622 for bus, interfaces in request.route_data['map'][path].items():
623 if self.bus_has_delete(interfaces):
624 self.delete_on_bus(path, bus)
625 deleted = True
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500626
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500627 #It's OK if some objects didn't have a Delete, but not all
628 if not deleted:
629 abort(403, _4034_msg % ('resource', 'removed', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500630
Matt Spinlerb1f6a2c2018-05-14 12:25:21 -0500631 def bus_has_delete(self, interfaces):
632 return DELETE_IFACE in interfaces
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500633
Brad Bishop87b63c12016-03-18 14:47:51 -0400634 def delete_on_bus(self, path, bus):
635 obj = self.bus.get_object(bus, path, introspect=False)
636 delete_iface = dbus.Interface(
637 obj, dbus_interface=DELETE_IFACE)
638 delete_iface.Delete()
639
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500640
Brad Bishop2f428582015-12-02 10:56:11 -0500641class SessionHandler(MethodHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400642 ''' Handles the /login and /logout routes, manages
643 server side session store and session cookies. '''
Brad Bishop2f428582015-12-02 10:56:11 -0500644
Brad Bishop87b63c12016-03-18 14:47:51 -0400645 rules = ['/login', '/logout']
646 login_str = "User '%s' logged %s"
647 bad_passwd_str = "Invalid username or password"
648 no_user_str = "No user logged in"
649 bad_json_str = "Expecting request format { 'data': " \
650 "[<username>, <password>] }, got '%s'"
Alexander Filippovd08a4562018-03-20 12:02:23 +0300651 bmc_not_ready_str = "BMC is not ready (booting)"
Brad Bishop87b63c12016-03-18 14:47:51 -0400652 _require_auth = None
653 MAX_SESSIONS = 16
Alexander Filippovd08a4562018-03-20 12:02:23 +0300654 BMCSTATE_IFACE = 'xyz.openbmc_project.State.BMC'
655 BMCSTATE_PATH = '/xyz/openbmc_project/state/bmc0'
656 BMCSTATE_PROPERTY = 'CurrentBMCState'
657 BMCSTATE_READY = 'xyz.openbmc_project.State.BMC.BMCState.Ready'
Brad Bishop2f428582015-12-02 10:56:11 -0500658
Brad Bishop87b63c12016-03-18 14:47:51 -0400659 def __init__(self, app, bus):
660 super(SessionHandler, self).__init__(
661 app, bus)
662 self.hmac_key = os.urandom(128)
663 self.session_store = []
Brad Bishop2f428582015-12-02 10:56:11 -0500664
Brad Bishop87b63c12016-03-18 14:47:51 -0400665 @staticmethod
666 def authenticate(username, clear):
667 try:
668 encoded = spwd.getspnam(username)[1]
669 return encoded == crypt.crypt(clear, encoded)
670 except KeyError:
671 return False
Brad Bishop2f428582015-12-02 10:56:11 -0500672
Brad Bishop87b63c12016-03-18 14:47:51 -0400673 def invalidate_session(self, session):
674 try:
675 self.session_store.remove(session)
676 except ValueError:
677 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500678
Brad Bishop87b63c12016-03-18 14:47:51 -0400679 def new_session(self):
680 sid = os.urandom(32)
681 if self.MAX_SESSIONS <= len(self.session_store):
682 self.session_store.pop()
683 self.session_store.insert(0, {'sid': sid})
Brad Bishop2f428582015-12-02 10:56:11 -0500684
Brad Bishop87b63c12016-03-18 14:47:51 -0400685 return self.session_store[0]
Brad Bishop2f428582015-12-02 10:56:11 -0500686
Brad Bishop87b63c12016-03-18 14:47:51 -0400687 def get_session(self, sid):
688 sids = [x['sid'] for x in self.session_store]
689 try:
690 return self.session_store[sids.index(sid)]
691 except ValueError:
692 return None
Brad Bishop2f428582015-12-02 10:56:11 -0500693
Brad Bishop87b63c12016-03-18 14:47:51 -0400694 def get_session_from_cookie(self):
695 return self.get_session(
696 request.get_cookie(
697 'sid', secret=self.hmac_key))
Brad Bishop2f428582015-12-02 10:56:11 -0500698
Brad Bishop87b63c12016-03-18 14:47:51 -0400699 def do_post(self, **kw):
700 if request.path == '/login':
701 return self.do_login(**kw)
702 else:
703 return self.do_logout(**kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500704
Brad Bishop87b63c12016-03-18 14:47:51 -0400705 def do_logout(self, **kw):
706 session = self.get_session_from_cookie()
707 if session is not None:
708 user = session['user']
709 self.invalidate_session(session)
710 response.delete_cookie('sid')
711 return self.login_str % (user, 'out')
Brad Bishop2f428582015-12-02 10:56:11 -0500712
Brad Bishop87b63c12016-03-18 14:47:51 -0400713 return self.no_user_str
Brad Bishop2f428582015-12-02 10:56:11 -0500714
Brad Bishop87b63c12016-03-18 14:47:51 -0400715 def do_login(self, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -0400716 if len(request.parameter_list) != 2:
717 abort(400, self.bad_json_str % (request.json))
Brad Bishop2f428582015-12-02 10:56:11 -0500718
Brad Bishop87b63c12016-03-18 14:47:51 -0400719 if not self.authenticate(*request.parameter_list):
Brad Bishopdc3fbfa2016-09-08 09:51:38 -0400720 abort(401, self.bad_passwd_str)
Brad Bishop2f428582015-12-02 10:56:11 -0500721
Alexander Filippovd08a4562018-03-20 12:02:23 +0300722 force = False
723 try:
724 force = request.json.get('force')
725 except (ValueError, AttributeError, KeyError, TypeError):
726 force = False
727
728 if not force and not self.is_bmc_ready():
729 abort(503, self.bmc_not_ready_str)
730
Brad Bishop87b63c12016-03-18 14:47:51 -0400731 user = request.parameter_list[0]
732 session = self.new_session()
733 session['user'] = user
734 response.set_cookie(
735 'sid', session['sid'], secret=self.hmac_key,
736 secure=True,
737 httponly=True)
738 return self.login_str % (user, 'in')
Brad Bishop2f428582015-12-02 10:56:11 -0500739
Alexander Filippovd08a4562018-03-20 12:02:23 +0300740 def is_bmc_ready(self):
741 if not self.app.with_bmc_check:
742 return True
743
744 try:
745 obj = self.bus.get_object(self.BMCSTATE_IFACE, self.BMCSTATE_PATH)
746 iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE)
747 state = iface.Get(self.BMCSTATE_IFACE, self.BMCSTATE_PROPERTY)
748 if state == self.BMCSTATE_READY:
749 return True
750
751 except dbus.exceptions.DBusException:
752 pass
753
754 return False
755
Brad Bishop87b63c12016-03-18 14:47:51 -0400756 def find(self, **kw):
757 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500758
Brad Bishop87b63c12016-03-18 14:47:51 -0400759 def setup(self, **kw):
760 pass
761
Brad Bishop2f428582015-12-02 10:56:11 -0500762
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500763class ImageUploadUtils:
764 ''' Provides common utils for image upload. '''
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500765
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500766 file_loc = '/tmp/images'
767 file_prefix = 'img'
768 file_suffix = ''
Adriana Kobylak53693892018-03-12 13:05:50 -0500769 signal = None
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500770
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500771 @classmethod
772 def do_upload(cls, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -0500773 def cleanup():
774 os.close(handle)
775 if cls.signal:
776 cls.signal.remove()
777 cls.signal = None
778
779 def signal_callback(path, a, **kw):
780 # Just interested on the first Version interface created which is
781 # triggered when the file is uploaded. This helps avoid getting the
782 # wrong information for multiple upload requests in a row.
783 if "xyz.openbmc_project.Software.Version" in a and \
784 "xyz.openbmc_project.Software.Activation" not in a:
785 paths.append(path)
786
787 while cls.signal:
788 # Serialize uploads by waiting for the signal to be cleared.
789 # This makes it easier to ensure that the version information
790 # is the right one instead of the data from another upload request.
791 gevent.sleep(1)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500792 if not os.path.exists(cls.file_loc):
Gunnar Millsfb515792017-11-09 15:52:17 -0600793 abort(500, "Error Directory not found")
Adriana Kobylak53693892018-03-12 13:05:50 -0500794 paths = []
795 bus = dbus.SystemBus()
796 cls.signal = bus.add_signal_receiver(
797 signal_callback,
798 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
799 signal_name='InterfacesAdded',
800 path=SOFTWARE_PATH)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500801 if not filename:
802 handle, filename = tempfile.mkstemp(cls.file_suffix,
803 cls.file_prefix, cls.file_loc)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500804 else:
805 filename = os.path.join(cls.file_loc, filename)
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500806 handle = os.open(filename, os.O_WRONLY | os.O_CREAT)
Leonel Gonzalez0b62edf2017-06-08 15:10:03 -0500807 try:
808 file_contents = request.body.read()
809 request.body.close()
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500810 os.write(handle, file_contents)
Adriana Kobylak53693892018-03-12 13:05:50 -0500811 # Close file after writing, the image manager process watches for
812 # the close event to know the upload is complete.
Gunnar Millsb66b18c2017-08-21 16:17:21 -0500813 os.close(handle)
Adriana Kobylak53693892018-03-12 13:05:50 -0500814 except (IOError, ValueError) as e:
815 cleanup()
816 abort(400, str(e))
817 except Exception:
818 cleanup()
819 abort(400, "Unexpected Error")
820 loop = gobject.MainLoop()
821 gcontext = loop.get_context()
822 count = 0
823 version_id = ''
824 while loop is not None:
825 try:
826 if gcontext.pending():
827 gcontext.iteration()
828 if not paths:
829 gevent.sleep(1)
830 else:
831 version_id = os.path.basename(paths.pop())
832 break
833 count += 1
834 if count == 10:
835 break
836 except Exception:
837 break
838 cls.signal.remove()
839 cls.signal = None
Adriana Kobylak97fe4352018-04-10 10:44:11 -0500840 if version_id:
841 return version_id
842 else:
843 abort(400, "Version already exists or failed to be extracted")
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500844
845
846class ImagePostHandler(RouteHandler):
847 ''' Handles the /upload/image route. '''
848
849 verbs = ['POST']
850 rules = ['/upload/image']
851 content_type = 'application/octet-stream'
852
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500853 def __init__(self, app, bus):
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500854 super(ImagePostHandler, self).__init__(
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500855 app, bus, self.verbs, self.rules, self.content_type)
856
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500857 def do_post(self, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -0500858 return ImageUploadUtils.do_upload()
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500859
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500860 def find(self, **kw):
861 pass
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500862
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500863 def setup(self, **kw):
864 pass
865
866
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500867class EventNotifier:
868 keyNames = {}
869 keyNames['event'] = 'event'
870 keyNames['path'] = 'path'
871 keyNames['intfMap'] = 'interfaces'
872 keyNames['propMap'] = 'properties'
873 keyNames['intf'] = 'interface'
874
875 def __init__(self, wsock, filters):
876 self.wsock = wsock
877 self.paths = filters.get("paths", [])
878 self.interfaces = filters.get("interfaces", [])
879 if not self.paths:
880 self.paths.append(None)
881 bus = dbus.SystemBus()
882 # Add a signal receiver for every path the client is interested in
883 for path in self.paths:
884 bus.add_signal_receiver(
885 self.interfaces_added_handler,
886 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
887 signal_name='InterfacesAdded',
888 path=path)
889 bus.add_signal_receiver(
890 self.properties_changed_handler,
891 dbus_interface=dbus.PROPERTIES_IFACE,
892 signal_name='PropertiesChanged',
893 path=path,
894 path_keyword='path')
895 loop = gobject.MainLoop()
896 # gobject's mainloop.run() will block the entire process, so the gevent
897 # scheduler and hence greenlets won't execute. The while-loop below
898 # works around this limitation by using gevent's sleep, instead of
899 # calling loop.run()
900 gcontext = loop.get_context()
901 while loop is not None:
902 try:
903 if gcontext.pending():
904 gcontext.iteration()
905 else:
906 # gevent.sleep puts only the current greenlet to sleep,
907 # not the entire process.
908 gevent.sleep(5)
909 except WebSocketError:
910 break
911
912 def interfaces_added_handler(self, path, iprops, **kw):
913 ''' If the client is interested in these changes, respond to the
914 client. This handles d-bus interface additions.'''
915 if (not self.interfaces) or \
916 (not set(iprops).isdisjoint(self.interfaces)):
917 response = {}
918 response[self.keyNames['event']] = "InterfacesAdded"
919 response[self.keyNames['path']] = path
920 response[self.keyNames['intfMap']] = iprops
921 try:
922 self.wsock.send(json.dumps(response))
923 except WebSocketError:
924 return
925
926 def properties_changed_handler(self, interface, new, old, **kw):
927 ''' If the client is interested in these changes, respond to the
928 client. This handles d-bus property changes. '''
929 if (not self.interfaces) or (interface in self.interfaces):
930 path = str(kw['path'])
931 response = {}
932 response[self.keyNames['event']] = "PropertiesChanged"
933 response[self.keyNames['path']] = path
934 response[self.keyNames['intf']] = interface
935 response[self.keyNames['propMap']] = new
936 try:
937 self.wsock.send(json.dumps(response))
938 except WebSocketError:
939 return
940
941
Deepak Kodihallib209dd12017-10-11 01:19:17 -0500942class EventHandler(RouteHandler):
943 ''' Handles the /subscribe route, for clients to be able
944 to subscribe to BMC events. '''
945
946 verbs = ['GET']
947 rules = ['/subscribe']
948
949 def __init__(self, app, bus):
950 super(EventHandler, self).__init__(
951 app, bus, self.verbs, self.rules)
952
953 def find(self, **kw):
954 pass
955
956 def setup(self, **kw):
957 pass
958
959 def do_get(self):
960 wsock = request.environ.get('wsgi.websocket')
961 if not wsock:
962 abort(400, 'Expected WebSocket request.')
Jayashankar Padathbec10c22018-05-29 18:22:59 +0530963 ping_sender = Greenlet.spawn(send_ws_ping, wsock, WEBSOCKET_TIMEOUT)
Deepak Kodihalli639b5022017-10-13 06:40:26 -0500964 filters = wsock.receive()
965 filters = json.loads(filters)
966 notifier = EventNotifier(wsock, filters)
Deepak Kodihallib209dd12017-10-11 01:19:17 -0500967
Deepak Kodihalli5c518f62018-04-23 03:26:38 -0500968class HostConsoleHandler(RouteHandler):
969 ''' Handles the /console route, for clients to be able
970 read/write the host serial console. The way this is
971 done is by exposing a websocket that's mirrored to an
972 abstract UNIX domain socket, which is the source for
973 the console data. '''
974
975 verbs = ['GET']
976 # Naming the route console0, because the numbering will help
977 # on multi-bmc/multi-host systems.
978 rules = ['/console0']
979
980 def __init__(self, app, bus):
981 super(HostConsoleHandler, self).__init__(
982 app, bus, self.verbs, self.rules)
983
984 def find(self, **kw):
985 pass
986
987 def setup(self, **kw):
988 pass
989
990 def read_wsock(self, wsock, sock):
991 while True:
992 try:
993 incoming = wsock.receive()
994 if incoming:
995 # Read websocket, write to UNIX socket
996 sock.send(incoming)
997 except Exception as e:
998 sock.close()
999 return
1000
1001 def read_sock(self, sock, wsock):
1002 max_sock_read_len = 4096
1003 while True:
1004 try:
1005 outgoing = sock.recv(max_sock_read_len)
1006 if outgoing:
1007 # Read UNIX socket, write to websocket
1008 wsock.send(outgoing)
1009 except Exception as e:
1010 wsock.close()
1011 return
1012
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001013 def do_get(self):
1014 wsock = request.environ.get('wsgi.websocket')
1015 if not wsock:
1016 abort(400, 'Expected WebSocket based request.')
1017
1018 # A UNIX domain socket structure defines a 108-byte pathname. The
1019 # server in this case, obmc-console-server, expects a 108-byte path.
1020 socket_name = "\0obmc-console"
1021 trailing_bytes = "\0" * (108 - len(socket_name))
1022 socket_path = socket_name + trailing_bytes
1023 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1024
1025 try:
1026 sock.connect(socket_path)
1027 except Exception as e:
1028 abort(500, str(e))
1029
1030 wsock_reader = Greenlet.spawn(self.read_wsock, wsock, sock)
1031 sock_reader = Greenlet.spawn(self.read_sock, sock, wsock)
Jayashankar Padathbec10c22018-05-29 18:22:59 +05301032 ping_sender = Greenlet.spawn(send_ws_ping, wsock, WEBSOCKET_TIMEOUT)
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001033 gevent.joinall([wsock_reader, sock_reader, ping_sender])
1034
1035
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001036class ImagePutHandler(RouteHandler):
1037 ''' Handles the /upload/image/<filename> route. '''
1038
1039 verbs = ['PUT']
1040 rules = ['/upload/image/<filename>']
1041 content_type = 'application/octet-stream'
1042
1043 def __init__(self, app, bus):
1044 super(ImagePutHandler, self).__init__(
1045 app, bus, self.verbs, self.rules, self.content_type)
1046
1047 def do_put(self, filename=''):
Adriana Kobylak53693892018-03-12 13:05:50 -05001048 return ImageUploadUtils.do_upload(filename)
Deepak Kodihalli1af301a2017-04-11 07:29:01 -05001049
1050 def find(self, **kw):
1051 pass
1052
1053 def setup(self, **kw):
1054 pass
1055
1056
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001057class DownloadDumpHandler(RouteHandler):
1058 ''' Handles the /download/dump route. '''
1059
1060 verbs = 'GET'
1061 rules = ['/download/dump/<dumpid>']
1062 content_type = 'application/octet-stream'
Jayanth Othayoth18c3a242017-08-02 08:16:11 -05001063 dump_loc = '/var/lib/phosphor-debug-collector/dumps'
Brad Bishop944cd042017-07-10 16:42:41 -04001064 suppress_json_resp = True
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001065
1066 def __init__(self, app, bus):
1067 super(DownloadDumpHandler, self).__init__(
1068 app, bus, self.verbs, self.rules, self.content_type)
1069
1070 def do_get(self, dumpid):
1071 return self.do_download(dumpid)
1072
1073 def find(self, **kw):
1074 pass
1075
1076 def setup(self, **kw):
1077 pass
1078
1079 def do_download(self, dumpid):
1080 dump_loc = os.path.join(self.dump_loc, dumpid)
1081 if not os.path.exists(dump_loc):
1082 abort(404, "Path not found")
1083
1084 files = os.listdir(dump_loc)
1085 num_files = len(files)
1086 if num_files == 0:
1087 abort(404, "Dump not found")
1088
1089 return static_file(os.path.basename(files[0]), root=dump_loc,
1090 download=True, mimetype=self.content_type)
1091
1092
Matt Spinlerd41643e2018-02-02 13:51:38 -06001093class WebHandler(RouteHandler):
1094 ''' Handles the routes for the web UI files. '''
1095
1096 verbs = 'GET'
1097
1098 # Match only what we know are web files, so everything else
1099 # can get routed to the REST handlers.
1100 rules = ['//', '/<filename:re:.+\.js>', '/<filename:re:.+\.svg>',
1101 '/<filename:re:.+\.css>', '/<filename:re:.+\.ttf>',
1102 '/<filename:re:.+\.eot>', '/<filename:re:.+\.woff>',
1103 '/<filename:re:.+\.woff2>', '/<filename:re:.+\.map>',
1104 '/<filename:re:.+\.png>', '/<filename:re:.+\.html>',
1105 '/<filename:re:.+\.ico>']
1106
1107 # The mimetypes module knows about most types, but not these
1108 content_types = {
1109 '.eot': 'application/vnd.ms-fontobject',
1110 '.woff': 'application/x-font-woff',
1111 '.woff2': 'application/x-font-woff2',
1112 '.ttf': 'application/x-font-ttf',
1113 '.map': 'application/json'
1114 }
1115
1116 _require_auth = None
1117 suppress_json_resp = True
1118
1119 def __init__(self, app, bus):
1120 super(WebHandler, self).__init__(
1121 app, bus, self.verbs, self.rules)
1122
1123 def get_type(self, filename):
1124 ''' Returns the content type and encoding for a file '''
1125
1126 content_type, encoding = mimetypes.guess_type(filename)
1127
1128 # Try our own list if mimetypes didn't recognize it
1129 if content_type is None:
1130 if filename[-3:] == '.gz':
1131 filename = filename[:-3]
1132 extension = filename[filename.rfind('.'):]
1133 content_type = self.content_types.get(extension, None)
1134
1135 return content_type, encoding
1136
1137 def do_get(self, filename='index.html'):
1138
1139 # If a gzipped version exists, use that instead.
1140 # Possible future enhancement: if the client doesn't
1141 # accept compressed files, unzip it ourselves before sending.
1142 if not os.path.exists(os.path.join(www_base_path, filename)):
1143 filename = filename + '.gz'
1144
1145 # Though bottle should protect us, ensure path is valid
1146 realpath = os.path.realpath(filename)
1147 if realpath[0] == '/':
1148 realpath = realpath[1:]
1149 if not os.path.exists(os.path.join(www_base_path, realpath)):
1150 abort(404, "Path not found")
1151
1152 mimetype, encoding = self.get_type(filename)
1153
1154 # Couldn't find the type - let static_file() deal with it,
1155 # though this should never happen.
1156 if mimetype is None:
1157 print("Can't figure out content-type for %s" % filename)
1158 mimetype = 'auto'
1159
1160 # This call will set several header fields for us,
1161 # including the charset if the type is text.
1162 response = static_file(filename, www_base_path, mimetype)
1163
1164 # static_file() will only set the encoding if the
1165 # mimetype was auto, so set it here.
1166 if encoding is not None:
1167 response.set_header('Content-Encoding', encoding)
1168
1169 return response
1170
1171 def find(self, **kw):
1172 pass
1173
1174 def setup(self, **kw):
1175 pass
1176
1177
Brad Bishop2f428582015-12-02 10:56:11 -05001178class AuthorizationPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001179 ''' Invokes an optional list of authorization callbacks. '''
Brad Bishop2f428582015-12-02 10:56:11 -05001180
Brad Bishop87b63c12016-03-18 14:47:51 -04001181 name = 'authorization'
1182 api = 2
Brad Bishop2f428582015-12-02 10:56:11 -05001183
Brad Bishop87b63c12016-03-18 14:47:51 -04001184 class Compose:
1185 def __init__(self, validators, callback, session_mgr):
1186 self.validators = validators
1187 self.callback = callback
1188 self.session_mgr = session_mgr
Brad Bishop2f428582015-12-02 10:56:11 -05001189
Brad Bishop87b63c12016-03-18 14:47:51 -04001190 def __call__(self, *a, **kw):
1191 sid = request.get_cookie('sid', secret=self.session_mgr.hmac_key)
1192 session = self.session_mgr.get_session(sid)
Brad Bishopd4c1c552017-02-21 00:07:28 -05001193 if request.method != 'OPTIONS':
1194 for x in self.validators:
1195 x(session, *a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -05001196
Brad Bishop87b63c12016-03-18 14:47:51 -04001197 return self.callback(*a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -05001198
Brad Bishop87b63c12016-03-18 14:47:51 -04001199 def apply(self, callback, route):
1200 undecorated = route.get_undecorated_callback()
1201 if not isinstance(undecorated, RouteHandler):
1202 return callback
Brad Bishop2f428582015-12-02 10:56:11 -05001203
Brad Bishop87b63c12016-03-18 14:47:51 -04001204 auth_types = getattr(
1205 undecorated, '_require_auth', None)
1206 if not auth_types:
1207 return callback
Brad Bishop2f428582015-12-02 10:56:11 -05001208
Brad Bishop87b63c12016-03-18 14:47:51 -04001209 return self.Compose(
1210 auth_types, callback, undecorated.app.session_handler)
1211
Brad Bishop2f428582015-12-02 10:56:11 -05001212
Brad Bishopd0c404a2017-02-21 09:23:25 -05001213class CorsPlugin(object):
1214 ''' Add CORS headers. '''
1215
1216 name = 'cors'
1217 api = 2
1218
1219 @staticmethod
1220 def process_origin():
1221 origin = request.headers.get('Origin')
1222 if origin:
1223 response.add_header('Access-Control-Allow-Origin', origin)
1224 response.add_header(
1225 'Access-Control-Allow-Credentials', 'true')
1226
1227 @staticmethod
1228 def process_method_and_headers(verbs):
1229 method = request.headers.get('Access-Control-Request-Method')
1230 headers = request.headers.get('Access-Control-Request-Headers')
1231 if headers:
1232 headers = [x.lower() for x in headers.split(',')]
1233
1234 if method in verbs \
1235 and headers == ['content-type']:
1236 response.add_header('Access-Control-Allow-Methods', method)
1237 response.add_header(
1238 'Access-Control-Allow-Headers', 'Content-Type')
Ratan Gupta91b46f82018-01-14 12:52:23 +05301239 response.add_header('X-Frame-Options', 'deny')
1240 response.add_header('X-Content-Type-Options', 'nosniff')
1241 response.add_header('X-XSS-Protection', '1; mode=block')
1242 response.add_header(
1243 'Content-Security-Policy', "default-src 'self'")
1244 response.add_header(
1245 'Strict-Transport-Security',
1246 'max-age=31536000; includeSubDomains; preload')
Brad Bishopd0c404a2017-02-21 09:23:25 -05001247
1248 def __init__(self, app):
1249 app.install_error_callback(self.error_callback)
1250
1251 def apply(self, callback, route):
1252 undecorated = route.get_undecorated_callback()
1253 if not isinstance(undecorated, RouteHandler):
1254 return callback
1255
1256 if not getattr(undecorated, '_enable_cors', None):
1257 return callback
1258
1259 def wrap(*a, **kw):
1260 self.process_origin()
1261 self.process_method_and_headers(undecorated._verbs)
1262 return callback(*a, **kw)
1263
1264 return wrap
1265
1266 def error_callback(self, **kw):
1267 self.process_origin()
1268
1269
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001270class JsonApiRequestPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001271 ''' Ensures request content satisfies the OpenBMC json api format. '''
1272 name = 'json_api_request'
1273 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001274
Brad Bishop87b63c12016-03-18 14:47:51 -04001275 error_str = "Expecting request format { 'data': <value> }, got '%s'"
1276 type_error_str = "Unsupported Content-Type: '%s'"
1277 json_type = "application/json"
1278 request_methods = ['PUT', 'POST', 'PATCH']
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001279
Brad Bishop87b63c12016-03-18 14:47:51 -04001280 @staticmethod
1281 def content_expected():
1282 return request.method in JsonApiRequestPlugin.request_methods
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001283
Brad Bishop87b63c12016-03-18 14:47:51 -04001284 def validate_request(self):
1285 if request.content_length > 0 and \
1286 request.content_type != self.json_type:
1287 abort(415, self.type_error_str % request.content_type)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001288
Brad Bishop87b63c12016-03-18 14:47:51 -04001289 try:
1290 request.parameter_list = request.json.get('data')
CamVan Nguyen249d1322018-03-05 10:08:33 -06001291 except ValueError as e:
Brad Bishop87b63c12016-03-18 14:47:51 -04001292 abort(400, str(e))
1293 except (AttributeError, KeyError, TypeError):
1294 abort(400, self.error_str % request.json)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001295
Brad Bishop87b63c12016-03-18 14:47:51 -04001296 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001297 content_type = getattr(
1298 route.get_undecorated_callback(), '_content_type', None)
1299 if self.json_type != content_type:
1300 return callback
1301
Brad Bishop87b63c12016-03-18 14:47:51 -04001302 verbs = getattr(
1303 route.get_undecorated_callback(), '_verbs', None)
1304 if verbs is None:
1305 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001306
Brad Bishop87b63c12016-03-18 14:47:51 -04001307 if not set(self.request_methods).intersection(verbs):
1308 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001309
Brad Bishop87b63c12016-03-18 14:47:51 -04001310 def wrap(*a, **kw):
1311 if self.content_expected():
1312 self.validate_request()
1313 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001314
Brad Bishop87b63c12016-03-18 14:47:51 -04001315 return wrap
1316
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001317
1318class JsonApiRequestTypePlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -04001319 ''' Ensures request content type satisfies the OpenBMC json api format. '''
1320 name = 'json_api_method_request'
1321 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001322
Brad Bishop87b63c12016-03-18 14:47:51 -04001323 error_str = "Expecting request format { 'data': %s }, got '%s'"
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001324 json_type = "application/json"
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001325
Brad Bishop87b63c12016-03-18 14:47:51 -04001326 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -05001327 content_type = getattr(
1328 route.get_undecorated_callback(), '_content_type', None)
1329 if self.json_type != content_type:
1330 return callback
1331
Brad Bishop87b63c12016-03-18 14:47:51 -04001332 request_type = getattr(
1333 route.get_undecorated_callback(), 'request_type', None)
1334 if request_type is None:
1335 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001336
Brad Bishop87b63c12016-03-18 14:47:51 -04001337 def validate_request():
1338 if not isinstance(request.parameter_list, request_type):
1339 abort(400, self.error_str % (str(request_type), request.json))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001340
Brad Bishop87b63c12016-03-18 14:47:51 -04001341 def wrap(*a, **kw):
1342 if JsonApiRequestPlugin.content_expected():
1343 validate_request()
1344 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001345
Brad Bishop87b63c12016-03-18 14:47:51 -04001346 return wrap
1347
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001348
Brad Bishop080a48e2017-02-21 22:34:43 -05001349class JsonErrorsPlugin(JSONPlugin):
1350 ''' Extend the Bottle JSONPlugin such that it also encodes error
1351 responses. '''
1352
1353 def __init__(self, app, **kw):
1354 super(JsonErrorsPlugin, self).__init__(**kw)
1355 self.json_opts = {
CamVan Nguyen249d1322018-03-05 10:08:33 -06001356 x: y for x, y in kw.items()
Brad Bishop080a48e2017-02-21 22:34:43 -05001357 if x in ['indent', 'sort_keys']}
1358 app.install_error_callback(self.error_callback)
1359
1360 def error_callback(self, response_object, response_body, **kw):
1361 response_body['body'] = json.dumps(response_object, **self.json_opts)
1362 response.content_type = 'application/json'
1363
1364
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001365class JsonApiResponsePlugin(object):
Brad Bishop080a48e2017-02-21 22:34:43 -05001366 ''' Emits responses in the OpenBMC json api format. '''
Brad Bishop87b63c12016-03-18 14:47:51 -04001367 name = 'json_api_response'
1368 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001369
Brad Bishopd4c1c552017-02-21 00:07:28 -05001370 @staticmethod
1371 def has_body():
1372 return request.method not in ['OPTIONS']
1373
Brad Bishop080a48e2017-02-21 22:34:43 -05001374 def __init__(self, app):
1375 app.install_error_callback(self.error_callback)
1376
Brad Bishop87b63c12016-03-18 14:47:51 -04001377 def apply(self, callback, route):
Brad Bishop944cd042017-07-10 16:42:41 -04001378 skip = getattr(
1379 route.get_undecorated_callback(), 'suppress_json_resp', None)
1380 if skip:
Jayanth Othayoth1444fd82017-06-29 05:45:07 -05001381 return callback
1382
Brad Bishop87b63c12016-03-18 14:47:51 -04001383 def wrap(*a, **kw):
Brad Bishopd4c1c552017-02-21 00:07:28 -05001384 data = callback(*a, **kw)
1385 if self.has_body():
1386 resp = {'data': data}
1387 resp['status'] = 'ok'
1388 resp['message'] = response.status_line
1389 return resp
Brad Bishop87b63c12016-03-18 14:47:51 -04001390 return wrap
1391
Brad Bishop080a48e2017-02-21 22:34:43 -05001392 def error_callback(self, error, response_object, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -04001393 response_object['message'] = error.status_line
Brad Bishop9c2531e2017-03-07 10:22:40 -05001394 response_object['status'] = 'error'
Brad Bishop080a48e2017-02-21 22:34:43 -05001395 response_object.setdefault('data', {})['description'] = str(error.body)
Brad Bishop87b63c12016-03-18 14:47:51 -04001396 if error.status_code == 500:
1397 response_object['data']['exception'] = repr(error.exception)
1398 response_object['data']['traceback'] = error.traceback.splitlines()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001399
Brad Bishop87b63c12016-03-18 14:47:51 -04001400
Brad Bishop080a48e2017-02-21 22:34:43 -05001401class JsonpPlugin(object):
Brad Bishop80fe37a2016-03-29 10:54:54 -04001402 ''' Json javascript wrapper. '''
1403 name = 'jsonp'
1404 api = 2
1405
Brad Bishop080a48e2017-02-21 22:34:43 -05001406 def __init__(self, app, **kw):
1407 app.install_error_callback(self.error_callback)
Brad Bishop80fe37a2016-03-29 10:54:54 -04001408
1409 @staticmethod
1410 def to_jsonp(json):
1411 jwrapper = request.query.callback or None
1412 if(jwrapper):
1413 response.set_header('Content-Type', 'application/javascript')
1414 json = jwrapper + '(' + json + ');'
1415 return json
1416
1417 def apply(self, callback, route):
1418 def wrap(*a, **kw):
1419 return self.to_jsonp(callback(*a, **kw))
1420 return wrap
1421
Brad Bishop080a48e2017-02-21 22:34:43 -05001422 def error_callback(self, response_body, **kw):
1423 response_body['body'] = self.to_jsonp(response_body['body'])
Brad Bishop80fe37a2016-03-29 10:54:54 -04001424
1425
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001426class ContentCheckerPlugin(object):
1427 ''' Ensures that a route is associated with the expected content-type
1428 header. '''
1429 name = 'content_checker'
1430 api = 2
1431
1432 class Checker:
1433 def __init__(self, type, callback):
1434 self.expected_type = type
1435 self.callback = callback
1436 self.error_str = "Expecting content type '%s', got '%s'"
1437
1438 def __call__(self, *a, **kw):
Deepak Kodihallidb1a21e2017-04-27 06:30:11 -05001439 if request.method in ['PUT', 'POST', 'PATCH'] and \
1440 self.expected_type and \
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001441 self.expected_type != request.content_type:
1442 abort(415, self.error_str % (self.expected_type,
1443 request.content_type))
1444
1445 return self.callback(*a, **kw)
1446
1447 def apply(self, callback, route):
1448 content_type = getattr(
1449 route.get_undecorated_callback(), '_content_type', None)
1450
1451 return self.Checker(content_type, callback)
1452
1453
Brad Bishop2c6fc762016-08-29 15:53:25 -04001454class App(Bottle):
Deepak Kodihalli0fe213f2017-10-11 00:08:48 -05001455 def __init__(self, **kw):
Brad Bishop2c6fc762016-08-29 15:53:25 -04001456 super(App, self).__init__(autojson=False)
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001457
1458 self.have_wsock = kw.get('have_wsock', False)
Alexander Filippovd08a4562018-03-20 12:02:23 +03001459 self.with_bmc_check = '--with-bmc-check' in sys.argv
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001460
Brad Bishop2ddfa002016-08-29 15:11:55 -04001461 self.bus = dbus.SystemBus()
1462 self.mapper = obmc.mapper.Mapper(self.bus)
Brad Bishop080a48e2017-02-21 22:34:43 -05001463 self.error_callbacks = []
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001464
Brad Bishop87b63c12016-03-18 14:47:51 -04001465 self.install_hooks()
1466 self.install_plugins()
1467 self.create_handlers()
1468 self.install_handlers()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001469
Brad Bishop87b63c12016-03-18 14:47:51 -04001470 def install_plugins(self):
1471 # install json api plugins
1472 json_kw = {'indent': 2, 'sort_keys': True}
Brad Bishop87b63c12016-03-18 14:47:51 -04001473 self.install(AuthorizationPlugin())
Brad Bishopd0c404a2017-02-21 09:23:25 -05001474 self.install(CorsPlugin(self))
Deepak Kodihalli461367a2017-04-10 07:11:38 -05001475 self.install(ContentCheckerPlugin())
Brad Bishop080a48e2017-02-21 22:34:43 -05001476 self.install(JsonpPlugin(self, **json_kw))
1477 self.install(JsonErrorsPlugin(self, **json_kw))
1478 self.install(JsonApiResponsePlugin(self))
Brad Bishop87b63c12016-03-18 14:47:51 -04001479 self.install(JsonApiRequestPlugin())
1480 self.install(JsonApiRequestTypePlugin())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001481
Brad Bishop87b63c12016-03-18 14:47:51 -04001482 def install_hooks(self):
Brad Bishop080a48e2017-02-21 22:34:43 -05001483 self.error_handler_type = type(self.default_error_handler)
1484 self.original_error_handler = self.default_error_handler
1485 self.default_error_handler = self.error_handler_type(
1486 self.custom_error_handler, self, Bottle)
1487
Brad Bishop87b63c12016-03-18 14:47:51 -04001488 self.real_router_match = self.router.match
1489 self.router.match = self.custom_router_match
1490 self.add_hook('before_request', self.strip_extra_slashes)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001491
Brad Bishop87b63c12016-03-18 14:47:51 -04001492 def create_handlers(self):
1493 # create route handlers
1494 self.session_handler = SessionHandler(self, self.bus)
Matt Spinlerd41643e2018-02-02 13:51:38 -06001495 self.web_handler = WebHandler(self, self.bus)
Brad Bishop87b63c12016-03-18 14:47:51 -04001496 self.directory_handler = DirectoryHandler(self, self.bus)
1497 self.list_names_handler = ListNamesHandler(self, self.bus)
1498 self.list_handler = ListHandler(self, self.bus)
1499 self.method_handler = MethodHandler(self, self.bus)
1500 self.property_handler = PropertyHandler(self, self.bus)
1501 self.schema_handler = SchemaHandler(self, self.bus)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001502 self.image_upload_post_handler = ImagePostHandler(self, self.bus)
1503 self.image_upload_put_handler = ImagePutHandler(self, self.bus)
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001504 self.download_dump_get_handler = DownloadDumpHandler(self, self.bus)
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001505 if self.have_wsock:
1506 self.event_handler = EventHandler(self, self.bus)
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001507 self.host_console_handler = HostConsoleHandler(self, self.bus)
Brad Bishop87b63c12016-03-18 14:47:51 -04001508 self.instance_handler = InstanceHandler(self, self.bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001509
Brad Bishop87b63c12016-03-18 14:47:51 -04001510 def install_handlers(self):
1511 self.session_handler.install()
Matt Spinlerd41643e2018-02-02 13:51:38 -06001512 self.web_handler.install()
Brad Bishop87b63c12016-03-18 14:47:51 -04001513 self.directory_handler.install()
1514 self.list_names_handler.install()
1515 self.list_handler.install()
1516 self.method_handler.install()
1517 self.property_handler.install()
1518 self.schema_handler.install()
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -05001519 self.image_upload_post_handler.install()
1520 self.image_upload_put_handler.install()
Jayanth Othayoth9bc94992017-06-29 06:30:40 -05001521 self.download_dump_get_handler.install()
Deepak Kodihallib209dd12017-10-11 01:19:17 -05001522 if self.have_wsock:
1523 self.event_handler.install()
Deepak Kodihalli5c518f62018-04-23 03:26:38 -05001524 self.host_console_handler.install()
Brad Bishop87b63c12016-03-18 14:47:51 -04001525 # this has to come last, since it matches everything
1526 self.instance_handler.install()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001527
Brad Bishop080a48e2017-02-21 22:34:43 -05001528 def install_error_callback(self, callback):
1529 self.error_callbacks.insert(0, callback)
1530
Brad Bishop87b63c12016-03-18 14:47:51 -04001531 def custom_router_match(self, environ):
1532 ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is
1533 needed doesn't work for us since the instance rules match
1534 everything. This monkey-patch lets the route handler figure
1535 out which response is needed. This could be accomplished
1536 with a hook but that would require calling the router match
1537 function twice.
1538 '''
1539 route, args = self.real_router_match(environ)
1540 if isinstance(route.callback, RouteHandler):
1541 route.callback._setup(**args)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001542
Brad Bishop87b63c12016-03-18 14:47:51 -04001543 return route, args
Brad Bishopb1cbdaf2015-11-13 21:28:16 -05001544
Brad Bishop080a48e2017-02-21 22:34:43 -05001545 def custom_error_handler(self, res, error):
Gunnar Millsf01d0ba2017-10-25 20:37:24 -05001546 ''' Allow plugins to modify error responses too via this custom
Brad Bishop080a48e2017-02-21 22:34:43 -05001547 error handler. '''
1548
1549 response_object = {}
1550 response_body = {}
1551 for x in self.error_callbacks:
1552 x(error=error,
1553 response_object=response_object,
1554 response_body=response_body)
1555
1556 return response_body.get('body', "")
1557
Brad Bishop87b63c12016-03-18 14:47:51 -04001558 @staticmethod
1559 def strip_extra_slashes():
1560 path = request.environ['PATH_INFO']
1561 trailing = ("", "/")[path[-1] == '/']
CamVan Nguyen249d1322018-03-05 10:08:33 -06001562 parts = list(filter(bool, path.split('/')))
Brad Bishop87b63c12016-03-18 14:47:51 -04001563 request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing