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