def test_send_message_deflate_frame_bfinal(self):
        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        request = _create_request_from_rawdata(
            '', deflate_frame_request=extension)
        self.assertEquals(1, len(request.ws_extension_processors))
        deflate_frame_processor = request.ws_extension_processors[0]
        deflate_frame_processor.set_bfinal(True)
        msgutil.send_message(request, 'Hello')
        msgutil.send_message(request, 'World')

        expected = ''

        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
        compressed_hello = compress.compress('Hello')
        compressed_hello += compress.flush(zlib.Z_FINISH)
        compressed_hello = compressed_hello + chr(0)
        expected += '\xc1%c' % len(compressed_hello)
        expected += compressed_hello

        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
        compressed_world = compress.compress('World')
        compressed_world += compress.flush(zlib.Z_FINISH)
        compressed_world = compressed_world + chr(0)
        expected += '\xc1%c' % len(compressed_world)
        expected += compressed_world

        self.assertEqual(expected, request.connection.written_data())
Example #2
0
def web_socket_transfer_data(request):
    lastmsg = ''
    r = redis.Redis()
    timelim = time.time() + timeout
    
    while True:
        #words = msgutil.receive_message(request)
        #if words == __KillerWords__:
        #    break
            
        # get last 10 messages
        messages = r.lrange('msgs',0,9)
        try:
            # give remaining messages from buffer
            lastindex = messages.index(lastmsg)
            if (lastindex>0):
                timelim = time.time() + timeout
                for i in xrange(0,lastindex):
                    msgutil.send_message(request,
                                    messages[lastindex - i -1].split('|',1)[1])
        except ValueError:
            # client has not received anything at all, give the whole buffer
            for msg in messages[::-1]:
                msgutil.send_message(request, msg.split('|',1)[1])
            timelim = time.time() + timeout
            
        lastmsg = messages[0]

        if (time.time() > timelim):
            print "A receive timedout"
            r.disconnect()
            break
    def test_send_message_permessage_compress_deflate_fragmented_bfinal(self):
        extension = common.ExtensionParameter(
            common.PERMESSAGE_COMPRESSION_EXTENSION)
        extension.add_parameter('method', 'deflate')
        request = _create_request_from_rawdata(
                      '', permessage_compression_request=extension)
        self.assertEquals(1, len(request.ws_extension_processors))
        compression_processor = (
            request.ws_extension_processors[0].get_compression_processor())
        compression_processor.set_bfinal(True)
        msgutil.send_message(request, 'Hello', end=False)
        msgutil.send_message(request, 'World', end=True)

        expected = ''

        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
        compressed_hello = compress.compress('Hello')
        compressed_hello += compress.flush(zlib.Z_FINISH)
        compressed_hello = compressed_hello + chr(0)
        expected += '\x41%c' % len(compressed_hello)
        expected += compressed_hello

        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)
        compressed_world = compress.compress('World')
        compressed_world += compress.flush(zlib.Z_FINISH)
        compressed_world = compressed_world + chr(0)
        expected += '\x80%c' % len(compressed_world)
        expected += compressed_world

        self.assertEqual(expected, request.connection.written_data())
Example #4
0
def web_socket_transfer_data(request):
    global connections
    r = request.ws_resource.split('?', 1)
    if len(r) == 1:
        return
    param = cgi.parse_qs(r[1])
    if 'p' not in param:
        return
    page_group = param['p'][0]
    if page_group in connections:
        connections[page_group].add(request)
    else:
        connections[page_group] = set([request])
    message = None
    dataToBroadcast = {}
    try:
        message = msgutil.receive_message(request)
        # notify to client that message is received by server.
        msgutil.send_message(request, message)
        msgutil.receive_message(request)
        dataToBroadcast['message'] = message
        dataToBroadcast['closeCode'] = str(request.ws_close_code)
    finally:
        # request is closed. notify this dataToBroadcast to other WebSockets.
        connections[page_group].remove(request)
        for ws in connections[page_group]:
            msgutil.send_message(ws, json.dumps(dataToBroadcast))
 def onMessage(self, mosq, obj, msg):
     if _status_ == _OPEN_:
         try:
             string = json.dumps({"topic": msg.topic, "message": msg.payload})
             msgutil.send_message(self.socket, string)
         except Exception:
             return
 def onPublish(self, mosq, obj, mid):
     if _status_ == _OPEN_:
         try:
             string = json.dumps({"topic": self.topic + "/server", "message": "Message published to broker"})
             msgutil.send_message(self.socket, string)
         except Exception:
             return
