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