voip.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. import base64
  16. import hashlib
  17. import hmac
  18. from twisted.internet import defer
  19. from synapse.http.servlet import RestServlet
  20. from synapse.rest.client.v2_alpha._base import client_patterns
  21. class VoipRestServlet(RestServlet):
  22. PATTERNS = client_patterns("/voip/turnServer$", v1=True)
  23. def __init__(self, hs):
  24. super(VoipRestServlet, self).__init__()
  25. self.hs = hs
  26. self.auth = hs.get_auth()
  27. @defer.inlineCallbacks
  28. def on_GET(self, request):
  29. requester = yield self.auth.get_user_by_req(
  30. request, self.hs.config.turn_allow_guests
  31. )
  32. turnUris = self.hs.config.turn_uris
  33. turnSecret = self.hs.config.turn_shared_secret
  34. turnUsername = self.hs.config.turn_username
  35. turnPassword = self.hs.config.turn_password
  36. userLifetime = self.hs.config.turn_user_lifetime
  37. if turnUris and turnSecret and userLifetime:
  38. expiry = (self.hs.get_clock().time_msec() + userLifetime) / 1000
  39. username = "%d:%s" % (expiry, requester.user.to_string())
  40. mac = hmac.new(
  41. turnSecret.encode(), msg=username.encode(), digestmod=hashlib.sha1
  42. )
  43. # We need to use standard padded base64 encoding here
  44. # encode_base64 because we need to add the standard padding to get the
  45. # same result as the TURN server.
  46. password = base64.b64encode(mac.digest())
  47. elif turnUris and turnUsername and turnPassword and userLifetime:
  48. username = turnUsername
  49. password = turnPassword
  50. else:
  51. return (200, {})
  52. return (
  53. 200,
  54. {
  55. "username": username,
  56. "password": password,
  57. "ttl": userLifetime / 1000,
  58. "uris": turnUris,
  59. },
  60. )
  61. def on_OPTIONS(self, request):
  62. return (200, {})
  63. def register_servlets(hs, http_server):
  64. VoipRestServlet(hs).register(http_server)