Example #7
0
def web_socket_transfer_data(request):
    # pywebsocket does not mask message by default. We need to build a frame manually to mask it.
    request.connection.write(stream.create_text_frame('First message', mask=False))

    request.connection.write(stream.create_text_frame('Fragmented ', opcode=common.OPCODE_TEXT, fin=0, mask=False))
    request.connection.write(stream.create_text_frame('message', opcode=common.OPCODE_CONTINUATION, fin=1, mask=False))

    request.connection.write(stream.create_text_frame('', mask=False))

    msgutil.send_message(request, 'END')

    # Wait for the client to start closing handshake.
    # To receive a close frame, we must use an internal method of request.ws_stream.
    opcode, payload, final, reserved1, reserved2, reserved3 = request.ws_stream._receive_frame()
    assert opcode == common.OPCODE_CLOSE
    assert final
    assert not reserved1
    assert not reserved2
    assert not reserved3

    # Send a masked close frame. Clients should be able to handle this frame and
    # the WebSocket object should be closed cleanly.
    request.connection.write(stream.create_close_frame('', mask=False))

    # Prevents pywebsocket from starting its own closing handshake.
    raise handshake.AbortedByUserException('Abort the connection')
Example #8
0
def web_socket_transfer_data(request):
    from urlparse import urlparse
    from urlparse import parse_qs
    #requests.append(request)
    url = urlparse(request.get_uri())
    query = parse_qs(url.query)
    if query.has_key('projectName'):
        projectNames = query["projectName"]
        if len(projectNames) == 1:
            projectName = projectNames[0]
            if not rooms.has_key(projectName):
                rooms[projectName] = []
            rooms[projectName].append(request)
    while True:
        try:
            message = msgutil.receive_message(request)
        except Exception:
            return
        #for req in requests:
        #    try:
        #        msgutil.send_message(req, message)
        #    except Exception:
        #        requests.remove(req)
        for req in rooms[projectName]:
            try:
                msgutil.send_message(req, message)
            except Exception:
                rooms[projectName].remove(req)
                if len(rooms[projectName]) == 0:
                    del rooms[projectName]
Example #9
0
def web_socket_transfer_data(request):
    while True:
        line = request.ws_stream.receive_message()
        if line == "echo":
            query = request.unparsed_uri.split('?')[1]
            GET = dict(urllib.parse.parse_qsl(query))

            # TODO(kristijanburnik): This code should be reused from
            # /mixed-content/generic/expect.py or implemented more generally
            # for other tests.
            path = GET.get("path", request.unparsed_uri.split('?')[0])
            key = GET["key"]
            action = GET["action"]

            if action == "put":
              value = GET["value"]
              stash.take(key=key, path=path)
              stash.put(key=key, value=value, path=path)
              response_data = json.dumps({"status": "success", "result": key})
            elif action == "purge":
             value = stash.take(key=key, path=path)
             response_data = json.dumps({"status": "success", "result": value})
            elif action == "take":
              value = stash.take(key=key, path=path)
              if value is None:
                  status = "allowed"
              else:
                  status = "blocked"
              response_data = json.dumps({"status": status, "result": value})

            msgutil.send_message(request, response_data)

            return
def web_socket_transfer_data(request):
    for i in range(1, 128):
        request.connection.write(chr(i) + str(i) + '\xff')
    for i in range(128, 256):
        msg = str(i)
        request.connection.write(chr(i) + chr(len(msg)) + msg)
    msgutil.send_message(request, 'done')
Example #11
0
    def test_send_message_deflate_frame(self):
        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        request = _create_request_from_rawdata(
            '', deflate_frame_request=extension)
        msgutil.send_message(request, 'Hello')
        msgutil.send_message(request, 'World')

        expected = ''

        compressed_hello = compress.compress('Hello')
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        expected += '\xc1%c' % len(compressed_hello)
        expected += compressed_hello

        compressed_world = compress.compress('World')
        compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_world = compressed_world[:-4]
        expected += '\xc1%c' % len(compressed_world)
        expected += compressed_world

        self.assertEqual(expected, request.connection.written_data())
