From 38eef0e33e23b2690b053a860689496bc61db2ac Mon Sep 17 00:00:00 2001 From: nexy7574 Date: Fri, 19 Apr 2024 11:23:53 +0100 Subject: [PATCH] Add /imfeelinglucky and /raw --- ipserv.py | 48 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/ipserv.py b/ipserv.py index 8cba0e7..9fdf3eb 100644 --- a/ipserv.py +++ b/ipserv.py @@ -3,8 +3,9 @@ import json import logging import time import aiohttp +import random from fastapi import FastAPI, Header, Request, Query, HTTPException -from fastapi.responses import JSONResponse +from fastapi.responses import JSONResponse, PlainTextResponse from contextlib import asynccontextmanager logging.basicConfig(level=logging.INFO) @@ -26,6 +27,13 @@ app.state.cache = {} async def make_request(ip: str, headers: dict[str, str]) -> dict | HTTPException: + if ip in app.state.cache: + data, timestamp = app.state.cache[ip] + if time.time() - timestamp < 3600: + logging.info("cache hit for %s", ip) + return data + logging.info("cache expired for %s", ip) + try: async with app.state.session.get(f"/lookup?ip={ip}") as response: data = await response.json() @@ -51,20 +59,13 @@ async def ip( else: ip = request.client.host - if ip in app.state.cache: - data, timestamp = app.state.cache[ip] - if time.time() - timestamp < 3600: - logging.info("cache hit for %s", ip) - return JSONResponse(data) - logging.info("cache expired for %s", ip) - logging.info("looking up IP info for %s", ip) data = await make_request( ip, {"User-Agent": User_Agent} ) if isinstance(data, HTTPException): - return data + raise data data["ip"] = ip data.pop("legalese", None) data.pop("source", None) @@ -89,7 +90,7 @@ async def lookup(ip: str = Query(...), User_Agent: str = Header("Mozilla/5.0")): {"User-Agent": User_Agent} ) if isinstance(data, HTTPException): - return data + raise data data["ip"] = ip data.pop("legalese", None) data.pop("source", None) @@ -97,3 +98,30 @@ async def lookup(ip: str = Query(...), User_Agent: str = Header("Mozilla/5.0")): logging.info("%s -> %r", ip, data) app.state.cache[ip] = [data, time.time()] return JSONResponse(data) + + +@app.get("/imfeelinglucky") +async def im_feeling_lucky(req: Request): + host = req.client.host + if host.count(".") != 3: + raise HTTPException(400, "IPv4 only endpoint.") + + data = await make_request(host, {"User-Agent": "Mozilla/5.0 Nex/19.04.2024"}) + if not isinstance(data, dict): + raise data + data = data.copy() + + parts = list(map(int, host.split("."))) + n = random.randint(1, 1000) + if n in range(50, 54): + if n > 400: + parts[n % 4] += 1 + else: + parts[n % 4] -= 1 + data["ip"] = ".".join(map(str, parts)) + return JSONResponse(data) + + +@app.get("/raw") +def get_raw(req: Request): + return PlainTextResponse(req.client.host)