hostmeta.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/python3
  2. import logging
  3. import rd
  4. from urllib.parse import urlparse
  5. __version__ = '0.1'
  6. conn_timeout = 5
  7. tls_verify = True
  8. def get_host_meta(url, default_scheme=None):
  9. import requests
  10. args = {}
  11. if default_scheme:
  12. args['default_scheme'] = default_scheme
  13. (scheme, hostname, path) = rd.parse_uri_components(url, **args)
  14. """ Get host-meta data from .well-known """
  15. url = '{!s}://{!s}/.well-known/host-meta'.format(scheme, hostname)
  16. headers = {
  17. 'Accept': ', '.join(rd.JRD_TYPES + rd.XRD_TYPES),
  18. 'User-Agent': 'pywebdisco/{!s}'.format(__version__),
  19. }
  20. logging.debug('fetching RD from {!s}'.format(url))
  21. rsp = requests.get(url, headers=headers, timeout=conn_timeout, verify=tls_verify)
  22. if rsp.url != url:
  23. logging.info('Host-meta request redirected to {!s}'.format(rsp.url))
  24. content_type = rsp.headers.get('Content-Type', '').split(';', 1)[0].strip()
  25. logging.debug('RD content type is {!s}'.format(content_type))
  26. return rd.loads(rsp.content.decode(rsp.encoding if rsp.encoding else 'utf-8'), content_type)
  27. if __name__ == '__main__':
  28. import argparse
  29. parser = argparse.ArgumentParser(description='Simple host-meta discovery')
  30. parser.add_argument('url', help='URL, possibly only hostname, of service we want discovery on')
  31. parser.add_argument('-d', '--debug', dest='debug', action='store_true', help='print debug logging output to console')
  32. parser.add_argument('-r', '--rel', metavar='REL', help='desired relation')
  33. parser.add_argument('-m', '--type', metavar='MIME', help='Content type, if rel can have multiple entries')
  34. parser.add_argument('-s', '--default-scheme', help='if no scheme is used in the url, use this')
  35. args = parser.parse_args()
  36. if args.debug:
  37. logging.basicConfig(level=logging.DEBUG)
  38. hm = get_host_meta(hostname, default_scheme=args.default_scheme)
  39. print('--- {!s}://{!s} ---'.format(scheme, hostname))
  40. if args.rel:
  41. link = wf.find_link(args.rel, mimetype=args.mimetype)
  42. if link is None:
  43. print('*** Link not found for rel={!s}'.format(args.rel))
  44. print('{!s}:\n\t{!s}'.format(args.rel, link))
  45. else:
  46. for rel in rd.KNOWN_RELS:
  47. link = getattr(hm, rel)
  48. if link:
  49. print('{}\t{}\t{}'.format(rel, link.href if link.href else link.template, link.type if link.type else '*'))