Example #12
0
def web_socket_transfer_data(request):
    pragma = request.headers_in.get('Pragma')
    cache_control = request.headers_in.get('Cache-Control')
    if pragma == 'no-cache' and cache_control == 'no-cache':
        msgutil.send_message(request, 'PASS')
    else:
        msgutil.send_message(request, 'FAIL')
def listen_psirp_updates(request, subscriber):
  while True:
    for version in subscriber.listen():
      if version is not None: # if publication exists
        print('Sending from Blackhawk: %s' % str(version.buffer))
        msgutil.send_message(request, '%s' % str(version.buffer))
      else:
        print("Received Publishment was null :(")
Example #14
0
    def test_send_message_deflate_stream(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        request = _create_request_from_rawdata("", deflate_stream=True)
        msgutil.send_message(request, "Hello")
        expected = compress.compress("\x81\x05Hello")
        expected += compress.flush(zlib.Z_SYNC_FLUSH)
        self.assertEqual(expected, request.connection.written_data())
def web_socket_transfer_data(request):
  while True:
    rcvd = msgutil.receive_message(request)
    opcode = request.ws_stream.get_last_received_opcode()
    if (opcode == common.OPCODE_BINARY):
      msgutil.send_message(request, rcvd, binary=True)
    elif (opcode == common.OPCODE_TEXT):
      msgutil.send_message(request, rcvd)
Example #16
0
def web_socket_transfer_data(request):
	while True:
		s = msgutil.receive_message(request)
		for connect in arr:
			try:
				msgutil.send_message(connect, s)
			except:
				arr.remove(connect)
Example #17
0
def web_socket_transfer_data(request):
    while True:
        line = msgutil.receive_message(request)
        print "received:", line
        line = str(int(line)*2)
        msgutil.send_message(request, line)
        if line == _GOODBYE_MESSAGE:
            return
Example #18
0
def web_socket_transfer_data(request):
    # send_message's third argument corresponds to "fin" bit;
    # it is set to True if this frame is the final fragment of a message.

    pause_briefly()
    msgutil.send_message(request, '', False)
    pause_briefly()
    msgutil.send_message(request, '', True)
    pause_briefly()
Example #19
0
def web_socket_transfer_data(request):
    expected_messages = ['Hello, world!']

    for test_number, expected_message in enumerate(expected_messages):
        frame = _retrieve_frame(request.ws_stream)
        if frame.opcode == common.OPCODE_BINARY and frame.payload == expected_message and frame.fin:
            msgutil.send_message(request, 'PASS: Message #%d.' % test_number)
        else:
            msgutil.send_message(request, 'FAIL: Message #%d: Received unexpected frame: opcode = %r, payload = %r, final = %r' % (test_number, frame.opcode, frame.payload, frame.fin))
Example #20
0
def web_socket_transfer_data(request):
	while True:
		s = msgutil.receive_message(request)
		n = int(s)
		total = 0
		for i in range(1,n + 1):
			total = total + i
		s2 = str(total)
		msgutil.send_message(request, s2)
Example #21
0
    def test_send_message(self):
        request = _create_request()
        msgutil.send_message(request, "Hello")
        self.assertEqual("\x81\x05Hello", request.connection.written_data())

        payload = "a" * 125
        request = _create_request()
        msgutil.send_message(request, payload)
        self.assertEqual("\x81\x7d" + payload, request.connection.written_data())
def web_socket_transfer_data(request):
    expected_messages = ['Hello, world!', '', all_distinct_bytes()]

    for test_number, expected_message in enumerate(expected_messages):
        message = msgutil.receive_message(request)
        if type(message) == str and message == expected_message:
            msgutil.send_message(request, 'PASS: Message #%d.' % test_number)
        else:
            msgutil.send_message(request, 'FAIL: Message #%d: Received unexpected message: %r' % (test_number, message))
Example #23
0
def web_socket_transfer_data(request):
    match = re.search(r"\?opcode=(\d+)$", request.ws_resource)
    if match is None:
        msgutil.send_message(request, "FAIL: Query value is incorrect or missing")
        return

    opcode = int(match.group(1))
    payload = "This text should be ignored. (opcode = %d)" % opcode
    request.connection.write(stream.create_header(opcode, len(payload), 1, 0, 0, 0, 0) + payload)
def initialize_subscriber(request):
  line = msgutil.receive_message(request).encode('utf-8')
  try:
    msg = json.loads(line)
    sid = str(msg["subscribe"]["sid"])
    rid = str(msg["subscribe"]["rid"])
  except ValueError, e:
    msgutil.send_message(request, '%s' % json_message("message", str(e) + " " + line))
    return False
Example #25
0
    def test_send_medium_message(self):
        payload = "a" * 126
        request = _create_request()
        msgutil.send_message(request, payload)
        self.assertEqual("\x81\x7e\x00\x7e" + payload, request.connection.written_data())

        payload = "a" * ((1 << 16) - 1)
        request = _create_request()
        msgutil.send_message(request, payload)
        self.assertEqual("\x81\x7e\xff\xff" + payload, request.connection.written_data())
def web_socket_transfer_data(request):
    expected_messages = ['Hello, world!']

    for test_number, expected_message in enumerate(expected_messages):
        # FIXME: Use better API.
        opcode, payload, final, unused_reserved1, unused_reserved2, unused_reserved3 = request.ws_stream._receive_frame()
        if opcode == common.OPCODE_BINARY and payload == expected_message and final:
            msgutil.send_message(request, 'PASS: Message #%d.' % test_number)
        else:
            msgutil.send_message(request, 'FAIL: Message #%d: Received unexpected frame: opcode = %r, payload = %r, final = %r' % (test_number, opcode, payload, final))
Example #27
0
def web_socket_transfer_data(request):
    while True:
        time.sleep(1)
        try:
            line = msgutil.receive_message(request)
        except Exception, e:
            raise e
        msgutil.send_message(request, line)
        if line == GOODBYEMESSAGE:
            return
Example #28
0
    def test_send_message(self):
        request = _create_request()
        msgutil.send_message(request, 'Hello')
        self.assertEqual('\x81\x05Hello', request.connection.written_data())

        payload = 'a' * 125
        request = _create_request()
        msgutil.send_message(request, payload)
        self.assertEqual('\x81\x7d' + payload,
                         request.connection.written_data())
 def run(self):
   while True:
     line = msgutil.receive_message(self.websocket).encode('utf-8')
     print("received %s" % line)
     try:
       msg = json.loads(line)
       self.act_on(msg)
       continue
     except ValueError, e:
       msg = json_message("message", "data is not json: "+ line)
       msgutil.send_message(self.websocket, '%s' % msg)
def web_socket_transfer_data(request):
  subscriber = initialize_subscriber(request)
  initial_content = subscriber.get_initial_content()  
  if initial_content is not None:
    print("Sending initial content: %s" % str(initial_content.buffer))
    msgutil.send_message(request, '%s' % str(initial_content.buffer))
  
  seat_reserver = SeatReserver(request, subscriber.sid, subscriber.rid)
  seat_reserver.start()

  listen_psirp_updates(request, subscriber)
Example #31
0
def web_socket_transfer_data(request):
    global connections
    connections[request] = True
    socketName = None
    try:
        socketName = msgutil.receive_message(request)
        # notify to client that socketName is received by server.
        msgutil.send_message(request, socketName)
        msgutil.receive_message(request)  # wait, and exception by close.
        socketName = socketName + ': receive next message'
    finally:
        # request is closed. notify this socketName to other web sockets.
        del connections[request]
        for ws in connections.keys():
            msgutil.send_message(ws, socketName)
Example #32
0
def web_socket_transfer_data(request):
    expected_messages = ["Hello, world!", "", all_distinct_bytes()]

    for test_number, expected_message in enumerate(expected_messages):
        expected_message = six.b(expected_message)
        message = msgutil.receive_message(request)
        if message == expected_message:
            msgutil.send_message(request, "PASS: Message #{:d}.".format(test_number))
        else:
            msgutil.send_message(
                request,
                "FAIL: Message #{:d}: Received unexpected message: {!r}".format(
                    test_number, message
                ),
            )
Example #33
0
 def test_send_message_fragments(self):
     request = _create_request()
     msgutil.send_message(request, 'Hello', False)
     msgutil.send_message(request, ' ', False)
     msgutil.send_message(request, 'World', False)
     msgutil.send_message(request, '!', True)
     self.assertEqual(b'\x01\x05Hello\x00\x01 \x00\x05World\x80\x01!',
                      request.connection.written_data())
Example #34
0
    def test_send_message(self):
        extension = common.ExtensionParameter(
            common.PERMESSAGE_DEFLATE_EXTENSION)
        request = _create_request_from_rawdata(
            b'', permessage_deflate_request=extension)
        msgutil.send_message(request, 'Hello')

        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)
        compressed_hello = compress.compress(b'Hello')
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        expected = b'\xc1%c' % len(compressed_hello)
        expected += compressed_hello
        self.assertEqual(expected, request.connection.written_data())
