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