Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Function to load DNS entries from the /DNS directory
- local function loadDNS()
- local dns = {}
- for _, file in ipairs(fs.list("/DNS")) do
- local f = fs.open("/DNS/" .. file, "r")
- local ip = f.readAll()
- f.close()
- dns[file] = ip
- end
- return dns
- end
- -- Function to log DNS connections
- local function logConnection(url, ip)
- local logFile = fs.open("dns_log.txt", "a")
- logFile.writeLine("URL: " .. url .. ", IP: " .. ip .. ", Time: " .. textutils.formatTime(os.time(), true))
- logFile.close()
- end
- -- Function to load the stored password from /DNS/locked.cfg
- local function loadPassword()
- local filePath = "/DNS/locked.cfg"
- if fs.exists(filePath) then
- local file = fs.open(filePath, "r")
- local password = file.readAll()
- file.close()
- return password
- end
- return nil -- No password file found
- end
- -- Function to handle DNS requests
- local function handleDNSRequest(dns, senderID, url)
- local storedPassword = loadPassword()
- if storedPassword then
- rednet.send(senderID, "PASSWORD_REQUIRED") -- Ask for the password
- local timer = os.startTimer(10) -- Wait for 10 seconds for a response
- while true do
- local event, id, message = os.pullEvent()
- if event == "rednet_message" and id == senderID then
- if message == storedPassword then
- if dns[url] then
- rednet.send(senderID, dns[url])
- logConnection(url, dns[url])
- else
- rednet.send(senderID, "404_NOT_FOUND")
- end
- else
- rednet.send(senderID, "AUTH_FAILED")
- end
- break
- elseif event == "timer" and id == timer then
- rednet.send(senderID, "TIMEOUT")
- break
- end
- end
- else
- if dns[url] then
- rednet.send(senderID, dns[url])
- logConnection(url, dns[url])
- else
- rednet.send(senderID, "404_NOT_FOUND")
- end
- end
- end
- -- Automatically find and open the first available modem
- local function openModem()
- local sides = {"top", "bottom", "left", "right", "front", "back"}
- for _, side in ipairs(sides) do
- if peripheral.isPresent(side) and peripheral.getType(side) == "modem" then
- rednet.open(side)
- return side
- end
- end
- print("Error: No modem found.")
- return nil
- end
- -- Main DNS server function
- local function runDNSServer()
- local modemSide = openModem()
- if not modemSide then return end
- local dns = loadDNS()
- print("DNS Server is running on " .. modemSide .. " modem. Listening for requests...")
- while true do
- local senderID, url = rednet.receive()
- handleDNSRequest(dns, senderID, url)
- end
- end
- -- Main execution
- runDNSServer()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement