0
votes

I'm writing my own websocket server and clients. I have successfully handled handshake and have established connection.

Now I'm writing the send_message function that creates apropriate frame. Below example is just for the purpose of this question, it is not what I finally intend to write and this just one way of many that I've tried giving me same following result.

def send_message(client_socket: socket.socket, message: str):
    length = len(message)
    opcode = 0x1
    fin, rsv1, rsv2, rsv3, opcode = 1, 0, 0, 0, opcode
    first_byte = chr(fin << 7 | rsv1 << 6 | rsv2 << 5 | rsv3 << 4 | opcode)
    if length < 126:
        mask = 0
        second_byte = chr(mask << 7 | length)
        first_byte += second_byte
        first_byte = six.b(first_byte)
    payload = first_byte + message.encode("utf-8")

    return client_socket.send(payload)

For input: Ok from server above function should send b'\x81\x0eOk from server'

First byte \x81 - 10000001

first bit set to 1 - FIN, means that this is last frame of the message

second, third and fourth - all zeros, for this example irrelevant

following four bits - opcode 0001, means the message is text

The problematic Second byte \x0e it should be 00001110 first bit set to 0 - mask, if set to 1 the payload is masked, in my case MUST be set to 0, all messages from server to client MUST not be masked

following 7 bits - payload length, in case of Ok from server = 14

Remaining is the payload.

Now when I send this to javascript client in chrome I receive: WebSocket connection to 'ws://localhost:8002/' failed: A server must not mask any frames that it sends to the client.

I copied code from multiple examples (websockets, SimpleWebsocketServer, etc.) all giving me the same b'\x81\x0eOk from server'

Question #1 What do I do wrong?

Question #2 How do I debug websockets? In chrome devtools there is no longer 'frames' tab for inspecting websockets, so can't see the actual bytes beeing received. Tried Wireshark, but apparantly decoding websocket frames features has been missing in it for years.

Edit

The function creates correct payload, the problem is somewhere else, perhaps socket settings.

1

1 Answers

0
votes

The initial handshake had \n\r instead of \r\n. All clients established connections anyway but when parsing following messages they would receive one extra byte creating skewed frames causing the bug.