Skip to content

Commit

Permalink
added catchall dns implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
jon committed Aug 1, 2022
1 parent dfadbb6 commit 411e399
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion __init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# phew! the Pico (or Python) HTTP Endpoint Wrangler
from .phew import server, logging, connect_to_wifi
from .phew import server, logging, dns, connect_to_wifi

from .phew.server import redirect, serve_file
from .phew.template import render_template
32 changes: 32 additions & 0 deletions phew/dns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import uasyncio, usocket
from . import logging

async def _handler(socket, ip_address):
while True:
try:
yield uasyncio.core._io_queue.queue_read(socket)
request, client = socket.recvfrom(256)
response = request[:2] # request id
response += b"\x81\x80" # response flags
response += request[4:6] + request[4:6] # qd/an count
response += b"\x00\x00\x00\x00" # ns/ar count
response += request[12:] # origional request body
response += b"\xC0\x0C" # pointer to domain name at byte 12
response += b"\x00\x01\x00\x01" # type and class (A record / IN class)
response += b"\x00\x00\x00\x3C" # time to live 60 seconds
response += b"\x00\x04" # response length (4 bytes = 1 ipv4 address)
response += bytes(map(int, ip_address.split("."))) # ip address parts
socket.sendto(response, client)
except Exception as e:
logging.error(e)

def run_catchall(ip_address, port = 53):
logging.info("> starting catch all dns server on port {}".format(port))

_socket = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
_socket.setblocking(False)
_socket.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
_socket.bind(usocket.getaddrinfo(ip_address, port, 0, usocket.SOCK_DGRAM)[0][-1])

loop = uasyncio.get_event_loop()
loop.create_task(_handler(_socket, ip_address))
2 changes: 1 addition & 1 deletion phew/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ def serve_file(file):


def run(host = "0.0.0.0", port = 80):
logging.info("> starting webserver on port {}".format(port))
logging.info("> starting web server on port {}".format(port))

loop = uasyncio.get_event_loop()
loop.create_task(uasyncio.start_server(_handle_request, host, port))
Expand Down

0 comments on commit 411e399

Please sign in to comment.