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