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