voip.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from twisted.internet import defer
  16. from .base import ClientV1RestServlet, client_path_patterns
  17. import hmac
  18. import hashlib
  19. import base64
  20. class VoipRestServlet(ClientV1RestServlet):
  21. PATTERNS = client_path_patterns("/voip/turnServer$")
  22. @defer.inlineCallbacks
  23. def on_GET(self, request):
  24. requester = yield self.auth.get_user_by_req(
  25. request,
  26. self.hs.config.turn_allow_guests
  27. )
  28. turnUris = self.hs.config.turn_uris
  29. turnSecret = self.hs.config.turn_shared_secret
  30. turnUsername = self.hs.config.turn_username
  31. turnPassword = self.hs.config.turn_password
  32. userLifetime = self.hs.config.turn_user_lifetime
  33. if turnUris and turnSecret and userLifetime:
  34. expiry = (self.hs.get_clock().time_msec() + userLifetime) / 1000
  35. username = "%d:%s" % (expiry, requester.user.to_string())
  36. mac = hmac.new(turnSecret, msg=username, digestmod=hashlib.sha1)
  37. # We need to use standard padded base64 encoding here
  38. # encode_base64 because we need to add the standard padding to get the
  39. # same result as the TURN server.
  40. password = base64.b64encode(mac.digest())
  41. elif turnUris and turnUsername and turnPassword and userLifetime:
  42. username = turnUsername
  43. password = turnPassword
  44. else:
  45. defer.returnValue((200, {}))
  46. defer.returnValue((200, {
  47. 'username': username,
  48. 'password': password,
  49. 'ttl': userLifetime / 1000,
  50. 'uris': turnUris,
  51. }))
  52. def on_OPTIONS(self, request):
  53. return (200, {})
  54. def register_servlets(hs, http_server):
  55. VoipRestServlet(hs).register(http_server)