blob: 55d5b4431c91153a3ca3373b6a6d0afdd819e40f [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
Brad Bishopaa65f6e2015-10-27 16:28:51 -040018import dbus
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050019import dbus.exceptions
20import json
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050021from xml.etree import ElementTree
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050022from bottle import Bottle, abort, request, response, JSONPlugin, HTTPError
Brad Bishopb103d2d2016-03-04 16:19:14 -050023import obmc.utils.misc
Brad Bishopb103d2d2016-03-04 16:19:14 -050024from obmc.dbuslib.introspection import IntrospectionNodeParser
25import obmc.mapper
Brad Bishop2f428582015-12-02 10:56:11 -050026import spwd
27import grp
28import crypt
Deepak Kodihalli1af301a2017-04-11 07:29:01 -050029import tempfile
Brad Bishopaa65f6e2015-10-27 16:28:51 -040030
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050031DBUS_UNKNOWN_INTERFACE = 'org.freedesktop.UnknownInterface'
Brad Bishopf4e74982016-04-01 14:53:05 -040032DBUS_UNKNOWN_INTERFACE_ERROR = 'org.freedesktop.DBus.Error.UnknownInterface'
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050033DBUS_UNKNOWN_METHOD = 'org.freedesktop.DBus.Error.UnknownMethod'
34DBUS_INVALID_ARGS = 'org.freedesktop.DBus.Error.InvalidArgs'
Brad Bishopd4578922015-12-02 11:10:36 -050035DBUS_TYPE_ERROR = 'org.freedesktop.DBus.Python.TypeError'
Deepak Kodihalli6075bb42017-04-04 05:49:17 -050036DELETE_IFACE = 'xyz.openbmc_project.Object.Delete'
Brad Bishop9ee57c42015-11-03 14:59:29 -050037
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050038_4034_msg = "The specified %s cannot be %s: '%s'"
Brad Bishopaa65f6e2015-10-27 16:28:51 -040039
Brad Bishop87b63c12016-03-18 14:47:51 -040040
Brad Bishop2f428582015-12-02 10:56:11 -050041def valid_user(session, *a, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -040042 ''' Authorization plugin callback that checks
43 that the user is logged in. '''
44 if session is None:
Brad Bishopdc3fbfa2016-09-08 09:51:38 -040045 abort(401, 'Login required')
Brad Bishop87b63c12016-03-18 14:47:51 -040046
Brad Bishop2f428582015-12-02 10:56:11 -050047
48class UserInGroup:
Brad Bishop87b63c12016-03-18 14:47:51 -040049 ''' Authorization plugin callback that checks that the user is logged in
50 and a member of a group. '''
51 def __init__(self, group):
52 self.group = group
Brad Bishop2f428582015-12-02 10:56:11 -050053
Brad Bishop87b63c12016-03-18 14:47:51 -040054 def __call__(self, session, *a, **kw):
55 valid_user(session, *a, **kw)
56 res = False
Brad Bishop2f428582015-12-02 10:56:11 -050057
Brad Bishop87b63c12016-03-18 14:47:51 -040058 try:
59 res = session['user'] in grp.getgrnam(self.group)[3]
60 except KeyError:
61 pass
Brad Bishop2f428582015-12-02 10:56:11 -050062
Brad Bishop87b63c12016-03-18 14:47:51 -040063 if not res:
64 abort(403, 'Insufficient access')
65
Brad Bishop2f428582015-12-02 10:56:11 -050066
Brad Bishopb1cbdaf2015-11-13 21:28:16 -050067class RouteHandler(object):
Brad Bishop6d190602016-04-15 13:09:39 -040068 _require_auth = obmc.utils.misc.makelist(valid_user)
Brad Bishopd0c404a2017-02-21 09:23:25 -050069 _enable_cors = True
Brad Bishopaa65f6e2015-10-27 16:28:51 -040070
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -050071 def __init__(self, app, bus, verbs, rules, content_type=''):
Brad Bishop87b63c12016-03-18 14:47:51 -040072 self.app = app
73 self.bus = bus
Brad Bishopb103d2d2016-03-04 16:19:14 -050074 self.mapper = obmc.mapper.Mapper(bus)
Brad Bishop6d190602016-04-15 13:09:39 -040075 self._verbs = obmc.utils.misc.makelist(verbs)
Brad Bishop87b63c12016-03-18 14:47:51 -040076 self._rules = rules
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -050077 self._content_type = content_type
Brad Bishop0f79e522016-03-18 13:33:17 -040078 self.intf_match = obmc.utils.misc.org_dot_openbmc_match
Brad Bishopaa65f6e2015-10-27 16:28:51 -040079
Brad Bishop88c76a42017-02-21 00:02:02 -050080 if 'GET' in self._verbs:
81 self._verbs = list(set(self._verbs + ['HEAD']))
Brad Bishopd4c1c552017-02-21 00:07:28 -050082 if 'OPTIONS' not in self._verbs:
83 self._verbs.append('OPTIONS')
Brad Bishop88c76a42017-02-21 00:02:02 -050084
Brad Bishop87b63c12016-03-18 14:47:51 -040085 def _setup(self, **kw):
86 request.route_data = {}
Brad Bishopd4c1c552017-02-21 00:07:28 -050087
Brad Bishop87b63c12016-03-18 14:47:51 -040088 if request.method in self._verbs:
Brad Bishopd4c1c552017-02-21 00:07:28 -050089 if request.method != 'OPTIONS':
90 return self.setup(**kw)
Brad Bishop88c76a42017-02-21 00:02:02 -050091
Brad Bishopd4c1c552017-02-21 00:07:28 -050092 # Javascript implementations will not send credentials
93 # with an OPTIONS request. Don't help malicious clients
94 # by checking the path here and returning a 404 if the
95 # path doesn't exist.
96 return None
Brad Bishop88c76a42017-02-21 00:02:02 -050097
Brad Bishopd4c1c552017-02-21 00:07:28 -050098 # Return 405
Brad Bishop88c76a42017-02-21 00:02:02 -050099 raise HTTPError(
100 405, "Method not allowed.", Allow=','.join(self._verbs))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400101
Brad Bishop87b63c12016-03-18 14:47:51 -0400102 def __call__(self, **kw):
103 return getattr(self, 'do_' + request.method.lower())(**kw)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400104
Brad Bishop88c76a42017-02-21 00:02:02 -0500105 def do_head(self, **kw):
106 return self.do_get(**kw)
107
Brad Bishopd4c1c552017-02-21 00:07:28 -0500108 def do_options(self, **kw):
109 for v in self._verbs:
110 response.set_header(
111 'Allow',
112 ','.join(self._verbs))
113 return None
114
Brad Bishop87b63c12016-03-18 14:47:51 -0400115 def install(self):
116 self.app.route(
117 self._rules, callback=self,
Brad Bishopd4c1c552017-02-21 00:07:28 -0500118 method=['OPTIONS', 'GET', 'PUT', 'PATCH', 'POST', 'DELETE'])
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400119
Brad Bishop87b63c12016-03-18 14:47:51 -0400120 @staticmethod
121 def try_mapper_call(f, callback=None, **kw):
122 try:
123 return f(**kw)
124 except dbus.exceptions.DBusException, e:
Brad Bishopfce77562016-11-28 15:44:18 -0500125 if e.get_dbus_name() == \
126 'org.freedesktop.DBus.Error.ObjectPathInUse':
127 abort(503, str(e))
Brad Bishopb103d2d2016-03-04 16:19:14 -0500128 if e.get_dbus_name() != obmc.mapper.MAPPER_NOT_FOUND:
Brad Bishop87b63c12016-03-18 14:47:51 -0400129 raise
130 if callback is None:
131 def callback(e, **kw):
132 abort(404, str(e))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400133
Brad Bishop87b63c12016-03-18 14:47:51 -0400134 callback(e, **kw)
135
136 @staticmethod
137 def try_properties_interface(f, *a):
138 try:
139 return f(*a)
140 except dbus.exceptions.DBusException, e:
141 if DBUS_UNKNOWN_INTERFACE in e.get_dbus_message():
142 # interface doesn't have any properties
143 return None
Brad Bishopf4e74982016-04-01 14:53:05 -0400144 if DBUS_UNKNOWN_INTERFACE_ERROR in e.get_dbus_name():
145 # interface doesn't have any properties
146 return None
Brad Bishop87b63c12016-03-18 14:47:51 -0400147 if DBUS_UNKNOWN_METHOD == e.get_dbus_name():
148 # properties interface not implemented at all
149 return None
150 raise
151
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400152
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500153class DirectoryHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400154 verbs = 'GET'
155 rules = '<path:path>/'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400156
Brad Bishop87b63c12016-03-18 14:47:51 -0400157 def __init__(self, app, bus):
158 super(DirectoryHandler, self).__init__(
159 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400160
Brad Bishop87b63c12016-03-18 14:47:51 -0400161 def find(self, path='/'):
162 return self.try_mapper_call(
163 self.mapper.get_subtree_paths, path=path, depth=1)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400164
Brad Bishop87b63c12016-03-18 14:47:51 -0400165 def setup(self, path='/'):
166 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400167
Brad Bishop87b63c12016-03-18 14:47:51 -0400168 def do_get(self, path='/'):
169 return request.route_data['map']
170
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400171
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500172class ListNamesHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400173 verbs = 'GET'
174 rules = ['/list', '<path:path>/list']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400175
Brad Bishop87b63c12016-03-18 14:47:51 -0400176 def __init__(self, app, bus):
177 super(ListNamesHandler, self).__init__(
178 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400179
Brad Bishop87b63c12016-03-18 14:47:51 -0400180 def find(self, path='/'):
181 return self.try_mapper_call(
182 self.mapper.get_subtree, path=path).keys()
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400183
Brad Bishop87b63c12016-03-18 14:47:51 -0400184 def setup(self, path='/'):
185 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400186
Brad Bishop87b63c12016-03-18 14:47:51 -0400187 def do_get(self, path='/'):
188 return request.route_data['map']
189
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400190
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500191class ListHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400192 verbs = 'GET'
193 rules = ['/enumerate', '<path:path>/enumerate']
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400194
Brad Bishop87b63c12016-03-18 14:47:51 -0400195 def __init__(self, app, bus):
196 super(ListHandler, self).__init__(
197 app, bus, self.verbs, self.rules)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400198
Brad Bishop87b63c12016-03-18 14:47:51 -0400199 def find(self, path='/'):
200 return self.try_mapper_call(
201 self.mapper.get_subtree, path=path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400202
Brad Bishop87b63c12016-03-18 14:47:51 -0400203 def setup(self, path='/'):
204 request.route_data['map'] = self.find(path)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400205
Brad Bishop87b63c12016-03-18 14:47:51 -0400206 def do_get(self, path='/'):
Brad Bishop71527b42016-04-01 14:51:14 -0400207 return {x: y for x, y in self.mapper.enumerate_subtree(
208 path,
209 mapper_data=request.route_data['map']).dataitems()}
Brad Bishop87b63c12016-03-18 14:47:51 -0400210
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400211
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500212class MethodHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400213 verbs = 'POST'
214 rules = '<path:path>/action/<method>'
215 request_type = list
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500216 content_type = 'application/json'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400217
Brad Bishop87b63c12016-03-18 14:47:51 -0400218 def __init__(self, app, bus):
219 super(MethodHandler, self).__init__(
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500220 app, bus, self.verbs, self.rules, self.content_type)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400221
Brad Bishop87b63c12016-03-18 14:47:51 -0400222 def find(self, path, method):
223 busses = self.try_mapper_call(
224 self.mapper.get_object, path=path)
225 for items in busses.iteritems():
226 m = self.find_method_on_bus(path, method, *items)
227 if m:
228 return m
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400229
Brad Bishop87b63c12016-03-18 14:47:51 -0400230 abort(404, _4034_msg % ('method', 'found', method))
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400231
Brad Bishop87b63c12016-03-18 14:47:51 -0400232 def setup(self, path, method):
233 request.route_data['method'] = self.find(path, method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400234
Brad Bishop87b63c12016-03-18 14:47:51 -0400235 def do_post(self, path, method):
236 try:
237 if request.parameter_list:
238 return request.route_data['method'](*request.parameter_list)
239 else:
240 return request.route_data['method']()
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400241
Brad Bishop87b63c12016-03-18 14:47:51 -0400242 except dbus.exceptions.DBusException, e:
243 if e.get_dbus_name() == DBUS_INVALID_ARGS:
244 abort(400, str(e))
245 if e.get_dbus_name() == DBUS_TYPE_ERROR:
246 abort(400, str(e))
247 raise
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400248
Brad Bishop87b63c12016-03-18 14:47:51 -0400249 @staticmethod
250 def find_method_in_interface(method, obj, interface, methods):
251 if methods is None:
252 return None
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400253
Brad Bishop6d190602016-04-15 13:09:39 -0400254 method = obmc.utils.misc.find_case_insensitive(method, methods.keys())
Brad Bishop87b63c12016-03-18 14:47:51 -0400255 if method is not None:
256 iface = dbus.Interface(obj, interface)
257 return iface.get_dbus_method(method)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400258
Brad Bishop87b63c12016-03-18 14:47:51 -0400259 def find_method_on_bus(self, path, method, bus, interfaces):
260 obj = self.bus.get_object(bus, path, introspect=False)
261 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
262 data = iface.Introspect()
263 parser = IntrospectionNodeParser(
264 ElementTree.fromstring(data),
Brad Bishopb103d2d2016-03-04 16:19:14 -0500265 intf_match=obmc.utils.misc.ListMatch(interfaces))
Brad Bishop87b63c12016-03-18 14:47:51 -0400266 for x, y in parser.get_interfaces().iteritems():
267 m = self.find_method_in_interface(
268 method, obj, x, y.get('method'))
269 if m:
270 return m
271
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400272
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500273class PropertyHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400274 verbs = ['PUT', 'GET']
275 rules = '<path:path>/attr/<prop>'
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500276 content_type = 'application/json'
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400277
Brad Bishop87b63c12016-03-18 14:47:51 -0400278 def __init__(self, app, bus):
279 super(PropertyHandler, self).__init__(
Deepak Kodihalli83afbaf2017-04-10 06:37:19 -0500280 app, bus, self.verbs, self.rules, self.content_type)
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400281
Brad Bishop87b63c12016-03-18 14:47:51 -0400282 def find(self, path, prop):
283 self.app.instance_handler.setup(path)
284 obj = self.app.instance_handler.do_get(path)
Brad Bishop56ad87f2017-02-21 23:33:29 -0500285 real_name = obmc.utils.misc.find_case_insensitive(
286 prop, obj.keys())
Brad Bishopaa65f6e2015-10-27 16:28:51 -0400287
Brad Bishop56ad87f2017-02-21 23:33:29 -0500288 if not real_name:
289 if request.method == 'PUT':
290 abort(403, _4034_msg % ('property', 'created', prop))
291 else:
292 abort(404, _4034_msg % ('property', 'found', prop))
293 return real_name, {path: obj}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500294
Brad Bishop87b63c12016-03-18 14:47:51 -0400295 def setup(self, path, prop):
Brad Bishop56ad87f2017-02-21 23:33:29 -0500296 name, obj = self.find(path, prop)
297 request.route_data['obj'] = obj
298 request.route_data['name'] = name
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500299
Brad Bishop87b63c12016-03-18 14:47:51 -0400300 def do_get(self, path, prop):
Brad Bishop56ad87f2017-02-21 23:33:29 -0500301 name = request.route_data['name']
302 return request.route_data['obj'][path][name]
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500303
Brad Bishop87b63c12016-03-18 14:47:51 -0400304 def do_put(self, path, prop, value=None):
305 if value is None:
306 value = request.parameter_list
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500307
Brad Bishop87b63c12016-03-18 14:47:51 -0400308 prop, iface, properties_iface = self.get_host_interface(
309 path, prop, request.route_data['map'][path])
310 try:
311 properties_iface.Set(iface, prop, value)
312 except ValueError, e:
313 abort(400, str(e))
314 except dbus.exceptions.DBusException, e:
315 if e.get_dbus_name() == DBUS_INVALID_ARGS:
316 abort(403, str(e))
317 raise
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500318
Brad Bishop87b63c12016-03-18 14:47:51 -0400319 def get_host_interface(self, path, prop, bus_info):
320 for bus, interfaces in bus_info.iteritems():
321 obj = self.bus.get_object(bus, path, introspect=True)
322 properties_iface = dbus.Interface(
323 obj, dbus_interface=dbus.PROPERTIES_IFACE)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500324
Brad Bishop87b63c12016-03-18 14:47:51 -0400325 info = self.get_host_interface_on_bus(
326 path, prop, properties_iface, bus, interfaces)
327 if info is not None:
328 prop, iface = info
329 return prop, iface, properties_iface
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500330
Brad Bishop87b63c12016-03-18 14:47:51 -0400331 def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces):
332 for i in interfaces:
333 properties = self.try_properties_interface(iface.GetAll, i)
Brad Bishop69cb6d12017-02-21 12:01:52 -0500334 if not properties:
Brad Bishop87b63c12016-03-18 14:47:51 -0400335 continue
Brad Bishop8b0d3fa2016-11-28 15:41:47 -0500336 prop = obmc.utils.misc.find_case_insensitive(
337 prop, properties.keys())
Brad Bishop87b63c12016-03-18 14:47:51 -0400338 if prop is None:
339 continue
340 return prop, i
341
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500342
Brad Bishop2503bd62015-12-16 17:56:12 -0500343class SchemaHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400344 verbs = ['GET']
345 rules = '<path:path>/schema'
Brad Bishop2503bd62015-12-16 17:56:12 -0500346
Brad Bishop87b63c12016-03-18 14:47:51 -0400347 def __init__(self, app, bus):
348 super(SchemaHandler, self).__init__(
349 app, bus, self.verbs, self.rules)
Brad Bishop2503bd62015-12-16 17:56:12 -0500350
Brad Bishop87b63c12016-03-18 14:47:51 -0400351 def find(self, path):
352 return self.try_mapper_call(
353 self.mapper.get_object,
354 path=path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500355
Brad Bishop87b63c12016-03-18 14:47:51 -0400356 def setup(self, path):
357 request.route_data['map'] = self.find(path)
Brad Bishop2503bd62015-12-16 17:56:12 -0500358
Brad Bishop87b63c12016-03-18 14:47:51 -0400359 def do_get(self, path):
360 schema = {}
361 for x in request.route_data['map'].iterkeys():
362 obj = self.bus.get_object(x, path, introspect=False)
363 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
364 data = iface.Introspect()
365 parser = IntrospectionNodeParser(
366 ElementTree.fromstring(data))
367 for x, y in parser.get_interfaces().iteritems():
368 schema[x] = y
Brad Bishop2503bd62015-12-16 17:56:12 -0500369
Brad Bishop87b63c12016-03-18 14:47:51 -0400370 return schema
371
Brad Bishop2503bd62015-12-16 17:56:12 -0500372
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500373class InstanceHandler(RouteHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400374 verbs = ['GET', 'PUT', 'DELETE']
375 rules = '<path:path>'
376 request_type = dict
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500377
Brad Bishop87b63c12016-03-18 14:47:51 -0400378 def __init__(self, app, bus):
379 super(InstanceHandler, self).__init__(
380 app, bus, self.verbs, self.rules)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500381
Brad Bishop87b63c12016-03-18 14:47:51 -0400382 def find(self, path, callback=None):
383 return {path: self.try_mapper_call(
384 self.mapper.get_object,
385 callback,
386 path=path)}
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500387
Brad Bishop87b63c12016-03-18 14:47:51 -0400388 def setup(self, path):
389 callback = None
390 if request.method == 'PUT':
391 def callback(e, **kw):
392 abort(403, _4034_msg % ('resource', 'created', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500393
Brad Bishop87b63c12016-03-18 14:47:51 -0400394 if request.route_data.get('map') is None:
395 request.route_data['map'] = self.find(path, callback)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500396
Brad Bishop87b63c12016-03-18 14:47:51 -0400397 def do_get(self, path):
Brad Bishop71527b42016-04-01 14:51:14 -0400398 return self.mapper.enumerate_object(
399 path,
400 mapper_data=request.route_data['map'])
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500401
Brad Bishop87b63c12016-03-18 14:47:51 -0400402 def do_put(self, path):
403 # make sure all properties exist in the request
404 obj = set(self.do_get(path).keys())
405 req = set(request.parameter_list.keys())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500406
Brad Bishop87b63c12016-03-18 14:47:51 -0400407 diff = list(obj.difference(req))
408 if diff:
409 abort(403, _4034_msg % (
410 'resource', 'removed', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500411
Brad Bishop87b63c12016-03-18 14:47:51 -0400412 diff = list(req.difference(obj))
413 if diff:
414 abort(403, _4034_msg % (
415 'resource', 'created', '%s/attr/%s' % (path, diff[0])))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500416
Brad Bishop87b63c12016-03-18 14:47:51 -0400417 for p, v in request.parameter_list.iteritems():
418 self.app.property_handler.do_put(
419 path, p, v)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500420
Brad Bishop87b63c12016-03-18 14:47:51 -0400421 def do_delete(self, path):
422 for bus_info in request.route_data['map'][path].iteritems():
423 if self.bus_missing_delete(path, *bus_info):
424 abort(403, _4034_msg % ('resource', 'removed', path))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500425
Brad Bishop87b63c12016-03-18 14:47:51 -0400426 for bus in request.route_data['map'][path].iterkeys():
427 self.delete_on_bus(path, bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500428
Brad Bishop87b63c12016-03-18 14:47:51 -0400429 def bus_missing_delete(self, path, bus, interfaces):
430 return DELETE_IFACE not in interfaces
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500431
Brad Bishop87b63c12016-03-18 14:47:51 -0400432 def delete_on_bus(self, path, bus):
433 obj = self.bus.get_object(bus, path, introspect=False)
434 delete_iface = dbus.Interface(
435 obj, dbus_interface=DELETE_IFACE)
436 delete_iface.Delete()
437
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500438
Brad Bishop2f428582015-12-02 10:56:11 -0500439class SessionHandler(MethodHandler):
Brad Bishop87b63c12016-03-18 14:47:51 -0400440 ''' Handles the /login and /logout routes, manages
441 server side session store and session cookies. '''
Brad Bishop2f428582015-12-02 10:56:11 -0500442
Brad Bishop87b63c12016-03-18 14:47:51 -0400443 rules = ['/login', '/logout']
444 login_str = "User '%s' logged %s"
445 bad_passwd_str = "Invalid username or password"
446 no_user_str = "No user logged in"
447 bad_json_str = "Expecting request format { 'data': " \
448 "[<username>, <password>] }, got '%s'"
449 _require_auth = None
450 MAX_SESSIONS = 16
Brad Bishop2f428582015-12-02 10:56:11 -0500451
Brad Bishop87b63c12016-03-18 14:47:51 -0400452 def __init__(self, app, bus):
453 super(SessionHandler, self).__init__(
454 app, bus)
455 self.hmac_key = os.urandom(128)
456 self.session_store = []
Brad Bishop2f428582015-12-02 10:56:11 -0500457
Brad Bishop87b63c12016-03-18 14:47:51 -0400458 @staticmethod
459 def authenticate(username, clear):
460 try:
461 encoded = spwd.getspnam(username)[1]
462 return encoded == crypt.crypt(clear, encoded)
463 except KeyError:
464 return False
Brad Bishop2f428582015-12-02 10:56:11 -0500465
Brad Bishop87b63c12016-03-18 14:47:51 -0400466 def invalidate_session(self, session):
467 try:
468 self.session_store.remove(session)
469 except ValueError:
470 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500471
Brad Bishop87b63c12016-03-18 14:47:51 -0400472 def new_session(self):
473 sid = os.urandom(32)
474 if self.MAX_SESSIONS <= len(self.session_store):
475 self.session_store.pop()
476 self.session_store.insert(0, {'sid': sid})
Brad Bishop2f428582015-12-02 10:56:11 -0500477
Brad Bishop87b63c12016-03-18 14:47:51 -0400478 return self.session_store[0]
Brad Bishop2f428582015-12-02 10:56:11 -0500479
Brad Bishop87b63c12016-03-18 14:47:51 -0400480 def get_session(self, sid):
481 sids = [x['sid'] for x in self.session_store]
482 try:
483 return self.session_store[sids.index(sid)]
484 except ValueError:
485 return None
Brad Bishop2f428582015-12-02 10:56:11 -0500486
Brad Bishop87b63c12016-03-18 14:47:51 -0400487 def get_session_from_cookie(self):
488 return self.get_session(
489 request.get_cookie(
490 'sid', secret=self.hmac_key))
Brad Bishop2f428582015-12-02 10:56:11 -0500491
Brad Bishop87b63c12016-03-18 14:47:51 -0400492 def do_post(self, **kw):
493 if request.path == '/login':
494 return self.do_login(**kw)
495 else:
496 return self.do_logout(**kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500497
Brad Bishop87b63c12016-03-18 14:47:51 -0400498 def do_logout(self, **kw):
499 session = self.get_session_from_cookie()
500 if session is not None:
501 user = session['user']
502 self.invalidate_session(session)
503 response.delete_cookie('sid')
504 return self.login_str % (user, 'out')
Brad Bishop2f428582015-12-02 10:56:11 -0500505
Brad Bishop87b63c12016-03-18 14:47:51 -0400506 return self.no_user_str
Brad Bishop2f428582015-12-02 10:56:11 -0500507
Brad Bishop87b63c12016-03-18 14:47:51 -0400508 def do_login(self, **kw):
509 session = self.get_session_from_cookie()
510 if session is not None:
511 return self.login_str % (session['user'], 'in')
Brad Bishop2f428582015-12-02 10:56:11 -0500512
Brad Bishop87b63c12016-03-18 14:47:51 -0400513 if len(request.parameter_list) != 2:
514 abort(400, self.bad_json_str % (request.json))
Brad Bishop2f428582015-12-02 10:56:11 -0500515
Brad Bishop87b63c12016-03-18 14:47:51 -0400516 if not self.authenticate(*request.parameter_list):
Brad Bishopdc3fbfa2016-09-08 09:51:38 -0400517 abort(401, self.bad_passwd_str)
Brad Bishop2f428582015-12-02 10:56:11 -0500518
Brad Bishop87b63c12016-03-18 14:47:51 -0400519 user = request.parameter_list[0]
520 session = self.new_session()
521 session['user'] = user
522 response.set_cookie(
523 'sid', session['sid'], secret=self.hmac_key,
524 secure=True,
525 httponly=True)
526 return self.login_str % (user, 'in')
Brad Bishop2f428582015-12-02 10:56:11 -0500527
Brad Bishop87b63c12016-03-18 14:47:51 -0400528 def find(self, **kw):
529 pass
Brad Bishop2f428582015-12-02 10:56:11 -0500530
Brad Bishop87b63c12016-03-18 14:47:51 -0400531 def setup(self, **kw):
532 pass
533
Brad Bishop2f428582015-12-02 10:56:11 -0500534
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500535class ImageUploadUtils:
536 ''' Provides common utils for image upload. '''
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500537
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500538 file_loc = '/tmp/images'
539 file_prefix = 'img'
540 file_suffix = ''
541
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500542 @classmethod
543 def do_upload(cls, filename=''):
544 if not os.path.exists(cls.file_loc):
545 os.makedirs(cls.file_loc)
546 if not filename:
547 handle, filename = tempfile.mkstemp(cls.file_suffix,
548 cls.file_prefix, cls.file_loc)
549 os.close(handle)
550 else:
551 filename = os.path.join(cls.file_loc, filename)
552
553 with open(filename, "w") as fd:
554 fd.write(request.body.read())
555
556
557class ImagePostHandler(RouteHandler):
558 ''' Handles the /upload/image route. '''
559
560 verbs = ['POST']
561 rules = ['/upload/image']
562 content_type = 'application/octet-stream'
563
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500564 def __init__(self, app, bus):
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500565 super(ImagePostHandler, self).__init__(
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500566 app, bus, self.verbs, self.rules, self.content_type)
567
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500568 def do_post(self, filename=''):
569 ImageUploadUtils.do_upload()
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500570
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500571 def find(self, **kw):
572 pass
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500573
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500574 def setup(self, **kw):
575 pass
576
577
578class ImagePutHandler(RouteHandler):
579 ''' Handles the /upload/image/<filename> route. '''
580
581 verbs = ['PUT']
582 rules = ['/upload/image/<filename>']
583 content_type = 'application/octet-stream'
584
585 def __init__(self, app, bus):
586 super(ImagePutHandler, self).__init__(
587 app, bus, self.verbs, self.rules, self.content_type)
588
589 def do_put(self, filename=''):
590 ImageUploadUtils.do_upload(filename)
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500591
592 def find(self, **kw):
593 pass
594
595 def setup(self, **kw):
596 pass
597
598
Brad Bishop2f428582015-12-02 10:56:11 -0500599class AuthorizationPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400600 ''' Invokes an optional list of authorization callbacks. '''
Brad Bishop2f428582015-12-02 10:56:11 -0500601
Brad Bishop87b63c12016-03-18 14:47:51 -0400602 name = 'authorization'
603 api = 2
Brad Bishop2f428582015-12-02 10:56:11 -0500604
Brad Bishop87b63c12016-03-18 14:47:51 -0400605 class Compose:
606 def __init__(self, validators, callback, session_mgr):
607 self.validators = validators
608 self.callback = callback
609 self.session_mgr = session_mgr
Brad Bishop2f428582015-12-02 10:56:11 -0500610
Brad Bishop87b63c12016-03-18 14:47:51 -0400611 def __call__(self, *a, **kw):
612 sid = request.get_cookie('sid', secret=self.session_mgr.hmac_key)
613 session = self.session_mgr.get_session(sid)
Brad Bishopd4c1c552017-02-21 00:07:28 -0500614 if request.method != 'OPTIONS':
615 for x in self.validators:
616 x(session, *a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500617
Brad Bishop87b63c12016-03-18 14:47:51 -0400618 return self.callback(*a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500619
Brad Bishop87b63c12016-03-18 14:47:51 -0400620 def apply(self, callback, route):
621 undecorated = route.get_undecorated_callback()
622 if not isinstance(undecorated, RouteHandler):
623 return callback
Brad Bishop2f428582015-12-02 10:56:11 -0500624
Brad Bishop87b63c12016-03-18 14:47:51 -0400625 auth_types = getattr(
626 undecorated, '_require_auth', None)
627 if not auth_types:
628 return callback
Brad Bishop2f428582015-12-02 10:56:11 -0500629
Brad Bishop87b63c12016-03-18 14:47:51 -0400630 return self.Compose(
631 auth_types, callback, undecorated.app.session_handler)
632
Brad Bishop2f428582015-12-02 10:56:11 -0500633
Brad Bishopd0c404a2017-02-21 09:23:25 -0500634class CorsPlugin(object):
635 ''' Add CORS headers. '''
636
637 name = 'cors'
638 api = 2
639
640 @staticmethod
641 def process_origin():
642 origin = request.headers.get('Origin')
643 if origin:
644 response.add_header('Access-Control-Allow-Origin', origin)
645 response.add_header(
646 'Access-Control-Allow-Credentials', 'true')
647
648 @staticmethod
649 def process_method_and_headers(verbs):
650 method = request.headers.get('Access-Control-Request-Method')
651 headers = request.headers.get('Access-Control-Request-Headers')
652 if headers:
653 headers = [x.lower() for x in headers.split(',')]
654
655 if method in verbs \
656 and headers == ['content-type']:
657 response.add_header('Access-Control-Allow-Methods', method)
658 response.add_header(
659 'Access-Control-Allow-Headers', 'Content-Type')
660
661 def __init__(self, app):
662 app.install_error_callback(self.error_callback)
663
664 def apply(self, callback, route):
665 undecorated = route.get_undecorated_callback()
666 if not isinstance(undecorated, RouteHandler):
667 return callback
668
669 if not getattr(undecorated, '_enable_cors', None):
670 return callback
671
672 def wrap(*a, **kw):
673 self.process_origin()
674 self.process_method_and_headers(undecorated._verbs)
675 return callback(*a, **kw)
676
677 return wrap
678
679 def error_callback(self, **kw):
680 self.process_origin()
681
682
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500683class JsonApiRequestPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400684 ''' Ensures request content satisfies the OpenBMC json api format. '''
685 name = 'json_api_request'
686 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500687
Brad Bishop87b63c12016-03-18 14:47:51 -0400688 error_str = "Expecting request format { 'data': <value> }, got '%s'"
689 type_error_str = "Unsupported Content-Type: '%s'"
690 json_type = "application/json"
691 request_methods = ['PUT', 'POST', 'PATCH']
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500692
Brad Bishop87b63c12016-03-18 14:47:51 -0400693 @staticmethod
694 def content_expected():
695 return request.method in JsonApiRequestPlugin.request_methods
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500696
Brad Bishop87b63c12016-03-18 14:47:51 -0400697 def validate_request(self):
698 if request.content_length > 0 and \
699 request.content_type != self.json_type:
700 abort(415, self.type_error_str % request.content_type)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500701
Brad Bishop87b63c12016-03-18 14:47:51 -0400702 try:
703 request.parameter_list = request.json.get('data')
704 except ValueError, e:
705 abort(400, str(e))
706 except (AttributeError, KeyError, TypeError):
707 abort(400, self.error_str % request.json)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500708
Brad Bishop87b63c12016-03-18 14:47:51 -0400709 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -0500710 content_type = getattr(
711 route.get_undecorated_callback(), '_content_type', None)
712 if self.json_type != content_type:
713 return callback
714
Brad Bishop87b63c12016-03-18 14:47:51 -0400715 verbs = getattr(
716 route.get_undecorated_callback(), '_verbs', None)
717 if verbs is None:
718 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500719
Brad Bishop87b63c12016-03-18 14:47:51 -0400720 if not set(self.request_methods).intersection(verbs):
721 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500722
Brad Bishop87b63c12016-03-18 14:47:51 -0400723 def wrap(*a, **kw):
724 if self.content_expected():
725 self.validate_request()
726 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500727
Brad Bishop87b63c12016-03-18 14:47:51 -0400728 return wrap
729
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500730
731class JsonApiRequestTypePlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400732 ''' Ensures request content type satisfies the OpenBMC json api format. '''
733 name = 'json_api_method_request'
734 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500735
Brad Bishop87b63c12016-03-18 14:47:51 -0400736 error_str = "Expecting request format { 'data': %s }, got '%s'"
Deepak Kodihallifb6cd482017-04-10 07:27:09 -0500737 json_type = "application/json"
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500738
Brad Bishop87b63c12016-03-18 14:47:51 -0400739 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -0500740 content_type = getattr(
741 route.get_undecorated_callback(), '_content_type', None)
742 if self.json_type != content_type:
743 return callback
744
Brad Bishop87b63c12016-03-18 14:47:51 -0400745 request_type = getattr(
746 route.get_undecorated_callback(), 'request_type', None)
747 if request_type is None:
748 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500749
Brad Bishop87b63c12016-03-18 14:47:51 -0400750 def validate_request():
751 if not isinstance(request.parameter_list, request_type):
752 abort(400, self.error_str % (str(request_type), request.json))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500753
Brad Bishop87b63c12016-03-18 14:47:51 -0400754 def wrap(*a, **kw):
755 if JsonApiRequestPlugin.content_expected():
756 validate_request()
757 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500758
Brad Bishop87b63c12016-03-18 14:47:51 -0400759 return wrap
760
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500761
Brad Bishop080a48e2017-02-21 22:34:43 -0500762class JsonErrorsPlugin(JSONPlugin):
763 ''' Extend the Bottle JSONPlugin such that it also encodes error
764 responses. '''
765
766 def __init__(self, app, **kw):
767 super(JsonErrorsPlugin, self).__init__(**kw)
768 self.json_opts = {
769 x: y for x, y in kw.iteritems()
770 if x in ['indent', 'sort_keys']}
771 app.install_error_callback(self.error_callback)
772
773 def error_callback(self, response_object, response_body, **kw):
774 response_body['body'] = json.dumps(response_object, **self.json_opts)
775 response.content_type = 'application/json'
776
777
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500778class JsonApiResponsePlugin(object):
Brad Bishop080a48e2017-02-21 22:34:43 -0500779 ''' Emits responses in the OpenBMC json api format. '''
Brad Bishop87b63c12016-03-18 14:47:51 -0400780 name = 'json_api_response'
781 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500782
Brad Bishopd4c1c552017-02-21 00:07:28 -0500783 @staticmethod
784 def has_body():
785 return request.method not in ['OPTIONS']
786
Brad Bishop080a48e2017-02-21 22:34:43 -0500787 def __init__(self, app):
788 app.install_error_callback(self.error_callback)
789
Brad Bishop87b63c12016-03-18 14:47:51 -0400790 def apply(self, callback, route):
791 def wrap(*a, **kw):
Brad Bishopd4c1c552017-02-21 00:07:28 -0500792 data = callback(*a, **kw)
793 if self.has_body():
794 resp = {'data': data}
795 resp['status'] = 'ok'
796 resp['message'] = response.status_line
797 return resp
Brad Bishop87b63c12016-03-18 14:47:51 -0400798 return wrap
799
Brad Bishop080a48e2017-02-21 22:34:43 -0500800 def error_callback(self, error, response_object, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -0400801 response_object['message'] = error.status_line
Brad Bishop9c2531e2017-03-07 10:22:40 -0500802 response_object['status'] = 'error'
Brad Bishop080a48e2017-02-21 22:34:43 -0500803 response_object.setdefault('data', {})['description'] = str(error.body)
Brad Bishop87b63c12016-03-18 14:47:51 -0400804 if error.status_code == 500:
805 response_object['data']['exception'] = repr(error.exception)
806 response_object['data']['traceback'] = error.traceback.splitlines()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500807
Brad Bishop87b63c12016-03-18 14:47:51 -0400808
Brad Bishop080a48e2017-02-21 22:34:43 -0500809class JsonpPlugin(object):
Brad Bishop80fe37a2016-03-29 10:54:54 -0400810 ''' Json javascript wrapper. '''
811 name = 'jsonp'
812 api = 2
813
Brad Bishop080a48e2017-02-21 22:34:43 -0500814 def __init__(self, app, **kw):
815 app.install_error_callback(self.error_callback)
Brad Bishop80fe37a2016-03-29 10:54:54 -0400816
817 @staticmethod
818 def to_jsonp(json):
819 jwrapper = request.query.callback or None
820 if(jwrapper):
821 response.set_header('Content-Type', 'application/javascript')
822 json = jwrapper + '(' + json + ');'
823 return json
824
825 def apply(self, callback, route):
826 def wrap(*a, **kw):
827 return self.to_jsonp(callback(*a, **kw))
828 return wrap
829
Brad Bishop080a48e2017-02-21 22:34:43 -0500830 def error_callback(self, response_body, **kw):
831 response_body['body'] = self.to_jsonp(response_body['body'])
Brad Bishop80fe37a2016-03-29 10:54:54 -0400832
833
Deepak Kodihalli461367a2017-04-10 07:11:38 -0500834class ContentCheckerPlugin(object):
835 ''' Ensures that a route is associated with the expected content-type
836 header. '''
837 name = 'content_checker'
838 api = 2
839
840 class Checker:
841 def __init__(self, type, callback):
842 self.expected_type = type
843 self.callback = callback
844 self.error_str = "Expecting content type '%s', got '%s'"
845
846 def __call__(self, *a, **kw):
Deepak Kodihallidb1a21e2017-04-27 06:30:11 -0500847 if request.method in ['PUT', 'POST', 'PATCH'] and \
848 self.expected_type and \
Deepak Kodihalli461367a2017-04-10 07:11:38 -0500849 self.expected_type != request.content_type:
850 abort(415, self.error_str % (self.expected_type,
851 request.content_type))
852
853 return self.callback(*a, **kw)
854
855 def apply(self, callback, route):
856 content_type = getattr(
857 route.get_undecorated_callback(), '_content_type', None)
858
859 return self.Checker(content_type, callback)
860
861
Brad Bishop2c6fc762016-08-29 15:53:25 -0400862class App(Bottle):
Brad Bishop2ddfa002016-08-29 15:11:55 -0400863 def __init__(self):
Brad Bishop2c6fc762016-08-29 15:53:25 -0400864 super(App, self).__init__(autojson=False)
Brad Bishop2ddfa002016-08-29 15:11:55 -0400865 self.bus = dbus.SystemBus()
866 self.mapper = obmc.mapper.Mapper(self.bus)
Brad Bishop080a48e2017-02-21 22:34:43 -0500867 self.error_callbacks = []
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500868
Brad Bishop87b63c12016-03-18 14:47:51 -0400869 self.install_hooks()
870 self.install_plugins()
871 self.create_handlers()
872 self.install_handlers()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500873
Brad Bishop87b63c12016-03-18 14:47:51 -0400874 def install_plugins(self):
875 # install json api plugins
876 json_kw = {'indent': 2, 'sort_keys': True}
Brad Bishop87b63c12016-03-18 14:47:51 -0400877 self.install(AuthorizationPlugin())
Brad Bishopd0c404a2017-02-21 09:23:25 -0500878 self.install(CorsPlugin(self))
Deepak Kodihalli461367a2017-04-10 07:11:38 -0500879 self.install(ContentCheckerPlugin())
Brad Bishop080a48e2017-02-21 22:34:43 -0500880 self.install(JsonpPlugin(self, **json_kw))
881 self.install(JsonErrorsPlugin(self, **json_kw))
882 self.install(JsonApiResponsePlugin(self))
Brad Bishop87b63c12016-03-18 14:47:51 -0400883 self.install(JsonApiRequestPlugin())
884 self.install(JsonApiRequestTypePlugin())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500885
Brad Bishop87b63c12016-03-18 14:47:51 -0400886 def install_hooks(self):
Brad Bishop080a48e2017-02-21 22:34:43 -0500887 self.error_handler_type = type(self.default_error_handler)
888 self.original_error_handler = self.default_error_handler
889 self.default_error_handler = self.error_handler_type(
890 self.custom_error_handler, self, Bottle)
891
Brad Bishop87b63c12016-03-18 14:47:51 -0400892 self.real_router_match = self.router.match
893 self.router.match = self.custom_router_match
894 self.add_hook('before_request', self.strip_extra_slashes)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500895
Brad Bishop87b63c12016-03-18 14:47:51 -0400896 def create_handlers(self):
897 # create route handlers
898 self.session_handler = SessionHandler(self, self.bus)
899 self.directory_handler = DirectoryHandler(self, self.bus)
900 self.list_names_handler = ListNamesHandler(self, self.bus)
901 self.list_handler = ListHandler(self, self.bus)
902 self.method_handler = MethodHandler(self, self.bus)
903 self.property_handler = PropertyHandler(self, self.bus)
904 self.schema_handler = SchemaHandler(self, self.bus)
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500905 self.image_upload_post_handler = ImagePostHandler(self, self.bus)
906 self.image_upload_put_handler = ImagePutHandler(self, self.bus)
Brad Bishop87b63c12016-03-18 14:47:51 -0400907 self.instance_handler = InstanceHandler(self, self.bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500908
Brad Bishop87b63c12016-03-18 14:47:51 -0400909 def install_handlers(self):
910 self.session_handler.install()
911 self.directory_handler.install()
912 self.list_names_handler.install()
913 self.list_handler.install()
914 self.method_handler.install()
915 self.property_handler.install()
916 self.schema_handler.install()
Deepak Kodihalli7ec0a4f2017-04-11 07:50:27 -0500917 self.image_upload_post_handler.install()
918 self.image_upload_put_handler.install()
Brad Bishop87b63c12016-03-18 14:47:51 -0400919 # this has to come last, since it matches everything
920 self.instance_handler.install()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500921
Brad Bishop080a48e2017-02-21 22:34:43 -0500922 def install_error_callback(self, callback):
923 self.error_callbacks.insert(0, callback)
924
Brad Bishop87b63c12016-03-18 14:47:51 -0400925 def custom_router_match(self, environ):
926 ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is
927 needed doesn't work for us since the instance rules match
928 everything. This monkey-patch lets the route handler figure
929 out which response is needed. This could be accomplished
930 with a hook but that would require calling the router match
931 function twice.
932 '''
933 route, args = self.real_router_match(environ)
934 if isinstance(route.callback, RouteHandler):
935 route.callback._setup(**args)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500936
Brad Bishop87b63c12016-03-18 14:47:51 -0400937 return route, args
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500938
Brad Bishop080a48e2017-02-21 22:34:43 -0500939 def custom_error_handler(self, res, error):
940 ''' Allow plugins to modify error reponses too via this custom
941 error handler. '''
942
943 response_object = {}
944 response_body = {}
945 for x in self.error_callbacks:
946 x(error=error,
947 response_object=response_object,
948 response_body=response_body)
949
950 return response_body.get('body', "")
951
Brad Bishop87b63c12016-03-18 14:47:51 -0400952 @staticmethod
953 def strip_extra_slashes():
954 path = request.environ['PATH_INFO']
955 trailing = ("", "/")[path[-1] == '/']
956 parts = filter(bool, path.split('/'))
957 request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing