websocket.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import socket
  2. import ssl
  3. from frame import receive_frame
  4. from handshake import ServerHandshake, ClientHandshake
  5. from errors import SSLError
  6. INHERITED_ATTRS = ['bind', 'close', 'listen', 'fileno', 'getpeername',
  7. 'getsockname', 'getsockopt', 'setsockopt', 'setblocking',
  8. 'settimeout', 'gettimeout', 'shutdown', 'family', 'type',
  9. 'proto']
  10. class websocket(object):
  11. """
  12. Implementation of web socket, upgrades a regular TCP socket to a websocket
  13. using the HTTP handshakes and frame (un)packing, as specified by RFC 6455.
  14. The API of a websocket is identical to that of a regular socket, as
  15. illustrated by the examples below.
  16. Server example:
  17. >>> import twspy, socket
  18. >>> sock = twspy.websocket()
  19. >>> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  20. >>> sock.bind(('', 8000))
  21. >>> sock.listen(5)
  22. >>> client = sock.accept()
  23. >>> client.send(twspy.Frame(twspy.OPCODE_TEXT, 'Hello, Client!'))
  24. >>> frame = client.recv()
  25. Client example:
  26. >>> import twspy
  27. >>> sock = twspy.websocket(location='/my/path')
  28. >>> sock.connect(('', 8000))
  29. >>> sock.send(twspy.Frame(twspy.OPCODE_TEXT, 'Hello, Server!'))
  30. """
  31. def __init__(self, sock=None, protocols=[], extensions=[], origin=None,
  32. location='/', trusted_origins=[], locations=[], auth=None,
  33. sfamily=socket.AF_INET, sproto=0):
  34. """
  35. Create a regular TCP socket of family `family` and protocol
  36. `sock` is an optional regular TCP socket to be used for sending binary
  37. data. If not specified, a new socket is created.
  38. `protocols` is a list of supported protocol names.
  39. `extensions` is a list of supported extensions (`Extension` instances).
  40. `origin` (for client sockets) is the value for the "Origin" header sent
  41. in a client handshake .
  42. `location` (for client sockets) is optional, used to request a
  43. particular resource in the HTTP handshake. In a URL, this would show as
  44. ws://host[:port]/<location>. Use this when the server serves multiple
  45. resources (see `locations`).
  46. `trusted_origins` (for server sockets) is a list of expected values
  47. for the "Origin" header sent by a client. If the received Origin header
  48. has value not in this list, a HandshakeError is raised. If the list is
  49. empty (default), all origins are excepted.
  50. `locations` (for server sockets) is an optional list of resources
  51. serverd by this server. If specified (without trailing slashes), these
  52. are used to verify the resource location requested by a client. The
  53. requested location may be used to distinquish different services in a
  54. server implementation.
  55. `auth` is optional, used for HTTP Basic or Digest authentication during
  56. the handshake. It must be specified as a (username, password) tuple.
  57. `sfamily` and `sproto` are used for the regular socket constructor.
  58. """
  59. self.protocols = protocols
  60. self.extensions = extensions
  61. self.origin = origin
  62. self.location = location
  63. self.trusted_origins = trusted_origins
  64. self.locations = locations
  65. self.auth = auth
  66. self.secure = False
  67. self.handshake_sent = False
  68. self.hooks_send = []
  69. self.hooks_recv = []
  70. self.sock = sock or socket.socket(sfamily, socket.SOCK_STREAM, sproto)
  71. def __getattr__(self, name):
  72. if name in INHERITED_ATTRS:
  73. return getattr(self.sock, name)
  74. raise AttributeError("'%s' has no attribute '%s'"
  75. % (self.__class__.__name__, name))
  76. def accept(self):
  77. """
  78. Equivalent to socket.accept(), but transforms the socket into a
  79. websocket instance and sends a server handshake (after receiving a
  80. client handshake). Note that the handshake may raise a HandshakeError
  81. exception.
  82. """
  83. sock, address = self.sock.accept()
  84. wsock = websocket(sock)
  85. wsock.secure = self.secure
  86. ServerHandshake(wsock).perform(self)
  87. wsock.handshake_sent = True
  88. return wsock, address
  89. def connect(self, address):
  90. """
  91. Equivalent to socket.connect(), but sends an client handshake request
  92. after connecting.
  93. `address` is a (host, port) tuple of the server to connect to.
  94. """
  95. self.sock.connect(address)
  96. ClientHandshake(self).perform()
  97. self.handshake_sent = True
  98. def send(self, *args):
  99. """
  100. Send a number of frames.
  101. """
  102. for frame in args:
  103. for hook in self.hooks_send:
  104. frame = hook(frame)
  105. #print 'send frame:', frame, 'to %s:%d' % self.sock.getpeername()
  106. self.sock.sendall(frame.pack())
  107. def recv(self):
  108. """
  109. Receive a single frames. This can be either a data frame or a control
  110. frame.
  111. """
  112. frame = receive_frame(self.sock)
  113. for hook in self.hooks_recv:
  114. frame = hook(frame)
  115. #print 'receive frame:', frame, 'from %s:%d' % self.sock.getpeername()
  116. return frame
  117. def recvn(self, n):
  118. """
  119. Receive exactly `n` frames. These can be either data frames or control
  120. frames, or a combination of both.
  121. """
  122. return [self.recv() for i in xrange(n)]
  123. def enable_ssl(self, *args, **kwargs):
  124. """
  125. Transforms the regular socket.socket to an ssl.SSLSocket for secure
  126. connections. Any arguments are passed to ssl.wrap_socket:
  127. http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket
  128. """
  129. if self.handshake_sent:
  130. raise SSLError('can only enable SSL before handshake')
  131. self.secure = True
  132. self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)
  133. def add_hook(self, send=None, recv=None, prepend=False):
  134. """
  135. Add a pair of send and receive hooks that are called for each frame
  136. that is sent or received. A hook is a function that receives a single
  137. argument - a Frame instance - and returns a `Frame` instance as well.
  138. `prepend` is a flag indicating whether the send hook is prepended to
  139. the other send hooks. This is expecially useful when a program uses
  140. extensions such as the built-in `DeflateFrame` extension. These
  141. extensions are installed using these hooks as well.
  142. For example, the following code creates a `Frame` instance for data
  143. being sent and removes the instance for received data. This way, data
  144. can be sent and received as if on a regular socket.
  145. >>> import twspy
  146. >>> sock.add_hook(lambda data: tswpy.Frame(tswpy.OPCODE_TEXT, data),
  147. >>> lambda frame: frame.payload)
  148. To add base64 encoding to the example above:
  149. >>> import base64
  150. >>> sock.add_hook(base64.encodestring, base64.decodestring, True)
  151. Note that here `prepend=True`, so that data passed to `send()` is first
  152. encoded and then packed into a frame. Of course, one could also decide
  153. to add the base64 hook first, or to return a new `Frame` instance with
  154. base64-encoded data.
  155. """
  156. if send:
  157. self.hooks_send.insert(0 if prepend else -1, send)
  158. if recv:
  159. self.hooks_recv.insert(-1 if prepend else 0, recv)