- if len(nodeinfo) > 0:
- # DEBUG: print("DEBUG: Returning auto-discovered nodeinfo:", len(nodeinfo))
- return nodeinfo
-
- requests = [
- f"https://{domain}/nodeinfo/2.1.json",
- f"https://{domain}/nodeinfo/2.1",
- f"https://{domain}/nodeinfo/2.0.json",
- f"https://{domain}/nodeinfo/2.0",
- f"https://{domain}/nodeinfo/1.0",
- f"https://{domain}/api/v1/instance"
- ]
-
- data = {}
- for request in requests:
- try:
- # DEBUG: print("DEBUG: Fetching request:", request)
- res = reqto.get(request, headers=api_headers, timeout=(config["connection_timeout"], config["read_timeout"]))
-
- # DEBUG: print(f"DEBUG: res.ok={res.ok},res.status_code={res.status_code}")
- if res.ok and isinstance(res.json(), dict):
- # DEBUG: print("DEBUG: Success:", request)
- data = res.json()
- nodeinfos["detection_mode"][domain] = "STATIC_CHECK"
- nodeinfos["nodeinfo_url"][domain] = request
- break
- elif not res.ok or res.status_code >= 400:
- print("WARNING: Failed fetching nodeinfo from domain:", domain)
- update_last_error(domain, res)
- continue
-
- except BaseException as e:
- # DEBUG: print("DEBUG: Cannot fetch API request:", request)
- update_last_error(domain, e)
- pass
-
- # DEBUG: print("DEBUG: Returning data[]:", type(data))
- return data
-
-def fetch_wellknown_nodeinfo(domain: str) -> list:
- # DEBUG: print("DEBUG: Fetching .well-known info for domain:", domain)
- data = {}
-
- try:
- res = reqto.get(f"https://{domain}/.well-known/nodeinfo", headers=api_headers, timeout=(config["connection_timeout"], config["read_timeout"]))
- # DEBUG: print("DEBUG: domain,res.ok,res.json[]:", domain, res.ok, type(res.json()))
- if res.ok and isinstance(res.json(), dict):
- nodeinfo = res.json()
- # DEBUG: print("DEBUG: Found entries:", len(nodeinfo), domain)
- if "links" in nodeinfo:
- # DEBUG: print("DEBUG: Found links in nodeinfo():", len(nodeinfo["links"]))
- for link in nodeinfo["links"]:
- # DEBUG: print("DEBUG: rel,href:", link["rel"], link["href"])
- if link["rel"] in nodeinfo_identifier:
- # DEBUG: print("DEBUG: Fetching nodeinfo from:", link["href"])
- res = reqto.get(link["href"])
-
- # DEBUG: print("DEBUG: href,res.ok,res.status_code:", link["href"], res.ok, res.status_code)
- if res.ok and isinstance(res.json(), dict):
- # DEBUG: print("DEBUG: Found JSON nodeinfo():", len(res.json()))
- data = res.json()
- nodeinfos["detection_mode"][domain] = "AUTO_DISCOVERY"
- nodeinfos["nodeinfo_url"][domain] = link["href"]
- break
- else:
- print("WARNING: Unknown 'rel' value:", domain, link["rel"])
- else:
- print("WARNING: nodeinfo does not contain 'links':", domain)
-
- except BaseException as e:
- print("WARNING: Failed fetching .well-known info:", domain)
- update_last_error(domain, e)
- pass
-
- # DEBUG: print("DEBUG: Returning data[]:", type(data))
- return data
-
-def fetch_generator_from_path(domain: str, path: str = "/") -> str:
- # DEBUG: print(f"DEBUG: domain='{domain}',path='{path}' - CALLED!")
- software = None
-
- try:
- # DEBUG: print(f"DEBUG: Fetching path='{path}' from '{domain}' ...")
- res = reqto.get(f"https://{domain}{path}", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"]))
-
- # DEBUG: print("DEBUG: domain,res.ok,res.status_code,res.text[]:", domain, res.ok, res.status_code, type(res.text))
- if res.ok and res.status_code < 300 and len(res.text) > 0:
- # DEBUG: print("DEBUG: Search for <meta name='generator'>:", domain)
- doc = bs4.BeautifulSoup(res.text, "html.parser")
-
- # DEBUG: print("DEBUG: doc[]:", type(doc))
- tag = doc.find("meta", {"name": "generator"})
-
- # DEBUG: print(f"DEBUG: tag[{type(tag)}: {tag}")
- if isinstance(tag, bs4.element.Tag):
- # DEBUG: print("DEBUG: Found generator meta tag: ", domain)
- software = tidyup(tag.get("content"))
- print(f"INFO: domain='{domain}' is generated by '{software}'")
- nodeinfos["detection_mode"][domain] = "GENERATOR"
- remove_pending_error(domain)
-
- except BaseException as e:
- # DEBUG: print(f"DEBUG: Cannot fetch / from '{domain}':", e)
- update_last_error(domain, e)
- pass
-
- # DEBUG: print(f"DEBUG: software[]={type(software)}")
- if type(software) is str and software == "":
- # DEBUG: print(f"DEBUG: Corrected empty string to None for software of domain='{domain}'")
- software = None
- elif type(software) is str and ("." in software or " " in software):
- # DEBUG: print(f"DEBUG: software='{software}' may contain a version number, domain='{domain}', removing it ...")
- software = remove_version(software)
-
- # DEBUG: print(f"DEBUG: software[]={type(software)}")
- if type(software) is str and "powered by" in software:
- # DEBUG: print(f"DEBUG: software='{software}' has 'powered by' in it")
- software = remove_version(strip_powered_by(software))
- elif type(software) is str and " by " in software:
- # DEBUG: print(f"DEBUG: software='{software}' has ' by ' in it")
- software = strip_until(software, " by ")
- elif type(software) is str and " see " in software:
- # DEBUG: print(f"DEBUG: software='{software}' has ' see ' in it")
- software = strip_until(software, " see ")
-
- # DEBUG: print(f"DEBUG: software='{software}' - EXIT!")
- return software
-
-def determine_software(domain: str) -> str:
- # DEBUG: print("DEBUG: Determining software for domain:", domain)
- software = None
-
- # DEBUG: print(f"DEBUG: Fetching nodeinfo from '{domain}' ...")
- data = fetch_nodeinfo(domain)
-
- # DEBUG: print("DEBUG: data[]:", type(data))
- if not isinstance(data, dict) or len(data) == 0:
- # DEBUG: print("DEBUG: Could not determine software type:", domain)
- return fetch_generator_from_path(domain)
-
- # DEBUG: print("DEBUG: data():", len(data), data)
- if "status" in data and data["status"] == "error" and "message" in data:
- print("WARNING: JSON response is an error:", data["message"])
- update_last_error(domain, data["message"])
- return fetch_generator_from_path(domain)
- elif "software" not in data or "name" not in data["software"]:
- # DEBUG: print(f"DEBUG: JSON response from {domain} does not include [software][name], fetching / ...")
- software = fetch_generator_from_path(domain)
-
- # DEBUG: print(f"DEBUG: Generator for domain='{domain}' is: {software}, EXIT!")
- return software
-
- software = tidyup(data["software"]["name"])
-
- # DEBUG: print("DEBUG: sofware after tidyup():", software)
- if software in ["akkoma", "rebased"]:
- # DEBUG: print("DEBUG: Setting pleroma:", domain, software)
- software = "pleroma"
- elif software in ["hometown", "ecko"]:
- # DEBUG: print("DEBUG: Setting mastodon:", domain, software)
- software = "mastodon"
- elif software in ["calckey", "groundpolis", "foundkey", "cherrypick", "meisskey"]:
- # DEBUG: print("DEBUG: Setting misskey:", domain, software)
- software = "misskey"
- elif software.find("/") > 0:
- print("WARNING: Spliting of slash:", software)
- software = software.split("/")[-1];
- elif software.find("|") > 0:
- print("WARNING: Spliting of pipe:", software)
- software = tidyup(software.split("|")[0]);
- elif "powered by" in software:
- # DEBUG: print(f"DEBUG: software='{software}' has 'powered by' in it")
- software = strip_powered_by(software)
- elif type(software) is str and " by " in software:
- # DEBUG: print(f"DEBUG: software='{software}' has ' by ' in it")
- software = strip_until(software, " by ")
- elif type(software) is str and " see " in software:
- # DEBUG: print(f"DEBUG: software='{software}' has ' see ' in it")
- software = strip_until(software, " see ")
-
- # DEBUG: print(f"DEBUG: software[]={type(software)}")
- if software == "":
- print("WARNING: tidyup() left no software name behind:", domain)
- software = None
-
- # DEBUG: print(f"DEBUG: software[]={type(software)}")
- if str(software) == "":
- # DEBUG: print(f"DEBUG: software for '{domain}' was not detected, trying generator ...")
- software = fetch_generator_from_path(domain)
- elif len(str(software)) > 0 and ("." in software or " " in software):
- # DEBUG: print(f"DEBUG: software='{software}' may contain a version number, domain='{domain}', removing it ...")
- software = remove_version(software)
-
- # DEBUG: print(f"DEBUG: software[]={type(software)}")
- if type(software) is str and "powered by" in software:
- # DEBUG: print(f"DEBUG: software='{software}' has 'powered by' in it")
- software = remove_version(strip_powered_by(software))
-
- # DEBUG: print("DEBUG: Returning domain,software:", domain, software)
- return software
-
-def update_block_reason(reason: str, blocker: str, blocked: str, block_level: str):
- # DEBUG: print("DEBUG: Updating block reason:", reason, blocker, blocked, block_level)
- try:
- cursor.execute(
- "UPDATE blocks SET reason = ?, last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ? AND reason = ''",
- (
- reason,
- time.time(),
- blocker,
- blocked,
- block_level
- ),
- )
-
- # DEBUG: print(f"DEBUG: cursor.rowcount={cursor.rowcount}")
- if cursor.rowcount == 0:
- print("WARNING: Did not update any rows:", domain)
-
- except BaseException as e:
- print(f"ERROR: failed SQL query: reason='{reason}',blocker='{blocker}',blocked='{blocked}',block_level='{block_level}',sql='{sql}',exception:'{e}'")
- sys.exit(255)
-
- # DEBUG: print("DEBUG: EXIT!")
-
-def update_last_seen(blocker: str, blocked: str, block_level: str):
- # DEBUG: print("DEBUG: Updating last_seen for:", blocker, blocked, block_level)
- try:
- cursor.execute(
- "UPDATE blocks SET last_seen = ? WHERE blocker = ? AND blocked = ? AND block_level = ?",
- (
- time.time(),
- blocker,
- blocked,
- block_level
- )
- )
-
- if cursor.rowcount == 0:
- print("WARNING: Did not update any rows:", domain)
-
- except BaseException as e:
- print(f"ERROR: failed SQL query: last_seen='{last_seen}',blocker='{blocker}',blocked='{blocked}',block_level='{block_level}',exception:'{e}'")
- sys.exit(255)
-
- # DEBUG: print("DEBUG: EXIT!")
-
-def block_instance(blocker: str, blocked: str, reason: str, block_level: str):
- # DEBUG: print("DEBUG: blocker,blocked,reason,block_level:", blocker, blocked, reason, block_level)
- if not validators.domain(blocker.split("/")[0]):
- print("WARNING: Bad blocker:", blocker)
- raise
- elif not validators.domain(blocked.split("/")[0]):
- print("WARNING: Bad blocked:", blocked)
- raise
-
- print("INFO: New block:", blocker, blocked, reason, block_level, first_seen, last_seen)
- try:
- cursor.execute(
- "INSERT INTO blocks (blocker, blocked, reason, block_level, first_seen, last_seen) VALUES(?, ?, ?, ?, ?, ?)",
- (
- blocker,
- blocked,
- reason,
- block_level,
- time.time(),
- time.time()
- ),
- )
-
- except BaseException as e:
- print(f"ERROR: failed SQL query: blocker='{blocker}',blocked='{blocked}',reason='{reason}',block_level='{block_level}',first_seen='{first_seen}',last_seen='{last_seen}',exception:'{e}'")
- sys.exit(255)
-
- # DEBUG: print("DEBUG: EXIT!")
-
-def is_instance_registered(domain: str) -> bool:
- # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
- # Default is not registered
- registered = False
-
- try:
- cursor.execute(
- "SELECT rowid FROM instances WHERE domain = ? LIMIT 1", [domain]
- )
-
- # Check condition
- registered = cursor.fetchone() != None
- except BaseException as e:
- print(f"ERROR: failed SQL query: last_seen='{last_seen}'blocker='{blocker}',blocked='{blocked}',block_level='{block_level}',first_seen='{first_seen}',last_seen='{last_seen}',exception:'{e}'")
- sys.exit(255)
-
- # DEBUG: print(f"DEBUG: registered='{registered}' - EXIT!")
- return registered
-
-def add_instance(domain: str, origin: str, originator: str):
- # DEBUG: print("DEBUG: domain,origin:", domain, origin, originator)
- if not validators.domain(domain.split("/")[0]):
- print("WARNING: Bad domain name:", domain)
- raise
- elif origin is not None and not validators.domain(origin.split("/")[0]):
- print("WARNING: Bad origin name:", origin)
- raise
-
- software = determine_software(domain)
- # DEBUG: print("DEBUG: Determined software:", software)
-
- print(f"INFO: Adding instance {domain} (origin: {origin})")
- try:
- cursor.execute(
- "INSERT INTO instances (domain, origin, originator, hash, software, first_seen) VALUES (?, ?, ?, ?, ?, ?)",
- (
- domain,
- origin,
- originator,
- get_hash(domain),
- software,
- time.time()
- ),
- )
-
- for key in nodeinfos:
- # DEBUG: print(f"DEBUG: key='{key}',domain='{domain}',nodeinfos[key]={nodeinfos[key]}")
- if domain in nodeinfos[key]:
- # DEBUG: print(f"DEBUG: domain='{domain}' has pending nodeinfo being updated ...")
- update_nodeinfos(domain)
- remove_pending_error(domain)
- break
-
- if domain in pending_errors:
- # DEBUG: print("DEBUG: domain has pending error being updated:", domain)
- update_last_error(domain, pending_errors[domain])
- remove_pending_error(domain)
-
- except BaseException as e:
- print(f"ERROR: failed SQL query: domain='{domain}',exception:'{e}'")
- sys.exit(255)
- else:
- # DEBUG: print("DEBUG: Updating nodeinfo for domain:", domain)
- update_last_nodeinfo(domain)
-
- # DEBUG: print("DEBUG: EXIT!")
-
-def send_bot_post(instance: str, blocks: dict):
- message = instance + " has blocked the following instances:\n\n"
- truncated = False
-
- if len(blocks) > 20:
- truncated = True
- blocks = blocks[0 : 19]
-
- for block in blocks:
- if block["reason"] == None or block["reason"] == '':
- message = message + block["blocked"] + " with unspecified reason\n"
- else:
- if len(block["reason"]) > 420:
- block["reason"] = block["reason"][0:419] + "[…]"
-
- message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
-
- if truncated:
- message = message + "(the list has been truncated to the first 20 entries)"
-
- botheaders = {**api_headers, **{"Authorization": "Bearer " + config["bot_token"]}}
-
- req = reqto.post(
- f"{config['bot_instance']}/api/v1/statuses",
- data={
- "status" : message,
- "visibility" : config['bot_visibility'],
- "content_type": "text/plain"
- },
- headers=botheaders,
- timeout=10
- ).json()
-
- return True
-
-def get_mastodon_blocks(domain: str) -> dict:
- # DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
- blocks = {
- "Suspended servers": [],
- "Filtered media" : [],
- "Limited servers" : [],
- "Silenced servers" : [],
- }
-
- try:
- doc = bs4.BeautifulSoup(
- reqto.get(f"https://{domain}/about/more", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
- "html.parser",
- )
- except BaseException as e:
- print("ERROR: Cannot fetch from domain:", domain, e)
- update_last_error(domain, e)
- return {}
-
- for header in doc.find_all("h3"):
- header_text = tidyup(header.text)
-
- if header_text in language_mapping:
- # DEBUG: print(f"DEBUG: header_text='{header_text}'")
- header_text = language_mapping[header_text]
-
- if header_text in blocks or header_text.lower() in blocks:
- # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
- for line in header.find_all_next("table")[0].find_all("tr")[1:]:
- blocks[header_text].append(
- {
- "domain": tidyup(line.find("span").text),
- "hash" : tidyup(line.find("span")["title"][9:]),
- "reason": tidyup(line.find_all("td")[1].text),
- }
- )
-
- # DEBUG: print("DEBUG: Returning blocks for domain:", domain)
- return {
- "reject" : blocks["Suspended servers"],
- "media_removal" : blocks["Filtered media"],
- "followers_only": blocks["Limited servers"] + blocks["Silenced servers"],
- }
-
-def get_friendica_blocks(domain: str) -> dict:
- # DEBUG: print("DEBUG: Fetching friendica blocks from domain:", domain)
- blocks = []
-
- try:
- doc = bs4.BeautifulSoup(
- reqto.get(f"https://{domain}/friendica", headers=headers, timeout=(config["connection_timeout"], config["read_timeout"])).text,
- "html.parser",
- )
- except BaseException as e:
- print("WARNING: Failed to fetch /friendica from domain:", domain, e)
- update_last_error(domain, e)
- return {}
-
- blocklist = doc.find(id="about_blocklist")
-
- # Prevents exceptions:
- if blocklist is None:
- # DEBUG: print("DEBUG:Instance has no block list:", domain)
- return {}
-
- for line in blocklist.find("table").find_all("tr")[1:]:
- # DEBUG: print(f"DEBUG: line='{line}'")
- blocks.append({
- "domain": tidyup(line.find_all("td")[0].text),
- "reason": tidyup(line.find_all("td")[1].text)
- })
-
- # DEBUG: print("DEBUG: Returning blocks() for domain:", domain, len(blocks))
- return {
- "reject": blocks
- }
-
-def get_misskey_blocks(domain: str) -> dict:
- # DEBUG: print("DEBUG: Fetching misskey blocks from domain:", domain)
- blocks = {
- "suspended": [],
- "blocked" : []
- }
-
- offset = 0
- step = config["misskey_offset"]
- while True:
- # iterating through all "suspended" (follow-only in its terminology)
- # instances page-by-page, since that troonware doesn't support
- # sending them all at once
- try:
- print(f"DEBUG: Fetching offset='{offset}' from '{domain}' ...")
- if offset == 0:
- # DEBUG: print("DEBUG: Sending JSON API request to domain,step,offset:", domain, step, offset)
- fetched = post_json_api(domain, "/api/federation/instances", json.dumps({
- "sort" : "+pubAt",
- "host" : None,
- "suspended": True,
- "limit" : step
- }), {"Origin": domain})
- else:
- # DEBUG: print("DEBUG: Sending JSON API request to domain,step,offset:", domain, step, offset)
- fetched = post_json_api(domain, "/api/federation/instances", json.dumps({
- "sort" : "+pubAt",
- "host" : None,
- "suspended": True,
- "limit" : step,
- "offset" : offset - 1
- }), {"Origin": domain})
-
- print("DEBUG: fetched():", len(fetched))
- if len(fetched) == 0:
- # DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
- break
- elif len(fetched) != config["misskey_offset"]:
- print(f"WARNING: Fetched '{len(fetched)}' row(s) but expected: '{config['misskey_offset']}'")
- offset = offset + (config["misskey_offset"] - len(fetched))
- else:
- # DEBUG: print("DEBUG: Raising offset by step:", step)
- offset = offset + step
-
- for instance in fetched:
- # just in case
- if instance["isSuspended"]:
- blocks["suspended"].append(
- {
- "domain": tidyup(instance["host"]),
- # no reason field, nothing
- "reason": None
- }
- )
-
- except BaseException as e:
- print("WARNING: Caught error, exiting loop:", domain, e)
- update_last_error(domain, e)
- offset = 0
- break
-
- while True:
- # same shit, different asshole ("blocked" aka full suspend)
- try:
- if offset == 0:
- # DEBUG: print("DEBUG: Sending JSON API request to domain,step,offset:", domain, step, offset)
- fetched = post_json_api(domain,"/api/federation/instances", json.dumps({
- "sort" : "+pubAt",
- "host" : None,
- "blocked": True,
- "limit" : step
- }), {"Origin": domain})
- else:
- # DEBUG: print("DEBUG: Sending JSON API request to domain,step,offset:", domain, step, offset)
- fetched = post_json_api(domain,"/api/federation/instances", json.dumps({
- "sort" : "+pubAt",
- "host" : None,
- "blocked": True,
- "limit" : step,
- "offset" : offset-1
- }), {"Origin": domain})
-
- print("DEBUG: fetched():", len(fetched))
- if len(fetched) == 0:
- # DEBUG: print("DEBUG: Returned zero bytes, exiting loop:", domain)
- break
- elif len(fetched) != config["misskey_offset"]:
- print(f"WARNING: Fetched '{len(fetched)}' row(s) but expected: '{config['misskey_offset']}'")
- offset = offset + (config["misskey_offset"] - len(fetched))
- else:
- # DEBUG: print("DEBUG: Raising offset by step:", step)
- offset = offset + step
-
- for instance in fetched:
- if instance["isBlocked"]:
- blocks["blocked"].append({
- "domain": tidyup(instance["host"]),
- "reason": None
- })
-
- except BaseException as e:
- print("ERROR: Exception during POST:", domain, e)
- update_last_error(domain, e)
- offset = 0
- break
-
- # DEBUG: print("DEBUG: Returning for domain,blocked(),suspended():", domain, len(blocks["blocked"]), len(blocks["suspended"]))
- return {
- "reject" : blocks["blocked"],
- "followers_only": blocks["suspended"]
- }
-
-def tidyup(string: str) -> str:
- # some retards put their blocks in variable case
- string = string.lower().strip()
-
- # other retards put the port
- string = re.sub("\:\d+$", "", string)
-
- # bigger retards put the schema in their blocklist, sometimes even without slashes
- string = re.sub("^https?\:(\/*)", "", string)