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