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