Example #35
0
def web_socket_transfer_data(request):
    # Wait for a close frame sent from the client.
    close_frame = request.ws_stream.receive_bytes(2)

    # Tell the client what we have received.
    msgutil.send_message(request, 'close_frame=%r' % close_frame)

    # If the following assertion fails, AssertionError will be raised,
    # which will prevent pywebsocket from sending a close frame.
    # In this case, the client will fail to finish closing handshake, thus
    # closeEvent.wasClean will become false.
    assert close_frame == '\xff\x00'

    # Pretend we have received a close frame from the client.
    # After this function exits, pywebsocket will send a close frame automatically.
    request.client_terminated = True
Example #36
0
    def test_send_empty_message(self):
        """Test that an empty message is compressed correctly."""

        extension = common.ExtensionParameter(
            common.PERMESSAGE_DEFLATE_EXTENSION)
        request = _create_request_from_rawdata(
            b'', permessage_deflate_request=extension)

        msgutil.send_message(request, '')

        # Payload in binary: 0b00000000
        # From LSB,
        # - 1 bit of BFINAL (0)
        # - 2 bits of BTYPE (no compression)
        # - 5 bits of padding
        self.assertEqual(b'\xc1\x01\x00', request.connection.written_data())
Example #37
0
def web_socket_transfer_data(request):
    # Wait for a close frame sent from the client.
    close_frame = request.ws_stream.receive_bytes(6)

    # Send only first two bytes of the received frame. The remaining four bytes are
    # "masking key", which changes every time the test runs.
    msgutil.send_message(request, 'close_frame[:2]=%r' % close_frame[:2])

    # If the following assertion fails, AssertionError will be raised,
    # which will prevent pywebsocket from sending a close frame.
    # In this case, the client will fail to finish closing handshake, thus
    # closeEvent.wasClean will become false.
    assert close_frame[:2] == '\x88\x80'

    # Pretend we have received a close frame from the client.
    # After this function exits, pywebsocket will send a close frame automatically.
    request.client_terminated = True
