Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 37 additions & 14 deletions wifimgr.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@
server_socket = None


def unquote_plus(s):
r = s.replace('+', ' ').split('%')
for i in range(1, len(r)):
s = r[i]
try:
r[i] = chr(int(s[:2], 16)) + s[2:]
except ValueError:
r[i] = '%' + s
return ''.join(r)


def get_connection():
"""return a working WLAN(STA_IF) instance or None"""

Expand Down Expand Up @@ -178,20 +189,19 @@ def handle_root(client):
client.close()


def handle_configure(client, request):
match = ure.search("ssid=([^&]*)&password=(.*)", request)
def handle_configure(client, content):
match = ure.search("ssid=([^&]*)&password=(.*)", content)

if match is None:
send_response(client, "Parameters not found", status_code=400)
return False
# version 1.9 compatibility
try:
ssid = match.group(1).decode("utf-8").replace("%3F", "?").replace("%21", "!")
password = match.group(2).decode("utf-8").replace("%3F", "?").replace("%21", "!")
except Exception:
ssid = match.group(1).replace("%3F", "?").replace("%21", "!")
password = match.group(2).replace("%3F", "?").replace("%21", "!")

ssid = unquote_plus(match.group(1).decode("utf-8"))
password = unquote_plus(match.group(2).decode("utf-8"))
except UnicodeEncodeError:
ssid = unquote_plus(match.group(1))
password = unquote_plus(match.group(2))
if len(ssid) == 0:
send_response(client, "SSID must be provided", status_code=400)
return False
Expand Down Expand Up @@ -281,18 +291,31 @@ def start(port=80):
print('client connected from', addr)
try:
client.settimeout(5.0)

request = b""
request = bytearray()
try:
while "\r\n\r\n" not in request:
request += client.recv(512)
request.extend(client.recv(512))
except OSError:
pass

print("Request is: {}".format(request))
if "HTTP" not in request: # skip invalid requests
if "HTTP" not in request:
# skip invalid requests
continue

if "POST" in request and "Content-Length: " in request:
content_length = int(ure.search("Content-Length: ([0-9]+)?", bytes(request)).group(1))
content = bytearray(request[bytes(request).index(b"\r\n\r\n") + 4:])
content_length_remaining = content_length - len(content)

while content_length_remaining > 0:
chunk = client.recv(512)
content.extend(chunk)
content_length_remaining -= len(chunk)

request = bytes(request)

print("Request is: {}".format(request))

# version 1.9 compatibility
try:
url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).decode("utf-8").rstrip("/")
Expand All @@ -303,7 +326,7 @@ def start(port=80):
if url == "":
handle_root(client)
elif url == "configure":
handle_configure(client, request)
handle_configure(client, bytes(content))
else:
handle_not_found(client, url)

Expand Down