]> git.mxchange.org Git - fba.git/blob - daemon.py
Continued:
[fba.git] / daemon.py
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3
4 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
5 # Copyright (C) 2023 Free Software Foundation
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published
9 # by the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16 #
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
19
20 import re
21
22 from datetime import datetime
23 from email.utils import format_datetime
24 from pathlib import Path
25
26 import fastapi
27 from fastapi import Request, HTTPException, Query
28 from fastapi.responses import JSONResponse
29 from fastapi.responses import PlainTextResponse
30 from fastapi.staticfiles import StaticFiles
31 from fastapi.templating import Jinja2Templates
32
33 import requests
34 import uvicorn
35
36 from fba import database
37 from fba import utils
38
39 from fba.helpers import config
40 from fba.helpers import json as json_helper
41 from fba.helpers import tidyup
42
43 from fba.models import blocks
44 from fba.models import instances
45
46 router = fastapi.FastAPI(docs_url=config.get("base_url") + "/docs", redoc_url=config.get("base_url") + "/redoc")
47 router.mount(
48     "/static",
49     StaticFiles(directory=Path(__file__).parent.absolute() / "static"),
50     name="static",
51 )
52
53 templates = Jinja2Templates(directory="templates")
54
55 @router.get(config.get("base_url") + "/api/info.json", response_class=JSONResponse)
56 def api_info():
57     database.cursor.execute("SELECT (SELECT COUNT(domain) FROM instances), (SELECT COUNT(domain) FROM instances WHERE software IN ('pleroma', 'mastodon', 'lemmy', 'friendica', 'misskey', 'peertube', 'takahe')), (SELECT COUNT(blocker) FROM blocks), (SELECT COUNT(domain) FROM instances WHERE last_error_details IS NOT NULL)")
58     row = database.cursor.fetchone()
59
60     return {
61         "known_instances"    : row[0],
62         "supported_instances": row[1],
63         "blocks_recorded"    : row[2],
64         "erroneous_instances": row[3],
65     }
66
67 @router.get(config.get("base_url") + "/api/scoreboard.json", response_class=JSONResponse)
68 def api_scoreboard(mode: str, amount: int):
69     if amount > config.get("api_limit"):
70         raise HTTPException(status_code=400, detail="Too many results")
71
72     if mode == "blocked":
73         database.cursor.execute("SELECT blocked, COUNT(blocked) AS score FROM blocks GROUP BY blocked ORDER BY score DESC LIMIT ?", [amount])
74     elif mode == "blocker":
75         database.cursor.execute("SELECT blocker, COUNT(blocker) AS score FROM blocks GROUP BY blocker ORDER BY score DESC LIMIT ?", [amount])
76     elif mode == "reference":
77         database.cursor.execute("SELECT origin, COUNT(domain) AS score FROM instances WHERE origin IS NOT NULL GROUP BY origin ORDER BY score DESC LIMIT ?", [amount])
78     elif mode == "software":
79         database.cursor.execute("SELECT software, COUNT(domain) AS score FROM instances WHERE software IS NOT NULL GROUP BY software ORDER BY score DESC, software ASC LIMIT ?", [amount])
80     elif mode == "command":
81         database.cursor.execute("SELECT command, COUNT(domain) AS score FROM instances WHERE command IS NOT NULL GROUP BY command ORDER BY score DESC, command ASC LIMIT ?", [amount])
82     elif mode == "error_code":
83         database.cursor.execute("SELECT last_status_code, COUNT(domain) AS score FROM instances WHERE last_status_code IS NOT NULL AND last_status_code != '200' GROUP BY last_status_code ORDER BY score DESC LIMIT ?", [amount])
84     elif mode == "detection_mode":
85         database.cursor.execute("SELECT detection_mode, COUNT(domain) AS cnt FROM instances GROUP BY detection_mode ORDER BY cnt DESC LIMIT ?", [amount])
86     elif mode == "avg_peers":
87         database.cursor.execute("SELECT software, AVG(total_peers) AS average FROM instances WHERE software IS NOT NULL GROUP BY software HAVING average > 0 ORDER BY average DESC LIMIT ?", [amount])
88     elif mode == "obfuscator":
89         database.cursor.execute("SELECT software, COUNT(domain) AS cnt FROM instances WHERE has_obfuscation = 1 GROUP BY software ORDER BY cnt DESC LIMIT ?", [amount])
90     elif mode == "obfuscation":
91         database.cursor.execute("SELECT has_obfuscation, COUNT(domain) AS cnt FROM instances WHERE software IN ('pleroma', 'mastodon', 'friendica') GROUP BY has_obfuscation ORDER BY cnt DESC LIMIT ?", [amount])
92     elif mode == "block_level":
93         database.cursor.execute("SELECT block_level, COUNT(rowid) AS cnt FROM blocks GROUP BY block_level ORDER BY cnt DESC LIMIT ?", [amount])
94     else:
95         raise HTTPException(status_code=400, detail="No filter specified")
96
97     scores = list()
98
99     for domain, score in database.cursor.fetchall():
100         scores.append({
101             "domain": domain,
102             "score" : round(score)
103         })
104
105     return scores
106
107 @router.get(config.get("base_url") + "/api/list.json", response_class=JSONResponse)
108 def api_list(request: Request, mode: str, value: str, amount: int):
109     if mode is None or value is None or amount is None:
110         raise HTTPException(status_code=500, detail="No filter specified")
111     elif amount > config.get("api_limit"):
112         raise HTTPException(status_code=500, detail=f"amount={amount} is to big")
113
114     domain = wildchar = punycode = reason = None
115
116     if mode in ("detection_mode", "software", "command"):
117         database.cursor.execute(
118             f"SELECT domain, origin, software, detection_mode, command, total_peers, total_blocks, first_seen, last_updated \
119 FROM instances \
120 WHERE {mode} = ? \
121 ORDER BY domain \
122 LIMIT ?", [value, amount]
123         )
124
125     domainlist = database.cursor.fetchall()
126
127     return domainlist
128
129 @router.get(config.get("base_url") + "/api/top.json", response_class=JSONResponse)
130 def api_index(request: Request, mode: str, value: str, amount: int):
131     if mode is None or value is None or amount is None:
132         raise HTTPException(status_code=500, detail="No filter specified")
133     elif amount > config.get("api_limit"):
134         raise HTTPException(status_code=500, detail=f"amount={amount} is to big")
135
136     domain = wildchar = punycode = reason = None
137
138     if mode == "block_level":
139         database.cursor.execute(
140             "SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks WHERE block_level = ? LIMIT ?", [value, amount]
141         )
142     elif mode in ["domain", "reverse"]:
143         domain = tidyup.domain(value)
144         if not utils.is_domain_wanted(domain):
145             raise HTTPException(status_code=500, detail=f"domain='{domain}' is not wanted")
146
147         wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
148         punycode = domain.encode("idna").decode("utf-8")
149     elif mode == "reason":
150         reason = re.sub("(%|_)", "", tidyup.reason(value))
151         if len(reason) < 3:
152             raise HTTPException(status_code=400, detail="Keyword is shorter than three characters")
153
154     if mode == "domain":
155         database.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen \
156 FROM blocks \
157 WHERE blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? \
158 ORDER BY block_level ASC, first_seen ASC \
159 LIMIT ?",
160             [
161                 domain,
162                 "*." + domain,
163                 wildchar,
164                 utils.get_hash(domain),
165                 punycode,
166                 "*." + punycode,
167                 amount
168             ]
169         )
170     elif mode == "reverse":
171         database.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen \
172 FROM blocks \
173 WHERE blocker = ? OR blocker = ? OR blocker = ? OR blocker = ? OR blocker = ? OR blocker = ? \
174 ORDER BY first_seen ASC \
175 LIMIT ?", [
176             domain,
177             "*." + domain,
178             wildchar,
179             utils.get_hash(domain),
180             punycode,
181             "*." + punycode,
182             amount
183         ])
184     elif mode == "reason":
185         database.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen \
186 FROM blocks \
187 WHERE reason LIKE ? AND reason != '' \
188 ORDER BY first_seen ASC \
189 LIMIT ?", [
190             "%" + reason + "%",
191             amount
192         ])
193
194     blocklist = database.cursor.fetchall()
195
196     result = {}
197     for blocker, blocked, block_level, reason, first_seen, last_seen in blocklist:
198         if reason is not None and reason != "":
199             reason = reason.replace(",", " ").replace("  ", " ")
200
201         entry = {
202             "blocker"   : blocker,
203             "blocked"   : blocked,
204             "reason"    : reason,
205             "first_seen": first_seen,
206             "last_seen" : last_seen
207         }
208
209         if block_level in result:
210             result[block_level].append(entry)
211         else:
212             result[block_level] = [entry]
213
214     return result
215
216 @router.get(config.get("base_url") + "/api/domain.json", response_class=JSONResponse)
217 def api_domain(domain: str):
218     if domain is None:
219         raise HTTPException(status_code=400, detail="Invalid request, parameter 'domain' missing")
220
221     # Tidy up domain name
222     domain = tidyup.domain(domain).encode("idna").decode("utf-8")
223
224     if not utils.is_domain_wanted(domain):
225         raise HTTPException(status_code=500, detail=f"domain='{domain}' is not wanted")
226
227     # Fetch domain data
228     database.cursor.execute("SELECT * FROM instances WHERE domain = ? LIMIT 1", [domain])
229     domain_data = database.cursor.fetchone()
230
231     if domain_data is None:
232         raise HTTPException(status_code=404, detail=f"domain='{domain}' not found")
233
234     return domain_data
235
236 @router.get(config.get("base_url") + "/api/mutual.json", response_class=JSONResponse)
237 def api_mutual(domains: list[str] = Query()):
238     """Return 200 if federation is open between the two, 4xx otherwise"""
239     database.cursor.execute(
240         "SELECT block_level FROM blocks " \
241         "WHERE ((blocker = :a OR blocker = :b) AND (blocked = :b OR blocked = :a OR blocked = :aw OR blocked = :bw)) " \
242         "AND block_level = 'reject' " \
243         "LIMIT 1",
244         {
245             "a" : domains[0],
246             "b" : domains[1],
247             "aw": "*." + domains[0],
248             "bw": "*." + domains[1],
249         },
250     )
251
252     if database.cursor.fetchone() is not None:
253         # Blocks found
254         return JSONResponse(status_code=418, content={})
255
256     # No known blocks
257     return JSONResponse(status_code=200, content={})
258
259 @router.get(config.get("base_url") + "/scoreboard")
260 def scoreboard(request: Request, mode: str, amount: int):
261     response = None
262
263     if mode == "blocker" and amount > 0:
264         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=blocker&amount={amount}")
265     elif mode == "blocked" and amount > 0:
266         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=blocked&amount={amount}")
267     elif mode == "reference" and amount > 0:
268         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=reference&amount={amount}")
269     elif mode == "software" and amount > 0:
270         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=software&amount={amount}")
271     elif mode == "command" and amount > 0:
272         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=command&amount={amount}")
273     elif mode == "error_code" and amount > 0:
274         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=error_code&amount={amount}")
275     elif mode == "detection_mode" and amount > 0:
276         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=detection_mode&amount={amount}")
277     elif mode == "avg_peers" and amount > 0:
278         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=avg_peers&amount={amount}")
279     elif mode == "obfuscator" and amount > 0:
280         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=obfuscator&amount={amount}")
281     elif mode == "obfuscation" and amount > 0:
282         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=obfuscation&amount={amount}")
283     elif mode == "block_level" and amount > 0:
284         response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/scoreboard.json?mode=block_level&amount={amount}")
285     else:
286         raise HTTPException(status_code=400, detail="No filter specified")
287
288     if response is None:
289         raise HTTPException(status_code=500, detail="Could not determine scores")
290     elif not response.ok:
291         raise HTTPException(status_code=response.status_code, detail=response.text)
292
293     return templates.TemplateResponse("views/scoreboard.html", {
294         "base_url"  : config.get("base_url"),
295         "slogan"    : config.get("slogan"),
296         "theme"     : config.get("theme"),
297         "request"   : request,
298         "scoreboard": True,
299         "mode"      : mode,
300         "amount"    : amount,
301         "scores"    : json_helper.from_response(response)
302     })
303
304 @router.get(config.get("base_url") + "/")
305 def index(request: Request):
306     # Get info
307     response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/info.json")
308
309     if not response.ok:
310         raise HTTPException(status_code=response.status_code, detail=response.text)
311
312     return templates.TemplateResponse("views/index.html", {
313         "request": request,
314         "theme"  : config.get("theme"),
315         "info"   : response.json(),
316         "slogan" : config.get("slogan"),
317     })
318
319 @router.get(config.get("base_url") + "/list")
320 def list_domains(request: Request, mode: str, value: str, amount: int = config.get("api_limit")):
321     if mode == "detection_mode" and not instances.valid(value, "detection_mode"):
322         raise HTTPException(status_code=500, detail="Invalid detection mode provided")
323
324     response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/list.json?mode={mode}&value={value}&amount={amount}")
325
326     domainlist = list()
327     if response is not None and response.ok:
328         domainlist = response.json()
329         format = config.get("timestamp_format")
330         for row in domainlist:
331             row["first_seen"]   = datetime.utcfromtimestamp(row["first_seen"]).strftime(format)
332             row["last_updated"] = datetime.utcfromtimestamp(row["last_updated"]).strftime(format) if isinstance(row["last_updated"], float) else None
333
334     return templates.TemplateResponse("views/list.html", {
335         "request"   : request,
336         "mode"      : mode if response is not None else None,
337         "value"     : value if response is not None else None,
338         "amount"    : amount if response is not None else None,
339         "found"     : len(domainlist),
340         "domainlist": domainlist,
341         "slogan"    : config.get("slogan"),
342         "theme"     : config.get("theme"),
343     })
344
345 @router.get(config.get("base_url") + "/top")
346 def top(request: Request, mode: str, value: str, amount: int = config.get("api_limit")):
347     if mode == "block_level" and not blocks.valid(value, "block_level"):
348         raise HTTPException(status_code=500, detail="Invalid block level provided")
349     elif mode in ["domain", "reverse"] and not utils.is_domain_wanted(value):
350         raise HTTPException(status_code=500, detail="Invalid or blocked domain specified")
351
352     response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/top.json?mode={mode}&value={value}&amount={amount}")
353
354     found = 0
355     blocklist = list()
356     if response.ok and response.status_code == 200 and len(response.text) > 0:
357         blocklist = response.json()
358
359         format = config.get("timestamp_format")
360         for block_level in blocklist:
361             for row in blocklist[block_level]:
362                 row["first_seen"] = datetime.utcfromtimestamp(row["first_seen"]).strftime(format)
363                 row["last_seen"]  = datetime.utcfromtimestamp(row["last_seen"]).strftime(format) if isinstance(row["last_seen"], float) else None
364                 found = found + 1
365
366     return templates.TemplateResponse("views/top.html", {
367         "request"  : request,
368         "mode"     : mode if response is not None else None,
369         "value"    : value if response is not None else None,
370         "amount"   : amount if response is not None else None,
371         "found"    : found,
372         "blocklist": blocklist,
373         "slogan"   : config.get("slogan"),
374         "theme"    : config.get("theme"),
375     })
376
377 @router.get(config.get("base_url") + "/infos")
378 def infos(request: Request, domain: str):
379     if domain is None:
380         raise HTTPException(status_code=400, detail="Invalid request, parameter 'domain' missing")
381
382     # Tidy up domain name
383     domain = tidyup.domain(domain).encode("idna").decode("utf-8")
384
385     if not utils.is_domain_wanted(domain):
386         raise HTTPException(status_code=500, detail=f"domain='{domain}' is not wanted")
387
388     response = requests.get(f"http://{config.get('host')}:{config.get('port')}{config.get('base_url')}/api/domain.json?domain={domain}")
389
390     if not response.ok or response.status_code >= 300 or response.text.strip() == "":
391         raise HTTPException(status_code=response.status_code, detail=response.reason)
392
393     domain_data = response.json()
394
395     # Format timestamps
396     format = config.get("timestamp_format")
397     instance = dict()
398     for key in domain_data.keys():
399         if key in ["last_nodeinfo", "last_blocked", "first_seen", "last_updated", "last_instance_fetch"] and isinstance(domain_data[key], float):
400             # Timestamps
401             instance[key] = datetime.utcfromtimestamp(domain_data[key]).strftime(format)
402         else:
403             # Generic
404             instance[key] = domain_data[key]
405
406     return templates.TemplateResponse("views/infos.html", {
407         "request" : request,
408         "domain"  : domain,
409         "instance": instance,
410         "theme"   : config.get("theme"),
411         "slogan"  : config.get("slogan"),
412     })
413
414 @router.get(config.get("base_url") + "/rss")
415 def rss(request: Request, domain: str = None):
416     if domain is not None:
417         domain = tidyup.domain(domain).encode("idna").decode("utf-8")
418
419         wildchar = "*." + ".".join(domain.split(".")[-domain.count("."):])
420         punycode = domain.encode("idna").decode("utf-8")
421
422         database.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks WHERE blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? OR blocked = ? ORDER BY first_seen DESC LIMIT ?", [
423             domain,
424             "*." + domain, wildchar,
425             utils.get_hash(domain),
426             punycode,
427             "*." + punycode,
428             config.get("rss_limit")
429         ])
430     else:
431         database.cursor.execute("SELECT blocker, blocked, block_level, reason, first_seen, last_seen FROM blocks ORDER BY first_seen DESC LIMIT ?", [config.get("rss_limit")])
432
433     result = database.cursor.fetchall()
434     blocklist = []
435
436     for row in result:
437         blocklist.append({
438             "blocker"    : row[0],
439             "blocked"    : row[1],
440             "block_level": row[2],
441             "reason"     : "Provided reason: '" + row[3] + "'" if row[3] is not None and row[3] != "" else "No reason provided.",
442             "first_seen" : format_datetime(datetime.fromtimestamp(row[4])),
443             "last_seen"  : format_datetime(datetime.fromtimestamp(row[5])),
444         })
445
446     return templates.TemplateResponse("views/rss.xml", {
447         "request"  : request,
448         "timestamp": format_datetime(datetime.now()),
449         "domain"   : domain,
450         "hostname" : config.get("hostname"),
451         "blocks"   : blocklist
452     }, headers={
453         "Content-Type": "routerlication/rss+xml"
454     })
455
456 @router.get(config.get("base_url") + "/robots.txt", response_class=PlainTextResponse)
457 def robots(request: Request):
458     return templates.TemplateResponse("views/robots.txt", {
459         "request" : request,
460         "base_url": config.get("base_url")
461     })
462
463 if __name__ == "__main__":
464     uvicorn.run("daemon:router", host=config.get("host"), port=config.get("port"), log_level=config.get("log_level"))