Example #38
0
def web_socket_transfer_data(request):
    global connections
    connections[request] = True
    socketName = None
    receivedException = True
    try:
        socketName = msgutil.receive_message(request)
        msgutil.send_message(request, socketName)
        msgutil.receive_message(request)  # wait, and exception by close.
        receivedException = False
    finally:
        # We keep track of whether we have an exception.
        del connections[request]
        for ws in connections.keys():
            msgutil.send_message(
                ws, "Closed by exception"
                if receivedException else "Closed without exception")
def web_socket_transfer_data(request):
    # Wait for a close frame sent from the client.
    close_frame = request.ws_stream.receive_bytes(6)

    msgutil.send_message(request, 'Client should ignore this message')

    # Send only first two bytes of the received frame. The remaining four bytes
    # are "masking key", which changes every time the test runs.

    message = "close_frame[:2]='%s'" % util.hexify(close_frame[:2])
    data = struct.pack('!H', 1000) + message.encode('UTF-8')

    request.connection.write(stream.create_close_frame(data))

    # Tell pywebsocket we have sent a close frame to the client, so it can close
    # the connection.
    request.server_terminated = True
Example #40
0
def web_socket_transfer_data(request):
    send_payload = ''
    r = request.ws_resource.split('?', 1)
    if len(r) == 2:
        params = cgi.parse_qs(r[1])
        if 'payload' in params:
            send_payload = params['payload'][0]

    msgutil.send_ping(request, send_payload)

    # We need to use an internal function to detect a pong frame from the client.
    opcode, recv_payload, final, reserved1, reserved2, reserved3 = request.ws_stream._receive_frame()
    if opcode == common.OPCODE_PONG and recv_payload == send_payload and final and not reserved1 and not reserved2 and not reserved3:
        msgutil.send_message(request, 'PASS')
    else:
        msgutil.send_message(request,
                             'FAIL: Received unexpected frame: opcode = %r, payload = %r, final = %r, reserved1 = %r, reserved2 = %r, reserved3 = %r' %
                             (opcode, recv_payload, final, reserved1, reserved2, reserved3))
