blob: 6ba2e281f70eac2109cccaba32e2ace2c854dade [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 Kodihalli1af301a2017-04-11 07:29:01 -0500535class ImageUploadHandler(RouteHandler):
536 ''' Handles the /upload route. '''
537
538 verbs = ['POST']
539 rules = ['/upload/image']
540 content_type = 'application/octet-stream'
541 file_loc = '/tmp/images'
542 file_prefix = 'img'
543 file_suffix = ''
544
545 def __init__(self, app, bus):
546 super(ImageUploadHandler, self).__init__(
547 app, bus, self.verbs, self.rules, self.content_type)
548
549 def do_post(self, **kw):
550 self.do_upload(**kw)
551
552 def do_upload(self, **kw):
553 if not os.path.exists(self.file_loc):
554 os.makedirs(self.file_loc)
555 handle, filename = tempfile.mkstemp(self.file_suffix,
556 self.file_prefix, self.file_loc)
557
558 with os.fdopen(handle, "w") as fd:
559 fd.write(request.body.read())
560
561 def find(self, **kw):
562 pass
563
564 def setup(self, **kw):
565 pass
566
567
Brad Bishop2f428582015-12-02 10:56:11 -0500568class AuthorizationPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400569 ''' Invokes an optional list of authorization callbacks. '''
Brad Bishop2f428582015-12-02 10:56:11 -0500570
Brad Bishop87b63c12016-03-18 14:47:51 -0400571 name = 'authorization'
572 api = 2
Brad Bishop2f428582015-12-02 10:56:11 -0500573
Brad Bishop87b63c12016-03-18 14:47:51 -0400574 class Compose:
575 def __init__(self, validators, callback, session_mgr):
576 self.validators = validators
577 self.callback = callback
578 self.session_mgr = session_mgr
Brad Bishop2f428582015-12-02 10:56:11 -0500579
Brad Bishop87b63c12016-03-18 14:47:51 -0400580 def __call__(self, *a, **kw):
581 sid = request.get_cookie('sid', secret=self.session_mgr.hmac_key)
582 session = self.session_mgr.get_session(sid)
Brad Bishopd4c1c552017-02-21 00:07:28 -0500583 if request.method != 'OPTIONS':
584 for x in self.validators:
585 x(session, *a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500586
Brad Bishop87b63c12016-03-18 14:47:51 -0400587 return self.callback(*a, **kw)
Brad Bishop2f428582015-12-02 10:56:11 -0500588
Brad Bishop87b63c12016-03-18 14:47:51 -0400589 def apply(self, callback, route):
590 undecorated = route.get_undecorated_callback()
591 if not isinstance(undecorated, RouteHandler):
592 return callback
Brad Bishop2f428582015-12-02 10:56:11 -0500593
Brad Bishop87b63c12016-03-18 14:47:51 -0400594 auth_types = getattr(
595 undecorated, '_require_auth', None)
596 if not auth_types:
597 return callback
Brad Bishop2f428582015-12-02 10:56:11 -0500598
Brad Bishop87b63c12016-03-18 14:47:51 -0400599 return self.Compose(
600 auth_types, callback, undecorated.app.session_handler)
601
Brad Bishop2f428582015-12-02 10:56:11 -0500602
Brad Bishopd0c404a2017-02-21 09:23:25 -0500603class CorsPlugin(object):
604 ''' Add CORS headers. '''
605
606 name = 'cors'
607 api = 2
608
609 @staticmethod
610 def process_origin():
611 origin = request.headers.get('Origin')
612 if origin:
613 response.add_header('Access-Control-Allow-Origin', origin)
614 response.add_header(
615 'Access-Control-Allow-Credentials', 'true')
616
617 @staticmethod
618 def process_method_and_headers(verbs):
619 method = request.headers.get('Access-Control-Request-Method')
620 headers = request.headers.get('Access-Control-Request-Headers')
621 if headers:
622 headers = [x.lower() for x in headers.split(',')]
623
624 if method in verbs \
625 and headers == ['content-type']:
626 response.add_header('Access-Control-Allow-Methods', method)
627 response.add_header(
628 'Access-Control-Allow-Headers', 'Content-Type')
629
630 def __init__(self, app):
631 app.install_error_callback(self.error_callback)
632
633 def apply(self, callback, route):
634 undecorated = route.get_undecorated_callback()
635 if not isinstance(undecorated, RouteHandler):
636 return callback
637
638 if not getattr(undecorated, '_enable_cors', None):
639 return callback
640
641 def wrap(*a, **kw):
642 self.process_origin()
643 self.process_method_and_headers(undecorated._verbs)
644 return callback(*a, **kw)
645
646 return wrap
647
648 def error_callback(self, **kw):
649 self.process_origin()
650
651
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500652class JsonApiRequestPlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400653 ''' Ensures request content satisfies the OpenBMC json api format. '''
654 name = 'json_api_request'
655 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500656
Brad Bishop87b63c12016-03-18 14:47:51 -0400657 error_str = "Expecting request format { 'data': <value> }, got '%s'"
658 type_error_str = "Unsupported Content-Type: '%s'"
659 json_type = "application/json"
660 request_methods = ['PUT', 'POST', 'PATCH']
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500661
Brad Bishop87b63c12016-03-18 14:47:51 -0400662 @staticmethod
663 def content_expected():
664 return request.method in JsonApiRequestPlugin.request_methods
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500665
Brad Bishop87b63c12016-03-18 14:47:51 -0400666 def validate_request(self):
667 if request.content_length > 0 and \
668 request.content_type != self.json_type:
669 abort(415, self.type_error_str % request.content_type)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500670
Brad Bishop87b63c12016-03-18 14:47:51 -0400671 try:
672 request.parameter_list = request.json.get('data')
673 except ValueError, e:
674 abort(400, str(e))
675 except (AttributeError, KeyError, TypeError):
676 abort(400, self.error_str % request.json)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500677
Brad Bishop87b63c12016-03-18 14:47:51 -0400678 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -0500679 content_type = getattr(
680 route.get_undecorated_callback(), '_content_type', None)
681 if self.json_type != content_type:
682 return callback
683
Brad Bishop87b63c12016-03-18 14:47:51 -0400684 verbs = getattr(
685 route.get_undecorated_callback(), '_verbs', None)
686 if verbs is None:
687 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500688
Brad Bishop87b63c12016-03-18 14:47:51 -0400689 if not set(self.request_methods).intersection(verbs):
690 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500691
Brad Bishop87b63c12016-03-18 14:47:51 -0400692 def wrap(*a, **kw):
693 if self.content_expected():
694 self.validate_request()
695 return callback(*a, **kw)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500696
Brad Bishop87b63c12016-03-18 14:47:51 -0400697 return wrap
698
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500699
700class JsonApiRequestTypePlugin(object):
Brad Bishop87b63c12016-03-18 14:47:51 -0400701 ''' Ensures request content type satisfies the OpenBMC json api format. '''
702 name = 'json_api_method_request'
703 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500704
Brad Bishop87b63c12016-03-18 14:47:51 -0400705 error_str = "Expecting request format { 'data': %s }, got '%s'"
Deepak Kodihallifb6cd482017-04-10 07:27:09 -0500706 json_type = "application/json"
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500707
Brad Bishop87b63c12016-03-18 14:47:51 -0400708 def apply(self, callback, route):
Deepak Kodihallifb6cd482017-04-10 07:27:09 -0500709 content_type = getattr(
710 route.get_undecorated_callback(), '_content_type', None)
711 if self.json_type != content_type:
712 return callback
713
Brad Bishop87b63c12016-03-18 14:47:51 -0400714 request_type = getattr(
715 route.get_undecorated_callback(), 'request_type', None)
716 if request_type is None:
717 return callback
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500718
Brad Bishop87b63c12016-03-18 14:47:51 -0400719 def validate_request():
720 if not isinstance(request.parameter_list, request_type):
721 abort(400, self.error_str % (str(request_type), request.json))
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500722
Brad Bishop87b63c12016-03-18 14:47:51 -0400723 def wrap(*a, **kw):
724 if JsonApiRequestPlugin.content_expected():
725 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
Brad Bishop080a48e2017-02-21 22:34:43 -0500731class JsonErrorsPlugin(JSONPlugin):
732 ''' Extend the Bottle JSONPlugin such that it also encodes error
733 responses. '''
734
735 def __init__(self, app, **kw):
736 super(JsonErrorsPlugin, self).__init__(**kw)
737 self.json_opts = {
738 x: y for x, y in kw.iteritems()
739 if x in ['indent', 'sort_keys']}
740 app.install_error_callback(self.error_callback)
741
742 def error_callback(self, response_object, response_body, **kw):
743 response_body['body'] = json.dumps(response_object, **self.json_opts)
744 response.content_type = 'application/json'
745
746
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500747class JsonApiResponsePlugin(object):
Brad Bishop080a48e2017-02-21 22:34:43 -0500748 ''' Emits responses in the OpenBMC json api format. '''
Brad Bishop87b63c12016-03-18 14:47:51 -0400749 name = 'json_api_response'
750 api = 2
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500751
Brad Bishopd4c1c552017-02-21 00:07:28 -0500752 @staticmethod
753 def has_body():
754 return request.method not in ['OPTIONS']
755
Brad Bishop080a48e2017-02-21 22:34:43 -0500756 def __init__(self, app):
757 app.install_error_callback(self.error_callback)
758
Brad Bishop87b63c12016-03-18 14:47:51 -0400759 def apply(self, callback, route):
760 def wrap(*a, **kw):
Brad Bishopd4c1c552017-02-21 00:07:28 -0500761 data = callback(*a, **kw)
762 if self.has_body():
763 resp = {'data': data}
764 resp['status'] = 'ok'
765 resp['message'] = response.status_line
766 return resp
Brad Bishop87b63c12016-03-18 14:47:51 -0400767 return wrap
768
Brad Bishop080a48e2017-02-21 22:34:43 -0500769 def error_callback(self, error, response_object, **kw):
Brad Bishop87b63c12016-03-18 14:47:51 -0400770 response_object['message'] = error.status_line
Brad Bishop9c2531e2017-03-07 10:22:40 -0500771 response_object['status'] = 'error'
Brad Bishop080a48e2017-02-21 22:34:43 -0500772 response_object.setdefault('data', {})['description'] = str(error.body)
Brad Bishop87b63c12016-03-18 14:47:51 -0400773 if error.status_code == 500:
774 response_object['data']['exception'] = repr(error.exception)
775 response_object['data']['traceback'] = error.traceback.splitlines()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500776
Brad Bishop87b63c12016-03-18 14:47:51 -0400777
Brad Bishop080a48e2017-02-21 22:34:43 -0500778class JsonpPlugin(object):
Brad Bishop80fe37a2016-03-29 10:54:54 -0400779 ''' Json javascript wrapper. '''
780 name = 'jsonp'
781 api = 2
782
Brad Bishop080a48e2017-02-21 22:34:43 -0500783 def __init__(self, app, **kw):
784 app.install_error_callback(self.error_callback)
Brad Bishop80fe37a2016-03-29 10:54:54 -0400785
786 @staticmethod
787 def to_jsonp(json):
788 jwrapper = request.query.callback or None
789 if(jwrapper):
790 response.set_header('Content-Type', 'application/javascript')
791 json = jwrapper + '(' + json + ');'
792 return json
793
794 def apply(self, callback, route):
795 def wrap(*a, **kw):
796 return self.to_jsonp(callback(*a, **kw))
797 return wrap
798
Brad Bishop080a48e2017-02-21 22:34:43 -0500799 def error_callback(self, response_body, **kw):
800 response_body['body'] = self.to_jsonp(response_body['body'])
Brad Bishop80fe37a2016-03-29 10:54:54 -0400801
802
Deepak Kodihalli461367a2017-04-10 07:11:38 -0500803class ContentCheckerPlugin(object):
804 ''' Ensures that a route is associated with the expected content-type
805 header. '''
806 name = 'content_checker'
807 api = 2
808
809 class Checker:
810 def __init__(self, type, callback):
811 self.expected_type = type
812 self.callback = callback
813 self.error_str = "Expecting content type '%s', got '%s'"
814
815 def __call__(self, *a, **kw):
816 if self.expected_type and \
817 self.expected_type != request.content_type:
818 abort(415, self.error_str % (self.expected_type,
819 request.content_type))
820
821 return self.callback(*a, **kw)
822
823 def apply(self, callback, route):
824 content_type = getattr(
825 route.get_undecorated_callback(), '_content_type', None)
826
827 return self.Checker(content_type, callback)
828
829
Brad Bishop2c6fc762016-08-29 15:53:25 -0400830class App(Bottle):
Brad Bishop2ddfa002016-08-29 15:11:55 -0400831 def __init__(self):
Brad Bishop2c6fc762016-08-29 15:53:25 -0400832 super(App, self).__init__(autojson=False)
Brad Bishop2ddfa002016-08-29 15:11:55 -0400833 self.bus = dbus.SystemBus()
834 self.mapper = obmc.mapper.Mapper(self.bus)
Brad Bishop080a48e2017-02-21 22:34:43 -0500835 self.error_callbacks = []
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500836
Brad Bishop87b63c12016-03-18 14:47:51 -0400837 self.install_hooks()
838 self.install_plugins()
839 self.create_handlers()
840 self.install_handlers()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500841
Brad Bishop87b63c12016-03-18 14:47:51 -0400842 def install_plugins(self):
843 # install json api plugins
844 json_kw = {'indent': 2, 'sort_keys': True}
Brad Bishop87b63c12016-03-18 14:47:51 -0400845 self.install(AuthorizationPlugin())
Brad Bishopd0c404a2017-02-21 09:23:25 -0500846 self.install(CorsPlugin(self))
Deepak Kodihalli461367a2017-04-10 07:11:38 -0500847 self.install(ContentCheckerPlugin())
Brad Bishop080a48e2017-02-21 22:34:43 -0500848 self.install(JsonpPlugin(self, **json_kw))
849 self.install(JsonErrorsPlugin(self, **json_kw))
850 self.install(JsonApiResponsePlugin(self))
Brad Bishop87b63c12016-03-18 14:47:51 -0400851 self.install(JsonApiRequestPlugin())
852 self.install(JsonApiRequestTypePlugin())
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500853
Brad Bishop87b63c12016-03-18 14:47:51 -0400854 def install_hooks(self):
Brad Bishop080a48e2017-02-21 22:34:43 -0500855 self.error_handler_type = type(self.default_error_handler)
856 self.original_error_handler = self.default_error_handler
857 self.default_error_handler = self.error_handler_type(
858 self.custom_error_handler, self, Bottle)
859
Brad Bishop87b63c12016-03-18 14:47:51 -0400860 self.real_router_match = self.router.match
861 self.router.match = self.custom_router_match
862 self.add_hook('before_request', self.strip_extra_slashes)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500863
Brad Bishop87b63c12016-03-18 14:47:51 -0400864 def create_handlers(self):
865 # create route handlers
866 self.session_handler = SessionHandler(self, self.bus)
867 self.directory_handler = DirectoryHandler(self, self.bus)
868 self.list_names_handler = ListNamesHandler(self, self.bus)
869 self.list_handler = ListHandler(self, self.bus)
870 self.method_handler = MethodHandler(self, self.bus)
871 self.property_handler = PropertyHandler(self, self.bus)
872 self.schema_handler = SchemaHandler(self, self.bus)
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500873 self.image_upload_handler = ImageUploadHandler(self, self.bus)
Brad Bishop87b63c12016-03-18 14:47:51 -0400874 self.instance_handler = InstanceHandler(self, self.bus)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500875
Brad Bishop87b63c12016-03-18 14:47:51 -0400876 def install_handlers(self):
877 self.session_handler.install()
878 self.directory_handler.install()
879 self.list_names_handler.install()
880 self.list_handler.install()
881 self.method_handler.install()
882 self.property_handler.install()
883 self.schema_handler.install()
Deepak Kodihalli1af301a2017-04-11 07:29:01 -0500884 self.image_upload_handler.install()
Brad Bishop87b63c12016-03-18 14:47:51 -0400885 # this has to come last, since it matches everything
886 self.instance_handler.install()
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500887
Brad Bishop080a48e2017-02-21 22:34:43 -0500888 def install_error_callback(self, callback):
889 self.error_callbacks.insert(0, callback)
890
Brad Bishop87b63c12016-03-18 14:47:51 -0400891 def custom_router_match(self, environ):
892 ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is
893 needed doesn't work for us since the instance rules match
894 everything. This monkey-patch lets the route handler figure
895 out which response is needed. This could be accomplished
896 with a hook but that would require calling the router match
897 function twice.
898 '''
899 route, args = self.real_router_match(environ)
900 if isinstance(route.callback, RouteHandler):
901 route.callback._setup(**args)
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500902
Brad Bishop87b63c12016-03-18 14:47:51 -0400903 return route, args
Brad Bishopb1cbdaf2015-11-13 21:28:16 -0500904
Brad Bishop080a48e2017-02-21 22:34:43 -0500905 def custom_error_handler(self, res, error):
906 ''' Allow plugins to modify error reponses too via this custom
907 error handler. '''
908
909 response_object = {}
910 response_body = {}
911 for x in self.error_callbacks:
912 x(error=error,
913 response_object=response_object,
914 response_body=response_body)
915
916 return response_body.get('body', "")
917
Brad Bishop87b63c12016-03-18 14:47:51 -0400918 @staticmethod
919 def strip_extra_slashes():
920 path = request.environ['PATH_INFO']
921 trailing = ("", "/")[path[-1] == '/']
922 parts = filter(bool, path.split('/'))
923 request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing