| 1 |
#!/usr/bin/env python3 |
| 2 |
# SPDX-FileCopyrightText: Christian Amsüss and the aiocoap contributors |
| 3 |
# |
| 4 |
# SPDX-License-Identifier: MIT |
| 5 |
|
| 6 |
"""A minimal server that can be placed where an RD might be auto-discovered, |
| 7 |
and announces the resources on a full resource directory. |
| 8 |
|
| 9 |
This is "minimal" because it only does two things: |
| 10 |
|
| 11 |
* Let clients query for Resource Directories from an explicitly configured |
| 12 |
list of links |
| 13 |
* Accept simple registrations and forward them as simple registrations to a |
| 14 |
configured RD. This expects that the actual RD accepts con= on a simple |
| 15 |
registration, which will probably be disallowed. |
| 16 |
|
| 17 |
It does not (but could be extended to) discover RDs or their resources on its |
| 18 |
own, or allow the list of servers to be updated remotely. |
| 19 |
|
| 20 |
While basically usable (eg. on 6LoWPAN border routers), it is more considered a |
| 21 |
demo; the devices on which such functionality is expected to run might easily |
| 22 |
prefer a more constrained implementation.""" |
| 23 |
|
| 24 |
import argparse |
| 25 |
import logging |
| 26 |
from urllib.parse import urljoin |
| 27 |
import asyncio |
| 28 |
|
| 29 |
from aiocoap import Message, GET, POST, CHANGED, CONTENT |
| 30 |
from aiocoap.error import NotFound, MethodNotAllowed, AnonymousHost, BadRequest |
| 31 |
from aiocoap.resource import WKCResource, Site |
| 32 |
from aiocoap.cli.common import (add_server_arguments, |
| 33 |
server_context_from_arguments) |
| 34 |
from aiocoap.util.cli import AsyncCLIDaemon |
| 35 |
from aiocoap.util.linkformat import LinkFormat, Link, parse |
| 36 |
|
| 37 |
class RelayingWKC(WKCResource): |
| 38 |
def __init__(self): |
| 39 |
self.links = LinkFormat() |
| 40 |
self.forward = None |
| 41 |
|
| 42 |
super().__init__(listgenerator=lambda: self.links) |
| 43 |
|
| 44 |
async def setup(self, rd_uri): |
| 45 |
# FIXME: deduplicate with .client.register (esp. when that recognizes more than just multicast) |
| 46 |
rd_uri = rd_uri or 'coap://[ff05::fd]' |
| 47 |
rd_wkc = urljoin(rd_uri, '/.well-known/core?rt=core.rd*') |
| 48 |
if not rd_wkc.startswith(rd_uri): |
| 49 |
print("Ignoring path of given RD argument") |
| 50 |
|
| 51 |
# This would request to self too if the RD is on the LAN, but |
| 52 |
# fortunately .wk/c filtering triggers and we don't get a response from |
| 53 |
# self b/c there's nothing to report yet. |
| 54 |
uri_response = await self.context.request( |
| 55 |
Message(code=GET, uri=rd_wkc) |
| 56 |
).response_raising |
| 57 |
|
| 58 |
if uri_response.code != CONTENT: |
| 59 |
raise RuntimeError("Unexpected response code %s" % uri_response.code) |
| 60 |
|
| 61 |
if uri_response.opt.content_format != 40: |
| 62 |
raise RuntimeError("Unexpected response content format %s" % uri_response.opt.content_format) |
| 63 |
links = parse(uri_response.payload.decode('utf8')) |
| 64 |
|
| 65 |
relayable = ("core.rd-lookup-ep", "core.rd-lookup-res", "core.rd-lookup-gp", "core.rd", "core.rd-group") |
| 66 |
for l in links.links: |
| 67 |
rt = (" ".join(l.rt)).split(" ") |
| 68 |
rt_relayable = [r for r in rt if r in relayable] |
| 69 |
if rt_relayable: |
| 70 |
target = l.get_target(uri_response.get_request_uri()) |
| 71 |
new = Link(target, rt=" ".join(rt_relayable), rel="x-see-also") |
| 72 |
print("Exporting link: %s" % new) |
| 73 |
self.links.links.append(new) |
| 74 |
if "core.rd" in rt: |
| 75 |
print("Using that link as target for simple registration") |
| 76 |
self.forward = target |
| 77 |
|
| 78 |
async def render_post(self, request): |
| 79 |
if self.forward is None: |
| 80 |
raise MethodNotAllowed |
| 81 |
|
| 82 |
try: |
| 83 |
client_uri = request.remote.uri |
| 84 |
except AnonymousHost: |
| 85 |
raise BadRequest("explicit base required") |
| 86 |
# FIXME: deduplicate with aiocoap.cli.rd.SimpleRegistrationWKC |
| 87 |
args = request.opt.uri_query |
| 88 |
if any (a.startswith('base=') for a in args): |
| 89 |
raise BadRequest("base is not allowed in simple registrations") |
| 90 |
# FIXME: Could do some formal checks on those, like whether the lifetime is numeric |
| 91 |
|
| 92 |
async def work(): |
| 93 |
get_wkc = Message(code=GET, uri=urljoin(client_uri, '/.well-known/core')) |
| 94 |
response = await self.context.request(get_wkc).response_raising |
| 95 |
|
| 96 |
if response.code != CONTENT: |
| 97 |
raise RuntimeError("Odd response code from %s" % client_uri) |
| 98 |
|
| 99 |
fwd = Message(code=POST, |
| 100 |
uri=self.forward, |
| 101 |
content_format=response.opt.content_format, |
| 102 |
payload=response.payload, |
| 103 |
) |
| 104 |
fwd.opt.uri_query = args + ('base=%s' % client_uri,) |
| 105 |
await self.context.request(fwd).response |
| 106 |
|
| 107 |
asyncio.ensure_future(work()) |
| 108 |
|
| 109 |
return Message(code=CHANGED) |
| 110 |
|
| 111 |
class RDRelayProgram(AsyncCLIDaemon): |
| 112 |
async def start(self): |
| 113 |
p = argparse.ArgumentParser() |
| 114 |
p.add_argument("-v", "--verbose", help="Be more verbose (repeat to debug)", action='count', dest="verbosity", default=0) |
| 115 |
p.add_argument("rd_uri", help="Preconfigured address of the resource directory", nargs='?') |
| 116 |
|
| 117 |
add_server_arguments(p) |
| 118 |
|
| 119 |
opts = p.parse_args() |
| 120 |
|
| 121 |
if opts.verbosity > 1: |
| 122 |
logging.basicConfig(level=logging.DEBUG) |
| 123 |
elif opts.verbosity == 1: |
| 124 |
logging.basicConfig(level=logging.INFO) |
| 125 |
else: |
| 126 |
logging.basicConfig(level=logging.WARNING) |
| 127 |
|
| 128 |
site = Site() |
| 129 |
wkc = RelayingWKC() |
| 130 |
site.add_resource(['.well-known', 'core'], wkc) |
| 131 |
|
| 132 |
self.context = await server_context_from_arguments(site, opts) |
| 133 |
wkc.context = self.context |
| 134 |
await wkc.setup(opts.rd_uri) |
| 135 |
print("Resource directory relay operational") |
| 136 |
|
| 137 |
async def shutdown(self): |
| 138 |
await self.context.shutdown() |
| 139 |
|
| 140 |
if __name__ == "__main__": |
| 141 |
RDRelayProgram.sync_main() |