Example #41
0
def web_socket_transfer_data(request):
    line = request.ws_stream.receive_message()

    query = json.loads(line)
    action = query["action"]
    key = query["key"]

    if action == "set":
        value = query["value"]
        handle_set(key, value)
        response = {}
    elif action == "get":
        value = handle_get(key)
        response = {"value": value}
    else:
        response = {}

    msgutil.send_message(request, json.dumps(response))
Example #42
0
    def test_send_message_deflate_frame_no_context_takeover_parameter(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        extension.add_parameter('no_context_takeover', None)
        request = _create_request_from_rawdata('',
                                               deflate_frame_request=extension)
        for i in xrange(3):
            msgutil.send_message(request, 'Hello')

        compressed_message = compress.compress('Hello')
        compressed_message += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_message = compressed_message[:-4]
        expected = '\xc1%c' % len(compressed_message)
        expected += compressed_message

        self.assertEqual(expected + expected + expected,
                         request.connection.written_data())
Example #43
0
def web_socket_transfer_data(request):
    # Wait for a close frame sent from the client.
    close_frame = request.ws_stream.receive_bytes(6)

    msgutil.send_message(request, 'Client should ignore this message')

    # Send only first two bytes of the received frame. The remaining four bytes are
    # "masking key", which changes every time the test runs.
    data = struct.pack('!H', 1000) + ('close_frame[:2]={}'.format(
        close_frame[:2]).replace("='", "=b'")).encode()
    request.connection.write(stream.create_close_frame(data))

    # If the following assertion fails, AssertionError will be raised,
    # which will prevent pywebsocket from sending a close frame.
    # In this case, the client will fail to finish closing handshake, thus
    # closeEvent.wasClean will become false.
    assert close_frame[:2] == b'\x88\x80'

    # Pretend we have received a close frame from the client.
    # After this function exits, pywebsocket will send a close frame automatically.
    request.client_terminated = True
Example #44
0
    def test_send_message_deflate_frame_comp_bit(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        request = _create_request_from_rawdata('',
                                               deflate_frame_request=extension)
        self.assertEquals(1, len(request.ws_extension_processors))
        deflate_frame_processor = request.ws_extension_processors[0]
        msgutil.send_message(request, 'Hello')
        deflate_frame_processor.disable_outgoing_compression()
        msgutil.send_message(request, 'Hello')
        deflate_frame_processor.enable_outgoing_compression()
        msgutil.send_message(request, 'Hello')

        expected = ''

        compressed_hello = compress.compress('Hello')
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        expected += '\xc1%c' % len(compressed_hello)
        expected += compressed_hello

        expected += '\x81\x05Hello'

        compressed_2nd_hello = compress.compress('Hello')
        compressed_2nd_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_2nd_hello = compressed_2nd_hello[:-4]
        expected += '\xc1%c' % len(compressed_2nd_hello)
        expected += compressed_2nd_hello

        self.assertEqual(expected, request.connection.written_data())
Example #45
0
    def test_send_message_fragmented(self):
        extension = common.ExtensionParameter(
            common.PERMESSAGE_DEFLATE_EXTENSION)
        request = _create_request_from_rawdata(
            b'', permessage_deflate_request=extension)
        msgutil.send_message(request, 'Hello', end=False)
        msgutil.send_message(request, 'Goodbye', end=False)
        msgutil.send_message(request, 'World')

        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)
        compressed_hello = compress.compress(b'Hello')
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        expected = b'\x41%c' % len(compressed_hello)
        expected += compressed_hello
        compressed_goodbye = compress.compress(b'Goodbye')
        compressed_goodbye += compress.flush(zlib.Z_SYNC_FLUSH)
        expected += b'\x00%c' % len(compressed_goodbye)
        expected += compressed_goodbye
        compressed_world = compress.compress(b'World')
        compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_world = compressed_world[:-4]
        expected += b'\x80%c' % len(compressed_world)
        expected += compressed_world
        self.assertEqual(expected, request.connection.written_data())
Example #46
0
def web_socket_transfer_data(request):
    while True:
        line = request.ws_stream.receive_message()
        if line == "echo":
            query = request.unparsed_uri.split('?')[1]
            GET = dict(urlparse.parse_qsl(query))

            # TODO(kristijanburnik): This code should be reused from
            # /mixed-content/generic/expect.py or implemented more generally
            # for other tests.
            path = GET.get("path", request.unparsed_uri.split('?')[0])
            key = GET["key"]
            action = GET["action"]

            if action == "put":
                value = GET["value"]
                stash.take(key=key, path=path)
                stash.put(key=key, value=value, path=path)
                response_data = json.dumps({
                    "status": "success",
                    "result": key
                })
            elif action == "purge":
                value = stash.take(key=key, path=path)
                response_data = json.dumps({
                    "status": "success",
                    "result": value
                })
            elif action == "take":
                value = stash.take(key=key, path=path)
                if value is None:
                    status = "allowed"
                else:
                    status = "blocked"
                response_data = json.dumps({"status": status, "result": value})

            msgutil.send_message(request, response_data)

            return
Example #47
0
    def test_send_message_with_null_character(self):
        """Test that a simple payload (one null) is framed correctly."""

        extension = common.ExtensionParameter(
            common.PERMESSAGE_DEFLATE_EXTENSION)
        request = _create_request_from_rawdata(
            b'', permessage_deflate_request=extension)

        msgutil.send_message(request, '\x00')

        # Payload in binary: 0b01100010 0b00000000 0b00000000
        # From LSB,
        # - 1 bit of BFINAL (0)
        # - 2 bits of BTYPE (01 that means fixed Huffman)
        # - 8 bits of the first code (00110000 that is the code for the literal
        #   alphabet 0x00)
        # - 7 bits of the second code (0000000 that is the code for the
        #   end-of-block)
        # - 1 bit of BFINAL (0)
        # - 2 bits of BTYPE (no compression)
        # - 2 bits of padding
        self.assertEqual(b'\xc1\x03\x62\x00\x00',
                         request.connection.written_data())
Example #48
0
	def read(self):
		try:
			length = 0
			f = open(self.filename, 'r')
			for line in f:
				length += 1

			f.seek(0)
			cnt = 0

			for line in f:
				cnt += 1
				if cnt == length:
					#######################################################
					# Note::
					# mesgutil.send_message()'s second parameter require
					# 'unicode'. so you shoule use decode('utf-8')
					#######################################################
					msgutil.send_message(self.sock, line[:-1].decode('utf-8'))
			f.close
		except Exception:
			if(f):
				f.close
def web_socket_transfer_data(request):
    # pywebsocket does not mask message by default. We need to build a frame manually to mask it.
    request.connection.write(
        stream.create_text_frame('First message', mask=True))

    request.connection.write(
        stream.create_text_frame('Fragmented ',
                                 opcode=common.OPCODE_TEXT,
                                 fin=0,
                                 mask=True))
    request.connection.write(
        stream.create_text_frame('message',
                                 opcode=common.OPCODE_CONTINUATION,
                                 fin=1,
                                 mask=True))

    request.connection.write(stream.create_text_frame('', mask=True))

    msgutil.send_message(request, 'END')

    # Wait for the client to start closing handshake.
    # To receive a close frame, we must use an internal method of request.ws_stream.
    opcode, payload, final, reserved1, reserved2, reserved3 = request.ws_stream._receive_frame(
    )
    assert opcode == common.OPCODE_CLOSE
    assert final
    assert not reserved1
    assert not reserved2
    assert not reserved3

    # Send a masked close frame. Clients should be able to handle this frame and
    # the WebSocket object should be closed cleanly.
    request.connection.write(stream.create_close_frame('', mask=True))

    raise handshake.AbortedByUserException(
        'Abort the connection'
    )  # Prevents pywebsocket from starting its own closing handshake.
Example #50
0
def web_socket_transfer_data(request):
    # Send three messages, and then wait for three messages.
    msgutil.send_message(request, '1')
    msgutil.send_message(request, '2')
    msgutil.send_message(request, '3')

    for expected in (u'1', u'2', u'3'):
        message = msgutil.receive_message(request)
        if type(message) != str or message != expected:
            raise handshake.AbortedByUserException('Abort the connection')
def web_socket_transfer_data(request):
    while True:
        line = msgutil.receive_message(request)
        if line == 'protocol':
            msgutil.send_message(request, request.ws_protocol)
            continue

        if line == 'resource':
            msgutil.send_message(request, request.ws_resource)
            continue

        if line == 'origin':
            msgutil.send_message(request, request.ws_origin)
            continue

        msgutil.send_message(request, line)

        if line == 'end':
            return
Example #52
0
def web_socket_transfer_data(request):
    while True:
        line = msgutil.receive_message(request)
        if line == "protocol":
            msgutil.send_message(request, request.ws_protocol)
            continue

        if line == "resource":
            msgutil.send_message(request, request.ws_resource)
            continue

        if line == "origin":
            msgutil.send_message(request, request.ws_origin)
            continue

        msgutil.send_message(request, line)

        if line == "end":
            return
def web_socket_transfer_data(request):
    #function is called when a websocket connection is established
    sp = sphero.Sphero()
    print "Connected to Web-Client"
    while True:
        try:
            data = json.loads(msgutil.receive_message(
                request))  #read websocket and deserialize the JSON object
            command = data["command"]
            listDevicesThread = None
            connectionThread = None
            if (command == "listDevices"):
                print 'list spheros'
                devices = sp.findSpheros()
                jDev = []
                for d in devices:
                    jDev.append({'name': d[1], 'address': d[0]})
                print "found: ", jDev
                if len(jDev) == 0:
                    print "Pair Sphero to computer via Bluetooth Manager first."
                    print "Then, try to select address again."
                msgutil.send_message(request, json.dumps(
                    jDev))  #serialize list into JSON and send over the socket
            elif (command == "cancelListDevices"):
                print "cancel device search"
                listDevicesThread.terminate()
                listDevicesThread = None
            elif (command == "connectToDevice"):
                name = data["name"]
                address = data["address"]
                print "connect to: ", name, address
                try:
                    sp.connect(address)
                    msgutil.send_message(request,
                                         json.dumps({'connected': True}))
                    print "connection successful"
                except Exception, e:
                    print str(e)
                    msgutil.send_message(request,
                                         json.dumps({'connected': False}))
                    print "connection failed"
            elif (command == "cancelConnection"):
                print "cancel attempted connection"
                connectionThread.terminate()
                connectionThread = None
            elif (command == "disconnect"):
                try:
                    sp.disconnect()
                except:
                    pass
Example #54
0
def web_socket_transfer_data(request):
    for i in range(NUMBER_OF_MESSAGES):
        # We need to use an internal function to verify that the frame has the
        # "final" flag set.
        opcode, recv_payload, final, reserved1, reserved2, reserved3 = \
            request.ws_stream._receive_frame()

        # We assume that the browser will not send any control messages.
        if opcode != common.OPCODE_BINARY:
            msgutil.send_message(request,
                                 'FAIL: message %r was not opcode binary' % i)
            return

        if not final:
            msgutil.send_message(request,
                                 'FAIL: message %r was fragmented' % i)
            return

        msgutil.send_message(request, 'OK: message %r not fragmented' % i)
def web_socket_transfer_data(request):
    while True:
        line = msgutil.receive_message(request)
        msgutil.send_message(request, line)
        if line == _GOODBYE_MESSAGE:
            return
Example #56
0
def web_socket_transfer_data(request):
    msgutil.send_message(request, 'Hello from Simple WSH.')
Example #57
0
def web_socket_transfer_data(request):
    msgutil.send_message(request, request.ws_protocol)
    # Wait for a close message.
    unused = request.ws_stream.receive_message()
Example #58
0
 def send(self, req, obj):
     return send_message(req, dumps(obj))
Example #59
0
 def send_result(self, req, code, result):
     return send_message(req, dumps([code, result]))
Example #60
0
def web_socket_transfer_data(request):
    msgutil.send_message(request, 'Hello from Handshake Error WSH.')