]> git.mxchange.org Git - fba.git/blob - fba.py
Continued:
[fba.git] / fba.py
1 import bs4
2 import hashlib
3 import re
4 import reqto
5 import json
6 import sqlite3
7 import sys
8 import time
9 import validators
10
11 with open("config.json") as f:
12     config = json.loads(f.read())
13
14 # Don't check these, known trolls/flooders/testing/developing
15 blacklist = [
16     # Floods network with fake nodes as "research" project
17     "activitypub-troll.cf",
18     # Similar troll
19     "gab.best",
20     # Similar troll
21     "4chan.icu",
22     # Flooder (?)
23     "social.shrimpcam.pw",
24     # Flooder (?)
25     "mastotroll.netz.org",
26     # Testing/developing installations
27     "ngrok.io",
28 ]
29
30 # Array with pending errors needed to be written to database
31 pending_errors = {
32 }
33
34 # "rel" identifiers (no real URLs)
35 nodeinfo_identifier = [
36     "http://nodeinfo.diaspora.software/ns/schema/2.1",
37     "http://nodeinfo.diaspora.software/ns/schema/2.0",
38     "http://nodeinfo.diaspora.software/ns/schema/1.1",
39     "http://nodeinfo.diaspora.software/ns/schema/1.0",
40 ]
41
42 # HTTP headers for requests
43 headers = {
44     "user-agent": config["useragent"],
45 }
46
47 # Found info from node, such as nodeinfo URL, detection mode that needs to be
48 # written to database. Both arrays must be filled at the same time or else
49 # update_nodeinfos() will fail
50 nodeinfos = {
51     # Detection mode: AUTO_DISCOVERY or STATIC_CHECKS
52     "detection_mode": {},
53     # Found nodeinfo URL
54     "nodeinfo_url": {},
55     # Where to fetch peers (other instances)
56     "get_peers_url": {},
57 }
58
59 language_mapping = {
60     # English -> English
61     "Silenced instances"            : "Silenced servers",
62     "Suspended instances"           : "Suspended servers",
63     "Limited instances"             : "Limited servers",
64     # Mappuing German -> English
65     "Gesperrte Server"              : "Suspended servers",
66     "Gefilterte Medien"             : "Filtered media",
67     "Stummgeschaltete Server"       : "Silenced servers",
68     # Japanese -> English
69     "停止済みのサーバー"            : "Suspended servers",
70     "制限中のサーバー"              : "Limited servers",
71     "メディアを拒否しているサーバー": "Filtered media",
72     "サイレンス済みのサーバー"      : "Silenced servers",
73     # ??? -> English
74     "שרתים מושעים"                  : "Suspended servers",
75     "מדיה מסוננת"                   : "Filtered media",
76     "שרתים מוגבלים"                 : "Silenced servers",
77     # French -> English
78     "Serveurs suspendus"            : "Suspended servers",
79     "Médias filtrés"                : "Filtered media",
80     "Serveurs limités"              : "Limited servers",
81     "Serveurs modérés"              : "Limited servers",
82 }
83
84 # URL for fetching peers
85 get_peers_url = "/api/v1/instance/peers"
86
87 # Connect to database
88 connection = sqlite3.connect("blocks.db")
89 cursor = connection.cursor()
90
91 def is_blacklisted(domain: str) -> bool:
92     blacklisted = False
93     for peer in blacklist:
94         if peer in domain:
95             blacklisted = True
96
97     return blacklisted
98
99 def remove_pending_error(domain: str):
100     try:
101         # Prevent updating any pending errors, nodeinfo was found
102         del pending_errors[domain]
103
104     except:
105         pass
106
107 def get_hash(domain: str) -> str:
108     return hashlib.sha256(domain.encode("utf-8")).hexdigest()
109
110 def update_last_blocked(domain: str):
111     # NOISY-DEBUG: print("DEBUG: Updating last_blocked for domain", domain)
112     try:
113         cursor.execute("UPDATE instances SET last_blocked = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
114             time.time(),
115             time.time(),
116             domain
117         ])
118
119         if cursor.rowcount == 0:
120             print("WARNING: Did not update any rows:", domain)
121
122     except BaseException as e:
123         print("ERROR: failed SQL query:", domain, e)
124         sys.exit(255)
125
126     # NOISY-DEBUG: print("DEBUG: EXIT!")
127
128 def update_nodeinfos(domain: str):
129     # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
130     sql_string = ''
131     fields = list()
132     for key in nodeinfos:
133         # NOISY-DEBUG: print("DEBUG: key:", key)
134         if domain in nodeinfos[key]:
135            # NOISY-DEBUG: print(f"DEBUG: Adding '{nodeinfos[key][domain]}' for key='{key}' ...")
136            fields.append(nodeinfos[key][domain])
137            sql_string += f" {key} = ?,"
138
139     fields.append(domain)
140     # NOISY-DEBUG: print(f"DEBUG: sql_string='{sql_string}',fields()={len(fields)}")
141
142     sql = "UPDATE instances SET" + sql_string + " last_status_code = NULL, last_error_details = NULL WHERE domain = ? LIMIT 1"
143     # NOISY-DEBUG: print("DEBUG: sql:", sql)
144
145     try:
146         # NOISY-DEBUG: print("DEBUG: Executing SQL:", sql)
147         cursor.execute(sql, fields)
148         # NOISY-DEBUG: print(f"DEBUG: Success! (rowcount={cursor.rowcount })")
149
150         if cursor.rowcount == 0:
151             print("WARNING: Did not update any rows:", domain)
152
153     except BaseException as e:
154         print(f"ERROR: failed SQL query: domain='{domain}',sql='{sql}',exception='{e}'")
155         sys.exit(255)
156
157     # NOISY-DEBUG: print("DEBUG: Deleting nodeinfos for domain:", domain)
158     for key in nodeinfos:
159         try:
160             # NOISY-DEBUG: print("DEBUG: Deleting key:", key)
161             del nodeinfos[key][domain]
162         except:
163             pass
164
165     # NOISY-DEBUG: print("DEBUG: EXIT!")
166
167 def update_last_error(domain: str, res: any):
168     # NOISY-DEBUG: print("DEBUG: domain,res[]:", domain, type(res))
169     try:
170         # NOISY-DEBUG: print("DEBUG: BEFORE res[]:", type(res))
171         if isinstance(res, BaseException) or isinstance(res, json.JSONDecodeError):
172             res = str(res)
173
174         # NOISY-DEBUG: print("DEBUG: AFTER res[]:", type(res))
175         if type(res) is str:
176             # NOISY-DEBUG: print(f"DEBUG: Setting last_error_details='{res}'");
177             cursor.execute("UPDATE instances SET last_status_code = 999, last_error_details = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
178                 res,
179                 time.time(),
180                 domain
181             ])
182         else:
183             # NOISY-DEBUG: print(f"DEBUG: Setting last_error_details='{res.reason}'");
184             cursor.execute("UPDATE instances SET last_status_code = ?, last_error_details = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
185                 res.status_code,
186                 res.reason,
187                 time.time(),
188                 domain
189             ])
190
191         if cursor.rowcount == 0:
192             # NOISY-DEBUG: print("DEBUG: Did not update any rows:", domain)
193             pending_errors[domain] = res
194
195     except BaseException as e:
196         print("ERROR: failed SQL query:", domain, e)
197         sys.exit(255)
198
199     # NOISY-DEBUG: print("DEBUG: EXIT!")
200
201 def update_last_nodeinfo(domain: str):
202     # NOISY-DEBUG: print("DEBUG: Updating last_nodeinfo for domain:", domain)
203     try:
204         cursor.execute("UPDATE instances SET last_nodeinfo = ?, last_updated = ? WHERE domain = ? LIMIT 1", [
205             time.time(),
206             time.time(),
207             domain
208         ])
209
210         if cursor.rowcount == 0:
211             print("WARNING: Did not update any rows:", domain)
212
213     except BaseException as e:
214         print("ERROR: failed SQL query:", domain, e)
215         sys.exit(255)
216
217     connection.commit()
218     # NOISY-DEBUG: print("DEBUG: EXIT!")
219
220 def get_peers(domain: str, software: str) -> list:
221     # NOISY-DEBUG: print("DEBUG: Getting peers for domain:", domain, software)
222     peers = list()
223
224     if software == "lemmy":
225         # NOISY-DEBUG: print(f"DEBUG: domain='{domain}' is Lemmy, fetching JSON ...")
226         try:
227             res = reqto.get(f"https://{domain}/api/v3/site", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
228
229             # NOISY-DEBUG: print(f"DEBUG: res.ok={res.ok},res.json[]={type(res.json())}")
230             if res.ok and isinstance(res.json(), dict):
231                 # NOISY-DEBUG: print("DEBUG: Success, res.json():", len(res.json()))
232                 json = res.json()
233
234                 if "federated_instances" in json and "linked" in json["federated_instances"]:
235                     # NOISY-DEBUG: print("DEBUG: Found federated_instances", domain)
236                     peers = json["federated_instances"]["linked"] + json["federated_instances"]["allowed"] + json["federated_instances"]["blocked"]
237
238         except BaseException as e:
239             print("WARNING: Exception during fetching JSON:", domain, e)
240
241         update_last_nodeinfo(domain)
242
243         # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
244         return peers
245     elif software == "peertube":
246         # NOISY-DEBUG: print(f"DEBUG: domain='{domain}' is a PeerTube, fetching JSON ...")
247
248         start = 0
249         for mode in ["followers", "following"]:
250             # NOISY-DEBUG: print(f"DEBUG: domain='{domain}',mode='{mode}'")
251             while True:
252                 try:
253                     res = reqto.get(f"https://{domain}/api/v1/server/{mode}?start={start}&count=100", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
254
255                     # NOISY-DEBUG: print(f"DEBUG: res.ok={res.ok},res.json[]={type(res.json())}")
256                     if res.ok and isinstance(res.json(), dict):
257                         # NOISY-DEBUG: print("DEBUG: Success, res.json():", len(res.json()))
258                         json = res.json()
259
260                         if "data" in json:
261                             # NOISY-DEBUG: print(f"DEBUG: Found {len(json['data'])} record(s).")
262                             for record in json["data"]:
263                                 # NOISY-DEBUG: print(f"DEBUG: record()={len(record)}")
264                                 if mode in record and "host" in record[mode]:
265                                     # NOISY-DEBUG: print(f"DEBUG: Found host={record[mode]['host']}, adding ...")
266                                     peers.append(record[mode]["host"])
267                                 else:
268                                     print(f"WARNING: record from '{domain}' has no '{mode}' or 'host' record: {record}")
269
270                             if len(json["data"]) < 100:
271                                 # NOISY-DEBUG: print("DEBUG: Reached end of JSON response:", domain)
272                                 break
273
274                         # Continue with next row
275                         start = start + 100
276
277                 except BaseException as e:
278                     print("WARNING: Exception during fetching JSON:", domain, e)
279
280             update_last_nodeinfo(domain)
281
282             # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
283             return peers
284
285     # NOISY-DEBUG: print(f"DEBUG: Fetching '{get_peers_url}' from '{domain}' ...")
286     try:
287         res = reqto.get(f"https://{domain}{get_peers_url}", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
288
289         # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
290         if not res.ok or res.status_code >= 400:
291             res = reqto.get(f"https://{domain}/api/v3/site", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
292
293             if "federated_instances" in json and "linked" in json["federated_instances"]:
294                 # NOISY-DEBUG: print("DEBUG: Found federated_instances", domain)
295                 peers = json["federated_instances"]["linked"] + json["federated_instances"]["allowed"] + json["federated_instances"]["blocked"]
296             else:
297                 print("WARNING: Could not reach any JSON API:", domain)
298                 update_last_error(domain, res)
299         else:
300             # NOISY-DEBUG: print("DEBUG:Querying API was successful:", domain, len(res.json()))
301             peers = res.json()
302             nodeinfos["get_peers_url"][domain] = get_peers_url
303
304     except BaseException as e:
305         print("WARNING: Some error during get():", domain, e)
306         update_last_error(domain, e)
307
308     update_last_nodeinfo(domain)
309
310     # NOISY-DEBUG: print("DEBUG: Returning peers[]:", type(peers))
311     return peers
312
313 def post_json_api(domain: str, path: str, data: str) -> list:
314     # NOISY-DEBUG: print("DEBUG: Sending POST to domain,path,data:", domain, path, data)
315     json = {}
316     try:
317         res = reqto.post(f"https://{domain}{path}", data=data, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
318
319         # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
320         if not res.ok or res.status_code >= 400:
321             print("WARNING: Cannot query JSON API:", domain, path, data, res.status_code)
322             update_last_error(domain, res)
323             raise
324
325         update_last_nodeinfo(domain)
326         json = res.json()
327     except BaseException as e:
328         print("WARNING: Some error during post():", domain, path, data, e)
329
330     # NOISY-DEBUG: print("DEBUG: Returning json():", len(json))
331     return json
332
333 def fetch_nodeinfo(domain: str) -> list:
334     # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from domain:", domain)
335
336     nodeinfo = fetch_wellknown_nodeinfo(domain)
337     # NOISY-DEBUG: print("DEBUG:nodeinfo:", len(nodeinfo))
338
339     if len(nodeinfo) > 0:
340         # NOISY-DEBUG: print("DEBUG: Returning auto-discovered nodeinfo:", len(nodeinfo))
341         return nodeinfo
342
343     requests = [
344        f"https://{domain}/nodeinfo/2.1.json",
345        f"https://{domain}/nodeinfo/2.1",
346        f"https://{domain}/nodeinfo/2.0.json",
347        f"https://{domain}/nodeinfo/2.0",
348        f"https://{domain}/nodeinfo/1.0",
349        f"https://{domain}/api/v1/instance"
350     ]
351
352     json = {}
353     for request in requests:
354         try:
355             # NOISY-DEBUG: print("DEBUG: Fetching request:", request)
356             res = reqto.get(request, headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
357
358             # NOISY-DEBUG: print("DEBUG: res.ok,res.json[]:", res.ok, type(res.json()))
359             if res.ok and isinstance(res.json(), dict):
360                 # NOISY-DEBUG: print("DEBUG: Success:", request)
361                 json = res.json()
362                 nodeinfos["detection_mode"][domain] = "STATIC_CHECK"
363                 nodeinfos["nodeinfo_url"][domain] = request
364                 break
365             elif not res.ok or res.status_code >= 400:
366                 print("WARNING: Failed fetching nodeinfo from domain:", domain)
367                 update_last_error(domain, res)
368                 continue
369
370         except BaseException as e:
371             # NOISY-DEBUG: print("DEBUG: Cannot fetch API request:", request)
372             update_last_error(domain, e)
373             pass
374
375     # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
376     return json
377
378 def fetch_wellknown_nodeinfo(domain: str) -> list:
379     # NOISY-DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
380     json = {}
381
382     try:
383         res = reqto.get(f"https://{domain}/.well-known/nodeinfo", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
384         # NOISY-DEBUG: print("DEBUG: domain,res.ok,res.json[]:", domain, res.ok, type(res.json()))
385         if res.ok and isinstance(res.json(), dict):
386             nodeinfo = res.json()
387             # NOISY-DEBUG: print("DEBUG: Found entries:", len(nodeinfo), domain)
388             if "links" in nodeinfo:
389                 # NOISY-DEBUG: print("DEBUG: Found links in nodeinfo():", len(nodeinfo["links"]))
390                 for link in nodeinfo["links"]:
391                     # NOISY-DEBUG: print("DEBUG: rel,href:", link["rel"], link["href"])
392                     if link["rel"] in nodeinfo_identifier:
393                         # NOISY-DEBUG: print("DEBUG: Fetching nodeinfo from:", link["href"])
394                         res = reqto.get(link["href"])
395
396                         # NOISY-DEBUG: print("DEBUG: href,res.ok,res.status_code:", link["href"], res.ok, res.status_code)
397                         if res.ok and isinstance(res.json(), dict):
398                             # NOISY-DEBUG: print("DEBUG: Found JSON nodeinfo():", len(res.json()))
399                             json = res.json()
400                             nodeinfos["detection_mode"][domain] = "AUTO_DISCOVERY"
401                             nodeinfos["nodeinfo_url"][domain] = link["href"]
402                             break
403                     else:
404                         print("WARNING: Unknown 'rel' value:", domain, link["rel"])
405             else:
406                 print("WARNING: nodeinfo does not contain 'links':", domain)
407
408     except BaseException as e:
409         print("WARNING: Failed fetching .well-known info:", domain)
410         update_last_error(domain, e)
411         pass
412
413     # NOISY-DEBUG: print("DEBUG: Returning json[]:", type(json))
414     return json
415
416 def fetch_generator_from_path(domain: str, path: str = "/") -> str:
417     # NOISY-DEBUG: print(f"DEBUG: domain='{domain}',path='{path}' - CALLED!")
418     software = None
419
420     try:
421         # NOISY-DEBUG: print(f"DEBUG: Fetching '{path}' from '{domain}' ...")
422         res = reqto.get(f"https://{domain}{path}", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
423
424         # NOISY-DEBUG: print("DEBUG: domain,res.ok,res.status_code:", domain, res.ok, res.status_code)
425         if res.ok and res.status_code < 300 and len(res.text) > 0:
426             # NOISY-DEBUG: print("DEBUG: Search for <meta name='generator'>:", domain)
427             doc = bs4.BeautifulSoup(res.text, "html.parser")
428
429             # NOISY-DEBUG: print("DEBUG: doc[]:", type(doc))
430             tag = doc.find("meta", {"name": "generator"})
431
432             # NOISY-DEBUG: print(f"DEBUG: tag[{type(tag)}: {tag}")
433             if isinstance(tag, bs4.element.Tag):
434                 # NOISY-DEBUG: print("DEBUG: Found generator meta tag: ", domain)
435                 software = tidyup(tag.get("content"))
436                 # NOISY-DEBUG: print(f"DEBUG: software='{software}'")
437                 remove_pending_error(domain)
438
439     except BaseException as e:
440         print(f"WARNING: Cannot fetch / from '{domain}':", e)
441         update_last_error(domain, e)
442         pass
443
444     # NOISY-DEBUG: print(f"DEBUG: software='{software}' - EXIT!")
445     return software
446
447 def determine_software(domain: str) -> str:
448     # NOISY-DEBUG: print("DEBUG: Determining software for domain:", domain)
449     software = None
450
451     # NOISY-DEBUG: print(f"DEBUG: Fetching nodeinfo from '{domain}' ...")
452     json = fetch_nodeinfo(domain)
453
454     # NOISY-DEBUG: print("DEBUG: json[]:", type(json))
455     if not isinstance(json, dict) or len(json) == 0:
456         # NOISY-DEBUG: print("DEBUG: Could not determine software type:", domain)
457         return fetch_generator_from_path(domain)
458
459     # NOISY-DEBUG: print("DEBUG: json():", len(json), json)
460     if "status" in json and json["status"] == "error" and "message" in json:
461         print("WARNING: JSON response is an error:", json["message"])
462         update_last_error(domain, json["message"])
463         return fetch_generator_from_path(domain)
464     elif "software" not in json or "name" not in json["software"]:
465         # NOISY-DEBUG: print(f"DEBUG: JSON response from {domain} does not include [software][name], fetching / ...")
466         software = fetch_generator_from_path(domain)
467
468         # NOISY-DEBUG: print(f"DEBUG: Generator for domain='{domain}' is: {software}, EXIT!")
469         return software
470
471     software = tidyup(json["software"]["name"])
472
473     # NOISY-DEBUG: print("DEBUG: sofware after tidyup():", software)
474     if software in ["akkoma", "rebased"]:
475         # NOISY-DEBUG: print("DEBUG: Setting pleroma:", domain, software)
476         software = "pleroma"
477     elif software in ["hometown", "ecko"]:
478         # NOISY-DEBUG: print("DEBUG: Setting mastodon:", domain, software)
479         software = "mastodon"
480     elif software in ["calckey", "groundpolis", "foundkey", "cherrypick", "meisskey"]:
481         # NOISY-DEBUG: print("DEBUG: Setting misskey:", domain, software)
482         software = "misskey"
483     elif software.find("/") > 0:
484         print("WARNING: Spliting of slash:", software)
485         software = software.split("/")[-1];
486     elif software.find("|") > 0:
487         print("WARNING: Spliting of pipe:", software)
488         software = tidyup(software.split("|")[0]);
489
490     # NOISY-DEBUG: print(f"DEBUG: software[]={type(software)}")
491     if software == "":
492         print("WARNING: tidyup() left no software name behind:", domain)
493         software = None
494
495     # NOISY-DEBUG: print(f"DEBUG: software[]={type(software)}")
496     if str(software) == "":
497         # NOISY-DEBUG: print(f"DEBUG: software for '{domain}' was not detected, trying generator ...")
498         software = fetch_generator_from_path(domain)
499
500     # NOISY-DEBUG: print("DEBUG: Returning domain,software:", domain, software)
501     return software
502
503 def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
504     # NOISY-DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
505     try:
506         cursor.execute(
507             "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
508             (
509                 reason,
510                 time.time(),
511                 blocker,
512                 blocked,
513                 block_level
514             ),
515         )
516
517         # NOISY-DEBUG: print(f"DEBUG: cursor.rowcount={cursor.rowcount}")
518         if cursor.rowcount == 0:
519             print("WARNING: Did not update any rows:", domain)
520
521     except BaseException as e:
522         print("ERROR: failed SQL query:", reason, blocker, blocked, block_level, e)
523         sys.exit(255)
524
525     # NOISY-DEBUG: print("DEBUG: EXIT!")
526
527 def update_last_seen(blocker: str, blocked: str, block_level: str):
528     # NOISY-DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
529     try:
530         cursor.execute(
531             "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
532             (
533                 time.time(),
534                 blocker,
535                 blocked,
536                 block_level
537             )
538         )
539
540         if cursor.rowcount == 0:
541             print("WARNING: Did not update any rows:", domain)
542
543     except BaseException as e:
544         print("ERROR: failed SQL query:", last_seen, blocker, blocked, block_level, e)
545         sys.exit(255)
546
547     # NOISY-DEBUG: print("DEBUG: EXIT!")
548
549 def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
550     # NOISY-DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
551     if not validators.domain(blocker):
552         print("WARNING: Bad blocker:", blocker)
553         raise
554     elif not validators.domain(blocked):
555         print("WARNING: Bad blocked:", blocked)
556         raise
557
558     print("INFO: New block:", blocker, blocked, reason, block_level, first_added, last_seen)
559     try:
560         cursor.execute(
561             "INSERT INTO blocks (blocker, blocked, reason, block_level, first_added, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
562              (
563                  blocker,
564                  blocked,
565                  reason,
566                  block_level,
567                  time.time(),
568                  time.time()
569              ),
570         )
571
572     except BaseException as e:
573         print("ERROR: failed SQL query:", blocker, blocked, reason, block_level, first_added, last_seen, e)
574         sys.exit(255)
575
576     # NOISY-DEBUG: print("DEBUG: EXIT!")
577
578 def add_instance(domain: str, origin: str, originator: str):
579     # NOISY-DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
580     if not validators.domain(domain):
581         print("WARNING: Bad domain name:", domain)
582         raise
583     elif origin is not None and not validators.domain(origin):
584         print("WARNING: Bad origin name:", origin)
585         raise
586
587     software = determine_software(domain)
588     # NOISY-DEBUG: print("DEBUG: Determined software:", software)
589
590     print(f"INFO: Adding new instance {domain} (origin: {origin})")
591     try:
592         cursor.execute(
593             "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
594             (
595                domain,
596                origin,
597                originator,
598                get_hash(domain),
599                software,
600                time.time()
601             ),
602         )
603
604         if domain in nodeinfos["nodeinfo_url"]:
605             # NOISY-DEBUG # NOISY-DEBUG: print("DEBUG: domain has pending nodeinfo being updated:", domain)
606             update_nodeinfos(domain)
607             remove_pending_error(domain)
608         elif domain in pending_errors:
609             # NOISY-DEBUG: print("DEBUG: domain has pending error being updated:", domain)
610             update_last_error(domain, pending_errors[domain])
611             remove_pending_error(domain)
612
613     except BaseException as e:
614         print("ERROR: failed SQL query:", domain, e)
615         sys.exit(255)
616     else:
617         # NOISY-DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
618         update_last_nodeinfo(domain)
619
620     # NOISY-DEBUG: print("DEBUG: EXIT!")
621
622 def send_bot_post(instance: str, blocks: dict):
623     message = instance + " has blocked the following instances:\n\n"
624     truncated = False
625
626     if len(blocks) > 20:
627         truncated = True
628         blocks = blocks[0 : 19]
629
630     for block in blocks:
631         if block["reason"] == None or block["reason"] == '':
632             message = message + block["blocked"] + " with unspecified reason\n"
633         else:
634             if len(block["reason"]) > 420:
635                 block["reason"] = block["reason"][0:419] + "[…]"
636
637             message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
638
639     if truncated:
640         message = message + "(the list has been truncated to the first 20 entries)"
641
642     botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
643
644     req = reqto.post(
645         f"{config['bot_instance']}/api/v1/statuses",
646         data={
647             "status"      : message,
648             "visibility"  : config['bot_visibility'],
649             "content_type": "text/plain"
650         },
651         headers=botheaders,
652         timeout=10
653     ).json()
654
655     return True
656
657 def get_mastodon_blocks(domain: str) -> dict:
658     # NOISY-DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
659     blocks = {
660         "Suspended servers": [],
661         "Filtered media"   : [],
662         "Limited servers"  : [],
663         "Silenced servers" : [],
664     }
665
666     try:
667         doc = bs4.BeautifulSoup(
668             reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
669             "html.parser",
670         )
671     except BaseException as e:
672         print("ERROR: Cannot fetch from domain:", domain, e)
673         update_last_error(domain, e)
674         return {}
675
676     for header in doc.find_all("h3"):
677         header_text = tidyup(header.text)
678
679         if header_text in language_mapping:
680             # NOISY-DEBUG: print(f"DEBUG: header_text='{header_text}'")
681             header_text = language_mapping[header_text]
682
683         if header_text in blocks or header_text.lower() in blocks:
684             # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
685             for line in header.find_all_next("table")[0].find_all("tr")[1:]:
686                 blocks[header_text].append(
687                     {
688                         "domain": tidyup(line.find("span").text),
689                         "hash"  : tidyup(line.find("span")["title"][9:]),
690                         "reason": tidyup(line.find_all("td")[1].text),
691                     }
692                 )
693
694     # NOISY-DEBUG: print("DEBUG: Returning blocks for domain:", domain)
695     return {
696         "reject"        : blocks["Suspended servers"],
697         "media_removal" : blocks["Filtered media"],
698         "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
699     }
700
701 def get_friendica_blocks(domain: str) -> dict:
702     # NOISY-DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
703     blocks = []
704
705     try:
706         doc = bs4.BeautifulSoup(
707             reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
708             "html.parser",
709         )
710     except BaseException as e:
711         print("WARNING: Failed to fetch /friendica from domain:", domain, e)
712         update_last_error(domain, e)
713         return {}
714
715     blocklist = doc.find(id="about_blocklist")
716
717     # Prevents exceptions:
718     if blocklist is None:
719         # NOISY-DEBUG: print("DEBUG:Instance has no block list:", domain)
720         return {}
721
722     for line in blocklist.find("table").find_all("tr")[1:]:
723         blocks.append({
724             "domain": tidyup(line.find_all("td")[0].text),
725             "reason": tidyup(line.find_all("td")[1].text)
726         })
727
728     # NOISY-DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
729     return {
730         "reject": blocks
731     }
732
733 def get_misskey_blocks(domain: str) -> dict:
734     # NOISY-DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
735     blocks = {
736         "suspended": [],
737         "blocked"  : []
738     }
739
740     counter = 0
741     step = 99
742     while True:
743         # iterating through all "suspended" (follow-only in its terminology)
744         # instances page-by-page, since that troonware doesn't support
745         # sending them all at once
746         try:
747             if counter == 0:
748                 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
749                 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
750                     "sort"     : "+caughtAt",
751                     "host"     : None,
752                     "suspended": True,
753                     "limit"    : step
754                 }))
755             else:
756                 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
757                 doc = post_json_api(domain, "/api/federation/instances/", json.dumps({
758                     "sort"     : "+caughtAt",
759                     "host"     : None,
760                     "suspended": True,
761                     "limit"    : step,
762                     "offset"   : counter-1
763                 }))
764
765             # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
766             if len(doc) == 0:
767                 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
768                 break
769
770             for instance in doc:
771                 # just in case
772                 if instance["isSuspended"]:
773                     blocks["suspended"].append(
774                         {
775                             "domain": tidyup(instance["host"]),
776                             # no reason field, nothing
777                             "reason": ""
778                         }
779                     )
780
781             if len(doc) < step:
782                 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
783                 break
784
785             # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
786             counter = counter + step
787
788         except BaseException as e:
789             print("WARNING: Caught error, exiting loop:", domain, e)
790             update_last_error(domain, e)
791             counter = 0
792             break
793
794     while True:
795         # same shit, different asshole ("blocked" aka full suspend)
796         try:
797             if counter == 0:
798                 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
799                 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
800                     "sort"   : "+caughtAt",
801                     "host"   : None,
802                     "blocked": True,
803                     "limit"  : step
804                 }))
805             else:
806                 # NOISY-DEBUG: print("DEBUG: Sending JSON API request to domain,step,counter:", domain, step, counter)
807                 doc = post_json_api(domain,"/api/federation/instances", json.dumps({
808                     "sort"   : "+caughtAt",
809                     "host"   : None,
810                     "blocked": True,
811                     "limit"  : step,
812                     "offset" : counter-1
813                 }))
814
815             # NOISY-DEBUG: print("DEBUG: doc():", len(doc))
816             if len(doc) == 0:
817                 # NOISY-DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
818                 break
819
820             for instance in doc:
821                 if instance["isBlocked"]:
822                     blocks["blocked"].append({
823                         "domain": tidyup(instance["host"]),
824                         "reason": ""
825                     })
826
827             if len(doc) < step:
828                 # NOISY-DEBUG: print("DEBUG: End of request:", len(doc), step)
829                 break
830
831             # NOISY-DEBUG: print("DEBUG: Raising counter by step:", step)
832             counter = counter + step
833
834         except BaseException as e:
835             print("ERROR: Exception during POST:", domain, e)
836             update_last_error(domain, e)
837             counter = 0
838             break
839
840     # NOISY-DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
841     return {
842         "reject"        : blocks["blocked"],
843         "followers_only": blocks["suspended"]
844     }
845
846 def tidyup(string: str) -> str:
847     # some retards put their blocks in variable case
848     string = string.lower().strip()
849
850     # other retards put the port
851     string = re.sub("\:\d+$", "", string)
852
853     # bigger retards put the schema in their blocklist, sometimes even without slashes
854     string = re.sub("^https?\:(\/*)", "", string)
855
856     # and trailing slash
857     string = re.sub("\/$", "", string)
858
859     # and the @
860     string = re.sub("^\@", "", string)
861
862     # the biggest retards of them all try to block individual users
863     string = re.sub("(.+)\@", "", string)
864
865     return string