Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 3 | import os |
| 4 | import sys |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 5 | import dbus |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 6 | import dbus.exceptions |
| 7 | import json |
| 8 | import logging |
| 9 | from xml.etree import ElementTree |
| 10 | from rocket import Rocket |
| 11 | from bottle import Bottle, abort, request, response, JSONPlugin, HTTPError |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 12 | import OpenBMCMapper |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 13 | from OpenBMCMapper import Mapper, PathTree, IntrospectionNodeParser, ListMatch |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 14 | import spwd |
| 15 | import grp |
| 16 | import crypt |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 17 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 18 | DBUS_UNKNOWN_INTERFACE = 'org.freedesktop.UnknownInterface' |
| 19 | DBUS_UNKNOWN_METHOD = 'org.freedesktop.DBus.Error.UnknownMethod' |
| 20 | DBUS_INVALID_ARGS = 'org.freedesktop.DBus.Error.InvalidArgs' |
Brad Bishop | d457892 | 2015-12-02 11:10:36 -0500 | [diff] [blame] | 21 | DBUS_TYPE_ERROR = 'org.freedesktop.DBus.Python.TypeError' |
Brad Bishop | aac521c | 2015-11-25 09:16:35 -0500 | [diff] [blame] | 22 | DELETE_IFACE = 'org.openbmc.Object.Delete' |
Brad Bishop | 9ee57c4 | 2015-11-03 14:59:29 -0500 | [diff] [blame] | 23 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 24 | _4034_msg = "The specified %s cannot be %s: '%s'" |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 25 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 26 | def valid_user(session, *a, **kw): |
| 27 | ''' Authorization plugin callback that checks that the user is logged in. ''' |
| 28 | if session is None: |
| 29 | abort(403, 'Login required') |
| 30 | |
| 31 | class UserInGroup: |
| 32 | ''' Authorization plugin callback that checks that the user is logged in |
| 33 | and a member of a group. ''' |
| 34 | def __init__(self, group): |
| 35 | self.group = group |
| 36 | |
| 37 | def __call__(self, session, *a, **kw): |
| 38 | valid_user(session, *a, **kw) |
| 39 | res = False |
| 40 | |
| 41 | try: |
| 42 | res = session['user'] in grp.getgrnam(self.group)[3] |
| 43 | except KeyError: |
| 44 | pass |
| 45 | |
| 46 | if not res: |
| 47 | abort(403, 'Insufficient access') |
| 48 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 49 | def find_case_insensitive(value, lst): |
| 50 | return next((x for x in lst if x.lower() == value.lower()), None) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 51 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 52 | def makelist(data): |
| 53 | if isinstance(data, list): |
| 54 | return data |
| 55 | elif data: |
| 56 | return [data] |
| 57 | else: |
| 58 | return [] |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 59 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 60 | class RouteHandler(object): |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 61 | _require_auth = makelist(valid_user) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 62 | def __init__(self, app, bus, verbs, rules): |
| 63 | self.app = app |
| 64 | self.bus = bus |
| 65 | self.mapper = Mapper(bus) |
| 66 | self._verbs = makelist(verbs) |
| 67 | self._rules = rules |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 68 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 69 | def _setup(self, **kw): |
| 70 | request.route_data = {} |
| 71 | if request.method in self._verbs: |
| 72 | return self.setup(**kw) |
| 73 | else: |
| 74 | self.find(**kw) |
| 75 | raise HTTPError(405, "Method not allowed.", |
| 76 | Allow=','.join(self._verbs)) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 77 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 78 | def __call__(self, **kw): |
| 79 | return getattr(self, 'do_' + request.method.lower())(**kw) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 80 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 81 | def install(self): |
| 82 | self.app.route(self._rules, callback = self, |
| 83 | method = ['GET', 'PUT', 'PATCH', 'POST', 'DELETE']) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 84 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 85 | @staticmethod |
| 86 | def try_mapper_call(f, callback = None, **kw): |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 87 | try: |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 88 | return f(**kw) |
| 89 | except dbus.exceptions.DBusException, e: |
| 90 | if e.get_dbus_name() != OpenBMCMapper.MAPPER_NOT_FOUND: |
| 91 | raise |
| 92 | if callback is None: |
| 93 | def callback(e, **kw): |
| 94 | abort(404, str(e)) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 95 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 96 | callback(e, **kw) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 97 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 98 | @staticmethod |
| 99 | def try_properties_interface(f, *a): |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 100 | try: |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 101 | return f(*a) |
| 102 | except dbus.exceptions.DBusException, e: |
| 103 | if DBUS_UNKNOWN_INTERFACE in e.get_dbus_message(): |
| 104 | # interface doesn't have any properties |
| 105 | return None |
| 106 | if DBUS_UNKNOWN_METHOD == e.get_dbus_name(): |
| 107 | # properties interface not implemented at all |
| 108 | return None |
| 109 | raise |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 110 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 111 | class DirectoryHandler(RouteHandler): |
| 112 | verbs = 'GET' |
| 113 | rules = '<path:path>/' |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 114 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 115 | def __init__(self, app, bus): |
| 116 | super(DirectoryHandler, self).__init__( |
| 117 | app, bus, self.verbs, self.rules) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 118 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 119 | def find(self, path = '/'): |
| 120 | return self.try_mapper_call( |
| 121 | self.mapper.get_subtree_paths, |
| 122 | path = path, depth = 1) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 123 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 124 | def setup(self, path = '/'): |
| 125 | request.route_data['map'] = self.find(path) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 126 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 127 | def do_get(self, path = '/'): |
| 128 | return request.route_data['map'] |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 129 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 130 | class ListNamesHandler(RouteHandler): |
| 131 | verbs = 'GET' |
| 132 | rules = ['/list', '<path:path>/list'] |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 133 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 134 | def __init__(self, app, bus): |
| 135 | super(ListNamesHandler, self).__init__( |
| 136 | app, bus, self.verbs, self.rules) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 137 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 138 | def find(self, path = '/'): |
| 139 | return self.try_mapper_call( |
| 140 | self.mapper.get_subtree, path = path).keys() |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 141 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 142 | def setup(self, path = '/'): |
| 143 | request.route_data['map'] = self.find(path) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 144 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 145 | def do_get(self, path = '/'): |
| 146 | return request.route_data['map'] |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 147 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 148 | class ListHandler(RouteHandler): |
| 149 | verbs = 'GET' |
| 150 | rules = ['/enumerate', '<path:path>/enumerate'] |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 151 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 152 | def __init__(self, app, bus): |
| 153 | super(ListHandler, self).__init__( |
| 154 | app, bus, self.verbs, self.rules) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 155 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 156 | def find(self, path = '/'): |
| 157 | return self.try_mapper_call( |
| 158 | self.mapper.get_subtree, path = path) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 159 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 160 | def setup(self, path = '/'): |
| 161 | request.route_data['map'] = self.find(path) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 162 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 163 | def do_get(self, path = '/'): |
Brad Bishop | 936f5fe | 2015-11-03 15:10:11 -0500 | [diff] [blame] | 164 | objs = {} |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 165 | mapper_data = request.route_data['map'] |
Brad Bishop | 936f5fe | 2015-11-03 15:10:11 -0500 | [diff] [blame] | 166 | tree = PathTree() |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 167 | for x,y in mapper_data.iteritems(): |
Brad Bishop | 936f5fe | 2015-11-03 15:10:11 -0500 | [diff] [blame] | 168 | tree[x] = y |
| 169 | |
| 170 | try: |
| 171 | # Check to see if the root path implements |
| 172 | # enumerate in addition to any sub tree |
| 173 | # objects. |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 174 | root = self.try_mapper_call(self.mapper.get_object, |
| 175 | path = path) |
| 176 | mapper_data[path] = root |
Brad Bishop | 936f5fe | 2015-11-03 15:10:11 -0500 | [diff] [blame] | 177 | except: |
| 178 | pass |
| 179 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 180 | have_enumerate = [ (x[0], self.enumerate_capable(*x)) \ |
| 181 | for x in mapper_data.iteritems() \ |
| 182 | if self.enumerate_capable(*x) ] |
Brad Bishop | 936f5fe | 2015-11-03 15:10:11 -0500 | [diff] [blame] | 183 | |
| 184 | for x,y in have_enumerate: |
| 185 | objs.update(self.call_enumerate(x, y)) |
| 186 | tmp = tree[x] |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 187 | # remove the subtree |
Brad Bishop | 936f5fe | 2015-11-03 15:10:11 -0500 | [diff] [blame] | 188 | del tree[x] |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 189 | # add the new leaf back since enumerate results don't |
| 190 | # include the object enumerate is being invoked on |
Brad Bishop | 936f5fe | 2015-11-03 15:10:11 -0500 | [diff] [blame] | 191 | tree[x] = tmp |
| 192 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 193 | # make dbus calls for any remaining objects |
Brad Bishop | 936f5fe | 2015-11-03 15:10:11 -0500 | [diff] [blame] | 194 | for x,y in tree.dataitems(): |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 195 | objs[x] = self.app.instance_handler.do_get(x) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 196 | |
| 197 | return objs |
| 198 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 199 | @staticmethod |
| 200 | def enumerate_capable(path, bus_data): |
| 201 | busses = [] |
| 202 | for name, ifaces in bus_data.iteritems(): |
| 203 | if OpenBMCMapper.ENUMERATE_IFACE in ifaces: |
| 204 | busses.append(name) |
| 205 | return busses |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 206 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 207 | def call_enumerate(self, path, busses): |
| 208 | objs = {} |
| 209 | for b in busses: |
| 210 | obj = self.bus.get_object(b, path, introspect = False) |
| 211 | iface = dbus.Interface(obj, OpenBMCMapper.ENUMERATE_IFACE) |
| 212 | objs.update(iface.enumerate()) |
| 213 | return objs |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 214 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 215 | class MethodHandler(RouteHandler): |
| 216 | verbs = 'POST' |
| 217 | rules = '<path:path>/action/<method>' |
| 218 | request_type = list |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 219 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 220 | def __init__(self, app, bus): |
| 221 | super(MethodHandler, self).__init__( |
| 222 | app, bus, self.verbs, self.rules) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 223 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 224 | def find(self, path, method): |
| 225 | busses = self.try_mapper_call(self.mapper.get_object, |
| 226 | path = path) |
| 227 | for items in busses.iteritems(): |
| 228 | m = self.find_method_on_bus(path, method, *items) |
| 229 | if m: |
| 230 | return m |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 231 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 232 | abort(404, _4034_msg %('method', 'found', method)) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 233 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 234 | def setup(self, path, method): |
| 235 | request.route_data['method'] = self.find(path, method) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 236 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 237 | def do_post(self, path, method): |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 238 | try: |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 239 | if request.parameter_list: |
| 240 | return request.route_data['method'](*request.parameter_list) |
| 241 | else: |
| 242 | return request.route_data['method']() |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 243 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 244 | except dbus.exceptions.DBusException, e: |
| 245 | if e.get_dbus_name() == DBUS_INVALID_ARGS: |
| 246 | abort(400, str(e)) |
Brad Bishop | d457892 | 2015-12-02 11:10:36 -0500 | [diff] [blame] | 247 | if e.get_dbus_name() == DBUS_TYPE_ERROR: |
| 248 | abort(400, str(e)) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 249 | raise |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 250 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 251 | @staticmethod |
| 252 | def find_method_in_interface(method, obj, interface, methods): |
| 253 | if methods is None: |
| 254 | return None |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 255 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 256 | method = find_case_insensitive(method, methods.keys()) |
| 257 | if method is not None: |
| 258 | iface = dbus.Interface(obj, interface) |
| 259 | return iface.get_dbus_method(method) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 260 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 261 | def find_method_on_bus(self, path, method, bus, interfaces): |
| 262 | obj = self.bus.get_object(bus, path, introspect = False) |
| 263 | iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE) |
| 264 | data = iface.Introspect() |
| 265 | parser = IntrospectionNodeParser( |
| 266 | ElementTree.fromstring(data), |
| 267 | intf_match = ListMatch(interfaces)) |
| 268 | for x,y in parser.get_interfaces().iteritems(): |
| 269 | m = self.find_method_in_interface(method, obj, x, |
| 270 | y.get('method')) |
| 271 | if m: |
| 272 | return m |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 273 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 274 | class PropertyHandler(RouteHandler): |
| 275 | verbs = ['PUT', 'GET'] |
| 276 | rules = '<path:path>/attr/<prop>' |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 277 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 278 | def __init__(self, app, bus): |
| 279 | super(PropertyHandler, self).__init__( |
| 280 | app, bus, self.verbs, self.rules) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 281 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 282 | def find(self, path, prop): |
| 283 | self.app.instance_handler.setup(path) |
| 284 | obj = self.app.instance_handler.do_get(path) |
| 285 | try: |
| 286 | obj[prop] |
| 287 | except KeyError, e: |
| 288 | if request.method == 'PUT': |
| 289 | abort(403, _4034_msg %('property', 'created', str(e))) |
| 290 | else: |
| 291 | abort(404, _4034_msg %('property', 'found', str(e))) |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 292 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 293 | return { path: obj } |
| 294 | |
| 295 | def setup(self, path, prop): |
| 296 | request.route_data['obj'] = self.find(path, prop) |
| 297 | |
| 298 | def do_get(self, path, prop): |
| 299 | return request.route_data['obj'][path][prop] |
| 300 | |
| 301 | def do_put(self, path, prop, value = None): |
| 302 | if value is None: |
| 303 | value = request.parameter_list |
| 304 | |
| 305 | prop, iface, properties_iface = self.get_host_interface( |
| 306 | path, prop, request.route_data['map'][path]) |
| 307 | try: |
| 308 | properties_iface.Set(iface, prop, value) |
| 309 | except ValueError, e: |
| 310 | abort(400, str(e)) |
| 311 | except dbus.exceptions.DBusException, e: |
| 312 | if e.get_dbus_name() == DBUS_INVALID_ARGS: |
| 313 | abort(403, str(e)) |
| 314 | raise |
| 315 | |
| 316 | def get_host_interface(self, path, prop, bus_info): |
| 317 | for bus, interfaces in bus_info.iteritems(): |
| 318 | obj = self.bus.get_object(bus, path, introspect = True) |
| 319 | properties_iface = dbus.Interface( |
| 320 | obj, dbus_interface=dbus.PROPERTIES_IFACE) |
| 321 | |
| 322 | info = self.get_host_interface_on_bus( |
| 323 | path, prop, properties_iface, |
| 324 | bus, interfaces) |
| 325 | if info is not None: |
| 326 | prop, iface = info |
| 327 | return prop, iface, properties_iface |
| 328 | |
| 329 | def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces): |
| 330 | for i in interfaces: |
| 331 | properties = self.try_properties_interface(iface.GetAll, i) |
| 332 | if properties is None: |
| 333 | continue |
| 334 | prop = find_case_insensitive(prop, properties.keys()) |
| 335 | if prop is None: |
| 336 | continue |
| 337 | return prop, i |
| 338 | |
| 339 | class InstanceHandler(RouteHandler): |
| 340 | verbs = ['GET', 'PUT', 'DELETE'] |
| 341 | rules = '<path:path>' |
| 342 | request_type = dict |
| 343 | |
| 344 | def __init__(self, app, bus): |
| 345 | super(InstanceHandler, self).__init__( |
| 346 | app, bus, self.verbs, self.rules) |
| 347 | |
| 348 | def find(self, path, callback = None): |
| 349 | return { path: self.try_mapper_call( |
| 350 | self.mapper.get_object, |
| 351 | callback, |
| 352 | path = path) } |
| 353 | |
| 354 | def setup(self, path): |
| 355 | callback = None |
| 356 | if request.method == 'PUT': |
| 357 | def callback(e, **kw): |
| 358 | abort(403, _4034_msg %('resource', |
| 359 | 'created', path)) |
| 360 | |
| 361 | if request.route_data.get('map') is None: |
| 362 | request.route_data['map'] = self.find(path, callback) |
| 363 | |
| 364 | def do_get(self, path): |
| 365 | properties = {} |
| 366 | for item in request.route_data['map'][path].iteritems(): |
| 367 | properties.update(self.get_properties_on_bus( |
| 368 | path, *item)) |
| 369 | |
| 370 | return properties |
| 371 | |
| 372 | @staticmethod |
| 373 | def get_properties_on_iface(properties_iface, iface): |
| 374 | properties = InstanceHandler.try_properties_interface( |
| 375 | properties_iface.GetAll, iface) |
| 376 | if properties is None: |
| 377 | return {} |
| 378 | return properties |
| 379 | |
| 380 | def get_properties_on_bus(self, path, bus, interfaces): |
| 381 | properties = {} |
| 382 | obj = self.bus.get_object(bus, path, introspect = False) |
| 383 | properties_iface = dbus.Interface( |
| 384 | obj, dbus_interface=dbus.PROPERTIES_IFACE) |
| 385 | for i in interfaces: |
| 386 | properties.update(self.get_properties_on_iface( |
| 387 | properties_iface, i)) |
| 388 | |
| 389 | return properties |
| 390 | |
| 391 | def do_put(self, path): |
| 392 | # make sure all properties exist in the request |
| 393 | obj = set(self.do_get(path).keys()) |
| 394 | req = set(request.parameter_list.keys()) |
| 395 | |
| 396 | diff = list(obj.difference(req)) |
| 397 | if diff: |
| 398 | abort(403, _4034_msg %('resource', 'removed', |
| 399 | '%s/attr/%s' %(path, diff[0]))) |
| 400 | |
| 401 | diff = list(req.difference(obj)) |
| 402 | if diff: |
| 403 | abort(403, _4034_msg %('resource', 'created', |
| 404 | '%s/attr/%s' %(path, diff[0]))) |
| 405 | |
| 406 | for p,v in request.parameter_list.iteritems(): |
| 407 | self.app.property_handler.do_put( |
| 408 | path, p, v) |
| 409 | |
| 410 | def do_delete(self, path): |
| 411 | for bus_info in request.route_data['map'][path].iteritems(): |
| 412 | if self.bus_missing_delete(path, *bus_info): |
| 413 | abort(403, _4034_msg %('resource', 'removed', |
| 414 | path)) |
| 415 | |
| 416 | for bus in request.route_data['map'][path].iterkeys(): |
| 417 | self.delete_on_bus(path, bus) |
| 418 | |
| 419 | def bus_missing_delete(self, path, bus, interfaces): |
| 420 | return DELETE_IFACE not in interfaces |
| 421 | |
| 422 | def delete_on_bus(self, path, bus): |
| 423 | obj = self.bus.get_object(bus, path, introspect = False) |
| 424 | delete_iface = dbus.Interface( |
| 425 | obj, dbus_interface = DELETE_IFACE) |
| 426 | delete_iface.Delete() |
| 427 | |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 428 | class SessionHandler(MethodHandler): |
| 429 | ''' Handles the /login and /logout routes, manages server side session store and |
| 430 | session cookies. ''' |
| 431 | |
| 432 | rules = ['/login', '/logout'] |
| 433 | login_str = "User '%s' logged %s" |
| 434 | bad_passwd_str = "Invalid username or password" |
| 435 | no_user_str = "No user logged in" |
| 436 | bad_json_str = "Expecting request format { 'data': [<username>, <password>] }, got '%s'" |
| 437 | _require_auth = None |
| 438 | MAX_SESSIONS = 16 |
| 439 | |
| 440 | def __init__(self, app, bus): |
| 441 | super(SessionHandler, self).__init__( |
| 442 | app, bus) |
| 443 | self.hmac_key = os.urandom(128) |
| 444 | self.session_store = [] |
| 445 | |
| 446 | @staticmethod |
| 447 | def authenticate(username, clear): |
| 448 | try: |
| 449 | encoded = spwd.getspnam(username)[1] |
| 450 | return encoded == crypt.crypt(clear, encoded) |
| 451 | except KeyError: |
| 452 | return False |
| 453 | |
| 454 | def invalidate_session(self, session): |
| 455 | try: |
| 456 | self.session_store.remove(session) |
| 457 | except ValueError: |
| 458 | pass |
| 459 | |
| 460 | def new_session(self): |
| 461 | sid = os.urandom(32) |
| 462 | if self.MAX_SESSIONS <= len(self.session_store): |
| 463 | self.session_store.pop() |
| 464 | self.session_store.insert(0, {'sid': sid}) |
| 465 | |
| 466 | return self.session_store[0] |
| 467 | |
| 468 | def get_session(self, sid): |
| 469 | sids = [ x['sid'] for x in self.session_store ] |
| 470 | try: |
| 471 | return self.session_store[sids.index(sid)] |
| 472 | except ValueError: |
| 473 | return None |
| 474 | |
| 475 | def get_session_from_cookie(self): |
| 476 | return self.get_session( |
| 477 | request.get_cookie('sid', |
| 478 | secret = self.hmac_key)) |
| 479 | |
| 480 | def do_post(self, **kw): |
| 481 | if request.path == '/login': |
| 482 | return self.do_login(**kw) |
| 483 | else: |
| 484 | return self.do_logout(**kw) |
| 485 | |
| 486 | def do_logout(self, **kw): |
| 487 | session = self.get_session_from_cookie() |
| 488 | if session is not None: |
| 489 | user = session['user'] |
| 490 | self.invalidate_session(session) |
| 491 | response.delete_cookie('sid') |
| 492 | return self.login_str %(user, 'out') |
| 493 | |
| 494 | return self.no_user_str |
| 495 | |
| 496 | def do_login(self, **kw): |
| 497 | session = self.get_session_from_cookie() |
| 498 | if session is not None: |
| 499 | return self.login_str %(session['user'], 'in') |
| 500 | |
| 501 | if len(request.parameter_list) != 2: |
| 502 | abort(400, self.bad_json_str %(request.json)) |
| 503 | |
| 504 | if not self.authenticate(*request.parameter_list): |
| 505 | return self.bad_passwd_str |
| 506 | |
| 507 | user = request.parameter_list[0] |
| 508 | session = self.new_session() |
| 509 | session['user'] = user |
| 510 | response.set_cookie('sid', session['sid'], secret = self.hmac_key, |
| 511 | secure = True, |
| 512 | httponly = True) |
| 513 | return self.login_str %(user, 'in') |
| 514 | |
| 515 | def find(self, **kw): |
| 516 | pass |
| 517 | |
| 518 | def setup(self, **kw): |
| 519 | pass |
| 520 | |
| 521 | class AuthorizationPlugin(object): |
| 522 | ''' Invokes an optional list of authorization callbacks. ''' |
| 523 | |
| 524 | name = 'authorization' |
| 525 | api = 2 |
| 526 | |
| 527 | class Compose: |
| 528 | def __init__(self, validators, callback, session_mgr): |
| 529 | self.validators = validators |
| 530 | self.callback = callback |
| 531 | self.session_mgr = session_mgr |
| 532 | |
| 533 | def __call__(self, *a, **kw): |
| 534 | sid = request.get_cookie('sid', secret = self.session_mgr.hmac_key) |
| 535 | session = self.session_mgr.get_session(sid) |
| 536 | for x in self.validators: |
| 537 | x(session, *a, **kw) |
| 538 | |
| 539 | return self.callback(*a, **kw) |
| 540 | |
| 541 | def apply(self, callback, route): |
| 542 | undecorated = route.get_undecorated_callback() |
| 543 | if not isinstance(undecorated, RouteHandler): |
| 544 | return callback |
| 545 | |
| 546 | auth_types = getattr(undecorated, |
| 547 | '_require_auth', None) |
| 548 | if not auth_types: |
| 549 | return callback |
| 550 | |
| 551 | return self.Compose(auth_types, callback, |
| 552 | undecorated.app.session_handler) |
| 553 | |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 554 | class JsonApiRequestPlugin(object): |
| 555 | ''' Ensures request content satisfies the OpenBMC json api format. ''' |
| 556 | name = 'json_api_request' |
| 557 | api = 2 |
| 558 | |
| 559 | error_str = "Expecting request format { 'data': <value> }, got '%s'" |
| 560 | type_error_str = "Unsupported Content-Type: '%s'" |
| 561 | json_type = "application/json" |
| 562 | request_methods = ['PUT', 'POST', 'PATCH'] |
| 563 | |
| 564 | @staticmethod |
| 565 | def content_expected(): |
| 566 | return request.method in JsonApiRequestPlugin.request_methods |
| 567 | |
| 568 | def validate_request(self): |
| 569 | if request.content_length > 0 and \ |
| 570 | request.content_type != self.json_type: |
| 571 | abort(415, self.type_error_str %(request.content_type)) |
| 572 | |
| 573 | try: |
| 574 | request.parameter_list = request.json.get('data') |
| 575 | except ValueError, e: |
| 576 | abort(400, str(e)) |
| 577 | except (AttributeError, KeyError, TypeError): |
| 578 | abort(400, self.error_str %(request.json)) |
| 579 | |
| 580 | def apply(self, callback, route): |
| 581 | verbs = getattr(route.get_undecorated_callback(), |
| 582 | '_verbs', None) |
| 583 | if verbs is None: |
| 584 | return callback |
| 585 | |
| 586 | if not set(self.request_methods).intersection(verbs): |
| 587 | return callback |
| 588 | |
| 589 | def wrap(*a, **kw): |
| 590 | if self.content_expected(): |
| 591 | self.validate_request() |
| 592 | return callback(*a, **kw) |
| 593 | |
| 594 | return wrap |
| 595 | |
| 596 | class JsonApiRequestTypePlugin(object): |
| 597 | ''' Ensures request content type satisfies the OpenBMC json api format. ''' |
| 598 | name = 'json_api_method_request' |
| 599 | api = 2 |
| 600 | |
| 601 | error_str = "Expecting request format { 'data': %s }, got '%s'" |
| 602 | |
| 603 | def apply(self, callback, route): |
| 604 | request_type = getattr(route.get_undecorated_callback(), |
| 605 | 'request_type', None) |
| 606 | if request_type is None: |
| 607 | return callback |
| 608 | |
| 609 | def validate_request(): |
| 610 | if not isinstance(request.parameter_list, request_type): |
| 611 | abort(400, self.error_str %(str(request_type), request.json)) |
| 612 | |
| 613 | def wrap(*a, **kw): |
| 614 | if JsonApiRequestPlugin.content_expected(): |
| 615 | validate_request() |
| 616 | return callback(*a, **kw) |
| 617 | |
| 618 | return wrap |
| 619 | |
| 620 | class JsonApiResponsePlugin(object): |
| 621 | ''' Emits normal responses in the OpenBMC json api format. ''' |
| 622 | name = 'json_api_response' |
| 623 | api = 2 |
| 624 | |
| 625 | def apply(self, callback, route): |
| 626 | def wrap(*a, **kw): |
| 627 | resp = { 'data': callback(*a, **kw) } |
| 628 | resp['status'] = 'ok' |
| 629 | resp['message'] = response.status_line |
| 630 | return resp |
| 631 | return wrap |
| 632 | |
| 633 | class JsonApiErrorsPlugin(object): |
| 634 | ''' Emits error responses in the OpenBMC json api format. ''' |
| 635 | name = 'json_api_errors' |
| 636 | api = 2 |
| 637 | |
| 638 | def __init__(self, **kw): |
| 639 | self.app = None |
| 640 | self.function_type = None |
| 641 | self.original = None |
| 642 | self.json_opts = { x:y for x,y in kw.iteritems() \ |
| 643 | if x in ['indent','sort_keys'] } |
| 644 | |
| 645 | def setup(self, app): |
| 646 | self.app = app |
| 647 | self.function_type = type(app.default_error_handler) |
| 648 | self.original = app.default_error_handler |
| 649 | self.app.default_error_handler = self.function_type( |
| 650 | self.json_errors, app, Bottle) |
| 651 | |
| 652 | def apply(self, callback, route): |
| 653 | return callback |
| 654 | |
| 655 | def close(self): |
| 656 | self.app.default_error_handler = self.function_type( |
| 657 | self.original, self.app, Bottle) |
| 658 | |
| 659 | def json_errors(self, res, error): |
| 660 | response_object = {'status': 'error', 'data': {} } |
| 661 | response_object['message'] = error.status_line |
| 662 | response_object['data']['description'] = str(error.body) |
| 663 | if error.status_code == 500: |
| 664 | response_object['data']['exception'] = repr(error.exception) |
| 665 | response_object['data']['traceback'] = error.traceback.splitlines() |
| 666 | |
| 667 | json_response = json.dumps(response_object, **self.json_opts) |
Brad Bishop | 9bfeec2 | 2015-11-17 09:14:50 -0500 | [diff] [blame] | 668 | response.content_type = 'application/json' |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 669 | return json_response |
| 670 | |
| 671 | class RestApp(Bottle): |
| 672 | def __init__(self, bus): |
| 673 | super(RestApp, self).__init__(autojson = False) |
Brad Bishop | 53fd493 | 2015-10-30 09:22:30 -0400 | [diff] [blame] | 674 | self.bus = bus |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 675 | self.mapper = Mapper(bus) |
| 676 | |
| 677 | self.install_hooks() |
| 678 | self.install_plugins() |
| 679 | self.create_handlers() |
| 680 | self.install_handlers() |
| 681 | |
| 682 | def install_plugins(self): |
| 683 | # install json api plugins |
| 684 | json_kw = {'indent': 2, 'sort_keys': True} |
| 685 | self.install(JSONPlugin(**json_kw)) |
| 686 | self.install(JsonApiErrorsPlugin(**json_kw)) |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 687 | self.install(AuthorizationPlugin()) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 688 | self.install(JsonApiResponsePlugin()) |
| 689 | self.install(JsonApiRequestPlugin()) |
| 690 | self.install(JsonApiRequestTypePlugin()) |
| 691 | |
| 692 | def install_hooks(self): |
| 693 | self.real_router_match = self.router.match |
| 694 | self.router.match = self.custom_router_match |
| 695 | self.add_hook('before_request', self.strip_extra_slashes) |
| 696 | |
| 697 | def create_handlers(self): |
| 698 | # create route handlers |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 699 | self.session_handler = SessionHandler(self, self.bus) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 700 | self.directory_handler = DirectoryHandler(self, self.bus) |
| 701 | self.list_names_handler = ListNamesHandler(self, self.bus) |
| 702 | self.list_handler = ListHandler(self, self.bus) |
| 703 | self.method_handler = MethodHandler(self, self.bus) |
| 704 | self.property_handler = PropertyHandler(self, self.bus) |
| 705 | self.instance_handler = InstanceHandler(self, self.bus) |
| 706 | |
| 707 | def install_handlers(self): |
Brad Bishop | 2f42858 | 2015-12-02 10:56:11 -0500 | [diff] [blame] | 708 | self.session_handler.install() |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 709 | self.directory_handler.install() |
| 710 | self.list_names_handler.install() |
| 711 | self.list_handler.install() |
| 712 | self.method_handler.install() |
| 713 | self.property_handler.install() |
| 714 | # this has to come last, since it matches everything |
| 715 | self.instance_handler.install() |
| 716 | |
| 717 | def custom_router_match(self, environ): |
| 718 | ''' The built-in Bottle algorithm for figuring out if a 404 or 405 is |
| 719 | needed doesn't work for us since the instance rules match everything. |
| 720 | This monkey-patch lets the route handler figure out which response is |
| 721 | needed. This could be accomplished with a hook but that would require |
| 722 | calling the router match function twice. |
| 723 | ''' |
| 724 | route, args = self.real_router_match(environ) |
| 725 | if isinstance(route.callback, RouteHandler): |
| 726 | route.callback._setup(**args) |
| 727 | |
| 728 | return route, args |
| 729 | |
| 730 | @staticmethod |
| 731 | def strip_extra_slashes(): |
| 732 | path = request.environ['PATH_INFO'] |
| 733 | trailing = ("","/")[path[-1] == '/'] |
| 734 | parts = filter(bool, path.split('/')) |
| 735 | request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 736 | |
| 737 | if __name__ == '__main__': |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 738 | log = logging.getLogger('Rocket.Errors') |
| 739 | log.setLevel(logging.INFO) |
| 740 | log.addHandler(logging.StreamHandler(sys.stdout)) |
| 741 | |
Brad Bishop | aa65f6e | 2015-10-27 16:28:51 -0400 | [diff] [blame] | 742 | bus = dbus.SystemBus() |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 743 | app = RestApp(bus) |
| 744 | default_cert = os.path.join(sys.prefix, 'share', |
| 745 | os.path.basename(__file__), 'cert.pem') |
| 746 | |
| 747 | server = Rocket(('0.0.0.0', |
| 748 | 443, |
| 749 | default_cert, |
| 750 | default_cert), |
Brad Bishop | b7f756c | 2015-12-02 11:13:20 -0500 | [diff] [blame] | 751 | 'wsgi', {'wsgi_app': app}, |
| 752 | min_threads = 1, |
| 753 | max_threads = 1) |
Brad Bishop | b1cbdaf | 2015-11-13 21:28:16 -0500 | [diff] [blame] | 754 | server.start() |