]> git.mxchange.org Git - fba.git/blob - fba.py
Continued:
[fba.git] / fba.py
1 from bs4 import BeautifulSoup
2 from hashlib import sha256
3
4 import reqto
5 import re
6 import sqlite3
7 import json
8 import sys
9 import time
10
11 with open("config.json") as f:
12     config = json.loads(f.read())
13
14 blacklist = [
15     "activitypub-troll.cf",
16     "gab.best",
17     "4chan.icu",
18     "social.shrimpcam.pw",
19     "mastotroll.netz.org",
20     "ngrok.io",
21 ]
22
23 headers = {
24     "user-agent": config["useragent"]
25 }
26
27 connection = sqlite3.connect("blocks.db")
28 cursor = connection.cursor()
29
30 def is_blacklisted(domain: str) -> bool:
31     blacklisted = False
32     for peer in blacklist:
33         if peer in domain:
34             blacklisted = True
35
36     return blacklisted
37
38 def get_hash(domain: str) -> str:
39     return sha256(domain.encode("utf-8")).hexdigest()
40
41 def update_last_blocked(domain: str):
42     # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
43     try:
44         cursor.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ?", [
45             time.time(),
46             time.time(),
47             domain
48         ])
49
50     except:
51         print("ERROR: failed SQL query:", domain)
52         sys.exit(255)
53
54 def update_last_error(domain: str, res: any):
55     # NOISY-DEBUG: print("DEBUG: domain,res.status_code:", domain, res.status_code, res.reason)
56     try:
57         cursor.execute("UPDATE instances SET last_status_code = ?, last_error_details = ?, last_updated = ? WHERE domain = ?", [
58             res.status_code,
59             res.reason,
60             time.time(),
61             domain
62         ])
63
64     except:
65         print("ERROR: failed SQL query:", domain)
66         sys.exit(255)
67
68 def update_last_nodeinfo(domain: str):
69     # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
70     try:
71         cursor.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ?", [
72             time.time(),
73             time.time(),
74             domain
75         ])
76
77     except:
78         print("ERROR: failed SQL query:", domain)
79         sys.exit(255)
80
81     connection.commit()
82
83 def get_peers(domain: str) -> list:
84     # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain)
85     peers = None
86
87     try:
88         res = reqto.get(f"https://{domain}/api/v1/instance/peers", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
89
90         if not res.ok or res.status_code >= 400:
91             print("WARNING: Cannot fetch peers:", domain)
92             update_last_error(domain, res)
93         else:
94             # NOISY-DEBUG: print("DEBUG: Querying API was successful:", domain, len(res.json()))
95             peers = res.json()
96
97     except:
98         print("WARNING: Some error during get():", domain)
99
100     update_last_nodeinfo(domain)
101
102     # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
103     return peers
104
105 def post_json_api(domain: str, path: str, data: str) -> list:
106     # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
107     json = {}
108     try:
109         res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
110
111         if not res.ok or res.status_code >= 400:
112             print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
113             update_last_error(domain, res)
114             raise
115
116         update_last_nodeinfo(domain)
117         json = res.json()
118     except:
119         print("WARNING: Some error during post():", domain, path, data)
120
121     # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
122     return json
123
124 def fetch_nodeinfo(domain: str) -> list:
125     # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
126
127     nodeinfo = fetch_wellknown_nodeinfo(domain)
128     # NOISY-DEBUG: print("DEBUG: nodeinfo:", len(nodeinfo))
129
130     if len(nodeinfo) > 0:
131         # NOISY-DEBUG: print("DEBUG: Returning auto-discovered nodeinfo:", len(nodeinfo))
132         return nodeinfo
133
134     requests = [
135        f"https://{domain}/nodeinfo/2.1.json",
136        f"https://{domain}/nodeinfo/2.1",
137        f"https://{domain}/nodeinfo/2.0.json",
138        f"https://{domain}/nodeinfo/2.0",
139        f"https://{domain}/nodeinfo/1.0",
140        f"https://{domain}/api/v1/instance"
141     ]
142
143     json = {}
144     for request in requests:
145         try:
146             # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
147             res = reqto.get(request, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
148
149             # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
150             if res.ok and res.json() is not None:
151                 # NOISY-DEBUG: print("DEBUG: Success:", request)
152                 json = res.json()
153                 break
154             elif not res.ok or res.status_code >= 400:
155                 # NOISY-DEBUG: print("DEBUG: Failed fetching nodeinfo from domain:", domain)
156                 update_last_error(domain, res)
157                 continue
158
159         except:
160             # NOISY-DEBUG: print("DEBUG: Cannot fetch API request:", request)
161             pass
162
163     # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
164     if json is None or len(json) == 0:
165         print("WARNING: Failed fetching nodeinfo from domain:", domain)
166
167     # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
168     return json
169
170 def fetch_wellknown_nodeinfo(domain: str) -> list:
171     # NOISY-DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
172     json = {}
173
174     try:
175         res = reqto.get(f"https://{domain}/.well-known/nodeinfo", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
176         # NOISY-DEBUG: print("DEBUG: domain,res.ok:", domain, res.ok)
177         if res.ok and res.json() is not None:
178             nodeinfo = res.json()
179             # NOISY-DEBUG: print("DEBUG: Found entries:", len(nodeinfo), domain)
180             if "links" in nodeinfo:
181                 # NOISY-DEBUG: print("DEBUG: Found links in nodeinfo():", len(nodeinfo["links"]))
182                 for link in nodeinfo["links"]:
183                     # NOISY-DEBUG: print("DEBUG: rel,href:", link["rel"], link["href"])
184                     if link["rel"] in ["http://nodeinfo.diaspora.software/ns/schema/2.0", "http://nodeinfo.diaspora.software/ns/schema/2.1"]:
185                         # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from:", link["href"])
186                         res = reqto.get(link["href"])
187                         # NOISY-DEBUG: print("DEBUG: href,res.ok:", link["href"], res.ok)
188                         if res.ok and res.json() is not None:
189                             # NOISY-DEBUG: print("DEBUG: Found JSON nodeinfo():", len(res.json()))
190                             json = res.json()
191                             break
192                     else:
193                         print("WARNING: Unknown 'rel' value:", domain, link["rel"])
194             else:
195                 print("WARNING: nodeinfo does not contain 'links':", domain)
196
197     except:
198         print("WARNING: Failed fetching .well-known info:", domain)
199         pass
200
201     # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
202     return json
203
204 def determine_software(domain: str) -> str:
205     # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
206     software = None
207
208     json = fetch_nodeinfo(domain)
209     # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
210
211     if json is None or len(json) == 0:
212         # NOISY-DEBUG: print("DEBUG: Could not determine software type:", domain)
213         return None
214
215     # NOISY-DEBUG: print("DEBUG: json():", len(json), json)
216     if "software" not in json or "name" not in json["software"]:
217         print("WARNING: JSON response does not include [software][name], guessing ...")
218         found = 0
219         for element in {"uri", "title", "description", "email", "version", "urls", "stats", "thumbnail", "languages", "contact_account"}:
220             if element in json:
221                 found = found + 1
222
223         # NOISY-DEBUG: print("DEBUG: Found elements:", found)
224         if found == len(json):
225             # NOISY-DEBUG: print("DEBUG: Maybe is Mastodon:", domain)
226             return "mastodon"
227
228         print("WARNING: Cannot guess software type:", domain, found, len(json))
229         return None
230
231     software = tidyup(json["software"]["name"])
232
233     # NOISY-DEBUG: print("DEBUG: tidyup software:", software)
234     if software in ["akkoma", "rebased"]:
235         # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, software)
236         software = "pleroma"
237     elif software in ["hometown", "ecko"]:
238         # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, software)
239         software = "mastodon"
240     elif software in ["calckey", "groundpolis", "foundkey", "cherrypick"]:
241         # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, software)
242         software = "misskey"
243     elif software.find("/") > 0:
244         print("WARNING: Spliting of path:", software)
245         software = software.split("/")[-1];
246     elif software.find("|") > 0:
247         print("WARNING: Spliting of path:", software)
248         software = software.split("|")[0].strip();
249
250     if software == "":
251         print("WARNING: tidyup() left no software name behind:", domain)
252         software = None
253
254     # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
255     return software
256
257 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
258     # NOISY: # NOISY-DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
259     try:
260         cursor.execute(
261             "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
262             (
263                 reason,
264                 time.time(),
265                 blocker,
266                 blocked,
267                 block_level
268             ),
269         )
270
271     except:
272         print("ERROR: failed SQL query:", reason, blocker, blocked, block_level)
273         sys.exit(255)
274
275 def update_last_seen(blocker: str, blocked: str, block_level: str):
276     # NOISY: # NOISY-DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
277     try:
278         cursor.execute(
279             "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
280             (
281                 time.time(),
282                 blocker,
283                 blocked,
284                 block_level
285             )
286         )
287
288     except:
289         print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level)
290         sys.exit(255)
291
292 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
293     # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
294     if blocker.find("@") > 0:
295         print("WARNING: Bad blocker:", blocker)
296         raise
297     elif blocked.find("@") > 0:
298         print("WARNING: Bad blocked:", blocked)
299         raise
300
301     print("INFO: New block:", blocker, blocked, reason, block_level, first_added, last_seen)
302     try:
303         cursor.execute(
304             "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
305              (
306                  blocker,
307                  blocked,
308                  reason,
309                  block_level,
310                  time.time(),
311                  time.time()
312              ),
313         )
314
315     except:
316         print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen)
317         sys.exit(255)
318
319 def add_instance(domain: str, origin: str, originator: str):
320     # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
321     if domain.find("@") > 0:
322         print("WARNING: Bad domain name:", domain)
323         raise
324     elif origin is not None and origin.find("@") > 0:
325         print("WARNING: Bad origin name:", origin)
326         raise
327
328     software = determine_software(domain)
329     # NOISY-DEBUG: print("DEBUG: Determined software:", software)
330
331     print(f"INFO: Adding new instance {domain} (origin: {origin})")
332     try:
333         cursor.execute(
334             "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
335             (
336                domain,
337                origin,
338                originator,
339                get_hash(domain),
340                software,
341                time.time()
342             ),
343         )
344
345     except:
346         print("ERROR: failed SQL query:", domain)
347         sys.exit(255)
348     else:
349         # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
350         update_last_nodeinfo(domain)
351
352 def send_bot_post(instance: str, blocks: dict):
353     message = instance + " has blocked the following instances:\n\n"
354     truncated = False
355
356     if len(blocks) > 20:
357         truncated = True
358         blocks = blocks[0 : 19]
359
360     for block in blocks:
361         if block["reason"] == None or block["reason"] == '':
362             message = message + block["blocked"] + " with unspecified reason\n"
363         else:
364             if len(block["reason"]) > 420:
365                 block["reason"] = block["reason"][0:419] + "[…]"
366
367             message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
368
369     if truncated:
370         message = message + "(the list has been truncated to the first 20 entries)"
371
372     botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
373
374     req = reqto.post(f"{config['bot_instance']}/api/v1/statuses",
375         data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
376         headers=botheaders, timeout=10).json()
377
378     return True
379
380 def get_mastodon_blocks(domain: str) -> dict:
381     # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
382     blocks = {
383         "Suspended servers": [],
384         "Filtered media"   : [],
385         "Limited servers"  : [],
386         "Silenced servers" : [],
387     }
388
389     translations = {
390         "Silenced instances": "Silenced servers",
391         "Suspended instances": "Suspended servers",
392         "Gesperrte Server": "Suspended servers",
393         "Gefilterte Medien": "Filtered media",
394         "Stummgeschaltete Server": "Silenced servers",
395         "停止済みのサーバー": "Suspended servers",
396         "メディアを拒否しているサーバー": "Filtered media",
397         "サイレンス済みのサーバー": "Silenced servers",
398         "שרתים מושעים": "Suspended servers",
399         "מדיה מסוננת": "Filtered media",
400         "שרתים מוגבלים": "Silenced servers",
401         "Serveurs suspendus": "Suspended servers",
402         "Médias filtrés": "Filtered media",
403         "Serveurs limités": "Silenced servers",
404     }
405
406     try:
407         doc = BeautifulSoup(
408             reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
409             "html.parser",
410         )
411     except:
412         print("ERROR: Cannot fetch from domain:", domain)
413         return {}
414
415     for header in doc.find_all("h3"):
416         header_text = header.text
417
418         if header_text in translations:
419             header_text = translations[header_text]
420
421         if header_text in blocks:
422             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
423             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
424                 blocks[header_text].append(
425                     {
426                         "domain": tidyup(line.find("span").text),
427                         "hash"  : tidyup(line.find("span")["title"][9:]),
428                         "reason": tidyup(line.find_all("td")[1].text),
429                     }
430                 )
431
432     # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
433     return {
434         "reject"        : blocks["Suspended servers"],
435         "media_removal" : blocks["Filtered media"],
436         "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
437     }
438
439 def get_friendica_blocks(domain: str) -> dict:
440     # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
441     blocks = []
442
443     try:
444         doc = BeautifulSoup(
445             reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
446             "html.parser",
447         )
448     except:
449         print("WARNING: Failed to fetch /friendica from domain:", domain)
450         return {}
451
452     blocklist = doc.find(id="about_blocklist")
453
454     # Prevents exceptions:
455     if blocklist is None:
456         # NOISY-DEBUG: print("DEBUG: Instance has no block list:", domain)
457         return {}
458
459     for line in blocklist.find("table").find_all("tr")[1:]:
460         blocks.append({
461             "domain": tidyup(line.find_all("td")[0].text),
462             "reason": tidyup(line.find_all("td")[1].text)
463         })
464
465     # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
466     return {
467         "reject": blocks
468     }
469
470 def get_misskey_blocks(domain: str) -> dict:
471     # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
472     blocks = {
473         "suspended": [],
474         "blocked": []
475     }
476
477     try:
478         counter = 0
479         step = 99
480         while True:
481             # iterating through all "suspended" (follow-only in its terminology)
482             # instances page-by-page, since that troonware doesn't support
483             # sending them all at once
484             try:
485                 if counter == 0:
486                     # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
487                     doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
488                         "sort"     : "+caughtAt",
489                         "host"     : None,
490                         "suspended": True,
491                         "limit"    : step
492                     }))
493                 else:
494                     # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
495                     doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
496                         "sort"     : "+caughtAt",
497                         "host"     : None,
498                         "suspended": True,
499                         "limit"    : step,
500                         "offset"   : counter-1
501                     }))
502
503                 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
504                 if len(doc) == 0:
505                     # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
506                     break
507
508                 for instance in doc:
509                     # just in case
510                     if instance["isSuspended"]:
511                         blocks["suspended"].append(
512                             {
513                                 "domain": tidyup(instance["host"]),
514                                 # no reason field, nothing
515                                 "reason": ""
516                             }
517                         )
518
519                 if len(doc) < step:
520                     # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
521                     break
522
523                 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
524                 counter = counter + step
525
526             except:
527                 print("WARNING: Caught error, exiting loop:", domain)
528                 counter = 0
529                 break
530
531         while True:
532             # same shit, different asshole ("blocked" aka full suspend)
533             try:
534                 if counter == 0:
535                     # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
536                     doc = post_json_api(domain,"/api/federation/instances", json.dumps({
537                         "sort"   : "+caughtAt",
538                         "host"   : None,
539                         "blocked": True,
540                         "limit"  : step
541                     }))
542                 else:
543                     # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
544                     doc = post_json_api(domain,"/api/federation/instances", json.dumps({
545                         "sort"   : "+caughtAt",
546                         "host"   : None,
547                         "blocked": True,
548                         "limit"  : step,
549                         "offset" : counter-1
550                     }))
551
552                 # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
553                 if len(doc) == 0:
554                     # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
555                     break
556
557                 for instance in doc:
558                     if instance["isBlocked"]:
559                         blocks["blocked"].append({
560                             "domain": tidyup(instance["host"]),
561                             "reason": ""
562                         })
563
564                 if len(doc) < step:
565                     # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
566                     break
567
568                 # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
569                 counter = counter + step
570
571             except:
572                 counter = 0
573                 break
574
575         # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
576         return {
577             "reject"        : blocks["blocked"],
578             "followers_only": blocks["suspended"]
579         }
580
581     except:
582         print("WARNING: API request failed for domain:", domain)
583         return {}
584
585 def tidyup(string: str) -> str:
586     # some retards put their blocks in variable case
587     string = string.lower().strip()
588
589     # other retards put the port
590     string = re.sub("\:\d+$", "", string)
591
592     # bigger retards put the schema in their blocklist, sometimes even without slashes
593     string = re.sub("^https?\:(\/*)", "", string)
594
595     # and trailing slash
596     string = re.sub("\/$", "", string)
597
598     # and the @
599     string = re.sub("^\@", "", string)
600
601     # the biggest retards of them all try to block individual users
602     string = re.sub("(.+)\@", "", string)
603
604     return string