jczic / MicroWebSrv

A micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (used on Pycom modules & ESP32)
https://github.com/jczic/MicroWebSrv
MIT License
641 stars 116 forks source link

WebSocket 501 error #6

Closed rdagger closed 6 years ago

rdagger commented 6 years ago

Thanks for creating the WebSocket support! When I run the wstest.html example on an ESP32:

websocket = new WebSocket(wsUri); is throwing the following error:

WebSocket connection to 'ws://192.168.0.39/' failed: Error during WebSocket handshake: Unexpected response code: 501

Looks like there are 2 issues.

  1. def _getConnUpgrade() checks if connection == 'upgrade'. The problem is connection can hold more than 1 attribute such as 'upgrade, keep-alive'. I changed == to in to fix: if 'upgrade' in self._headers.get('Connection', '').lower()

  2. A bigger problem is that uhashlib is not implemented. MicroWebSocket.py imports sha1 from uhashlib. I don't have a fix. MicroPython lib contains a hashlib library. It contains sha256, but not sha1. Is it possible to use sha256 instead of sha1?

jczic commented 6 years ago

Ok for (1), connection can contain keep-alive, but this is strange in a ws request. What's your browser ?

For (2), ok, SHA1 is mandatory yes... It's implemented on pycom modules and on micropython standard. Do you really not have this lib : http://docs.micropython.org/en/latest/wipy/library/uhashlib.html ?

rdagger commented 6 years ago

I was testing with Firefox:

'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0','Connection': 'keep-alive, Upgrade'

Unfortunately, uhashlib is not implemented: import uhashlib

Traceback (most recent call last): File "", line 1, in ImportError: no module named 'uhashlib'

rdagger commented 6 years ago

I posted a question to the MicroPython ESP32 developers and MrSurly responded that there is a hashlib library. They provided the following example:

import binascii, hashlib
hash = hashlib.sha1('mango')
binascii.hexlify(hash.digest()) 

How about enclosing the uhashlib import in a try statement and then if an exception occurs try hashlib?

jczic commented 6 years ago

Ok, it's just "hashlib" and no "uhashlib", depends of implementation. This is possible to load the existing module with :

try :
    from uhashlib import sha1
except :
    from hashlib import sha1

:)

jczic commented 6 years ago

Ok, this is updated with std names (without u prefix).

rdagger commented 6 years ago

Looks like uhashlib was an oversight. A related pull request #178 was just submitted to the MicroPython ESP32 repo.

jczic commented 6 years ago

Oh yes! 👍