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