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