X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=fba%2Fhttp%2Ffederation.py;h=2c35fc65887373b84dcf368329dbcc46e25b2d5b;hb=99e074c6332a63c26de35e347f13c75b3651d8d8;hp=46c1da60d70966f45592c250fe21026e0c883d6c;hpb=a436e35a18dc0a69f7d04f326865943fd331c719;p=fba.git diff --git a/fba/http/federation.py b/fba/http/federation.py index 46c1da6..2c35fc6 100644 --- a/fba/http/federation.py +++ b/fba/http/federation.py @@ -21,6 +21,7 @@ import bs4 import requests import validators +from fba.helpers import blacklist from fba.helpers import config from fba.helpers import cookies from fba.helpers import domain as domain_helper @@ -42,6 +43,12 @@ from fba.networks import peertube # Depth counter, being raised and lowered _DEPTH = 0 +# API paths +_api_paths = [ + "/api/v1/instance/peers", + "/api/v3/site", +] + logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -50,21 +57,25 @@ def fetch_instances(domain: str, origin: str, software: str, command: str, path: logger.debug("domain='%s',origin='%s',software='%s',command='%s',path='%s',_DEPTH=%d - CALLED!", domain, origin, software, command, path, _DEPTH) domain_helper.raise_on(domain) - if not isinstance(origin, str) and origin is not None: + if blacklist.is_blacklisted(domain): + raise Exception(f"domain='{domain}' is blacklisted but function was invoked") + elif not isinstance(origin, str) and origin is not None: raise ValueError(f"Parameter origin[]='{type(origin)}' is not of type 'str'") elif not isinstance(command, str): raise ValueError(f"Parameter command[]='{type(command)}' is not of type 'str'") elif command == "": raise ValueError("Parameter 'command' is empty") - elif command in ["fetch_blocks", "fetch_cs", "fetch_bkali", "fetch_relays", "fetch_fedipact", "fetch_joinmobilizon", "fetch_joinmisskey", "fetch_joinfediverse"] and origin is None: + elif command in ["fetch_blocks", "fetch_cs", "fetch_bkali", "fetch_relays", "fetch_fedipact", "fetch_joinmobilizon", "fetch_joinmisskey", "fetch_joinfediverse", "fetch_relaylist"] and origin is None: raise ValueError(f"Parameter command='{command}' but origin is None, please fix invoking this function.") elif not isinstance(path, str) and path is not None: raise ValueError(f"Parameter path[]='{type(path)}' is not of type 'str'") + elif path is not None and not path.startswith("/"): + raise ValueError(f"path='{path}' does not start with a slash") elif _DEPTH > 0 and instances.is_recent(domain, "last_instance_fetch"): raise ValueError(f"domain='{domain}' has recently been fetched but function was invoked") elif software is None and not instances.is_recent(domain, "last_nodeinfo"): try: - logger.debug("Software for domain='%s' is not set, determining ...", domain) + logger.debug("Software for domain='%s',path='%s' is not set, determining ...", domain, path) software = determine_software(domain, path) except network.exceptions as exception: logger.warning("Exception '%s' during determining software type", type(exception)) @@ -85,8 +96,9 @@ def fetch_instances(domain: str, origin: str, software: str, command: str, path: instances.add(domain, origin, command, path, software) logger.debug("software='%s'", software) - if software_helper.is_relay(software): + if software is not None and software_helper.is_relay(software): logger.debug("software='%s' is a relay software - EXIT!", software) + _DEPTH = _DEPTH - 1 return logger.debug("Updating last_instance_fetch for domain='%s' ...", domain) @@ -99,41 +111,50 @@ def fetch_instances(domain: str, origin: str, software: str, command: str, path: logger.debug("Fetching instances for domain='%s',software='%s',origin='%s'", domain, software, origin) peerlist = fetch_peers(domain, software, origin) except network.exceptions as exception: - logger.warning("Cannot fetch peers from domain='%s',software='%s': '%s'", domain, software, type(exception)) + _DEPTH = _DEPTH - 1 + raise exception logger.debug("peerlist[]='%s'", type(peerlist)) if isinstance(peerlist, list): logger.debug("Invoking instances.set_total_peerlist(%s,%d) ...", domain, len(peerlist)) instances.set_total_peers(domain, peerlist) + logger.debug("Invoking cookies.clear(%s) ...", domain) + cookies.clear(domain) + logger.debug("peerlist[]='%s'", type(peerlist)) - if peerlist is None or len(peerlist) == 0: + if peerlist is None: logger.warning("Cannot fetch peers: domain='%s',software='%s'", domain, software) - if instances.has_pending(domain): logger.debug("Flushing updates for domain='%s' ...", domain) instances.update(domain) - logger.debug("Invoking cookies.clear(%s) ...", domain) - cookies.clear(domain) - _DEPTH = _DEPTH - 1 logger.debug("EXIT!") return + elif len(peerlist) == 0: + logger.info("domain='%s' returned an empty peer list.", domain) + if instances.has_pending(domain): + logger.debug("Flushing updates for domain='%s' ...", domain) + instances.update(domain) + + _DEPTH = _DEPTH - 1 + logger.debug("domain='%s',software='%s' has an empty peer list returned - EXIT!", domain, software) + return logger.info("Checking %d instance(s) from domain='%s',software='%s',depth=%d ...", len(peerlist), domain, software, _DEPTH) for instance in peerlist: - logger.debug("instance='%s'", instance) - if instance is None or instance == "": + logger.debug("instance[%s]='%s'", type(instance), instance) + if instance in [None, ""]: logger.debug("instance[%s]='%s' is either None or empty - SKIPPED!", type(instance), instance) continue logger.debug("instance='%s' - BEFORE!", instance) - instance = tidyup.domain(instance) + instance = tidyup.domain(instance) if isinstance(instance, str) and instance != "" else None logger.debug("instance='%s' - AFTER!", instance) - if instance == "": - logger.warning("Empty instance after tidyup.domain(), domain='%s'", domain) + if instance in [None, ""]: + logger.warning("instance='%s' is empty after tidyup.domain(), domain='%s'", instance, domain) continue elif ".." in instance: logger.warning("instance='%s' contains double-dot, removing ...", instance) @@ -166,9 +187,6 @@ def fetch_instances(domain: str, origin: str, software: str, command: str, path: logger.debug("Adding instance='%s',domain='%s',command='%s',_DEPTH=%d ...", instance, domain, command, _DEPTH) instances.add(instance, domain, command) - logger.debug("Invoking cookies.clear(%s) ...", domain) - cookies.clear(domain) - logger.debug("Checking if domain='%s' has pending updates ...", domain) if instances.has_pending(domain): logger.debug("Flushing updates for domain='%s' ...", domain) @@ -181,9 +199,13 @@ def fetch_peers(domain: str, software: str, origin: str) -> list: logger.debug("domain='%s',software='%s',origin='%s' - CALLED!", domain, software, origin) domain_helper.raise_on(domain) - if not isinstance(software, str) and software is not None: + if blacklist.is_blacklisted(domain): + raise Exception(f"domain='{domain}' is blacklisted but function was invoked") + elif not isinstance(software, str) and software is not None: raise ValueError(f"Parameter software[]='{type(software)}' is not of type 'str'") - elif software_helper.is_relay(software): + elif isinstance(software, str) and software == "": + raise ValueError("Parameter 'software' is empty") + elif software is not None and software_helper.is_relay(software): raise ValueError(f"domain='{domain}' is of software='{software}' and isn't supported here.") elif not isinstance(origin, str) and origin is not None: raise ValueError(f"Parameter origin[]='{type(origin)}' is not of type 'str'") @@ -213,25 +235,20 @@ def fetch_peers(domain: str, software: str, origin: str) -> list: logger.debug("Returning empty list ... - EXIT!") return list() - paths = [ - "/api/v1/instance/peers", - "/api/v3/site", - ] - # Init peers variable peers = list() - logger.debug("Checking %d paths ...", len(paths)) - for path in paths: + logger.debug("Checking %d API paths ...", len(_api_paths)) + for path in _api_paths: logger.debug("Fetching path='%s' from domain='%s',software='%s' ...", path, domain, software) data = network.get_json_api( domain, path, - headers, - (config.get("connection_timeout"), config.get("read_timeout")) + headers=headers, + timeout=(config.get("connection_timeout"), config.get("read_timeout")) ) - logger.debug("data[]='%s'", type(data)) + logger.debug("data(%d)[]='%s'", len(data), type(data)) if "error_message" in data: logger.debug("Was not able to fetch peers from path='%s',domain='%s' ...", path, domain) instances.set_last_error(domain, data) @@ -257,25 +274,28 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str: logger.debug("domain='%s',path='%s' - CALLED!", domain, path) domain_helper.raise_on(domain) - if not isinstance(path, str): + if blacklist.is_blacklisted(domain): + raise Exception(f"domain='{domain}' is blacklisted but function was invoked") + elif not isinstance(path, str): raise ValueError(f"path[]='{type(path)}' is not of type 'str'") elif path == "": raise ValueError("Parameter 'path' is empty") + elif not path.startswith("/"): + raise ValueError(f"path='{path}' does not start with / but should") - logger.debug("domain='%s',path='%s' - CALLED!", domain, path) software = None logger.debug("Fetching path='%s' from domain='%s' ...", path, domain) response = network.fetch_response( domain, path, - network.web_headers, - (config.get("connection_timeout"), config.get("read_timeout")), + headers=network.web_headers, + timeout=(config.get("connection_timeout"), config.get("read_timeout")), allow_redirects=True ) logger.debug("response.ok='%s',response.status_code=%d,response.text()=%d", response.ok, response.status_code, len(response.text)) - if ((response.ok and response.status_code == 200) or response.status_code == 410) and response.text.find(" 0 and domain_helper.is_in_url(domain, response.url): + if ((response.ok and response.status_code == 200) or response.status_code == 410) and response.text.find(" 0 and domain_helper.is_in_url(domain, response.url.split("#")[0]): logger.debug("Parsing response.text()=%d Bytes ...", len(response.text)) doc = bs4.BeautifulSoup(response.text, "html.parser") @@ -286,15 +306,15 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str: app_name = doc.find("meta", {"name" : "application-name"}) logger.debug("generator[]='%s',site_name[]='%s',platform[]='%s',app_name[]='%s'", type(generator), type(site_name), type(platform), type(app_name)) - if isinstance(platform, bs4.element.Tag) and isinstance(platform.get("content"), str): + if isinstance(platform, bs4.element.Tag) and isinstance(platform.get("content"), str) and platform.get("content") != "": logger.debug("Found property=og:platform, domain='%s'", domain) software = tidyup.domain(platform.get("content")) + logger.debug("software[%s]='%s' after tidyup.domain() ...", type(software), software) - logger.debug("software[%s]='%s'", type(software), software) if software is not None and software != "": logger.debug("domain='%s' has og:platform='%s' - Setting detection_mode=PLATFORM ...", domain, software) instances.set_detection_mode(domain, "PLATFORM") - elif isinstance(generator, bs4.element.Tag) and isinstance(generator.get("content"), str): + elif isinstance(generator, bs4.element.Tag) and isinstance(generator.get("content"), str) and generator.get("content") != "": logger.debug("Found generator meta tag: domain='%s'", domain) software = tidyup.domain(generator.get("content")) @@ -302,7 +322,7 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str: if software is not None and software != "": logger.info("domain='%s' is generated by software='%s' - Setting detection_mode=GENERATOR ...", domain, software) instances.set_detection_mode(domain, "GENERATOR") - elif isinstance(app_name, bs4.element.Tag) and isinstance(app_name.get("content"), str): + elif isinstance(app_name, bs4.element.Tag) and isinstance(app_name.get("content"), str) and app_name.get("content") != "": logger.debug("Found property=og:app_name, domain='%s'", domain) software = tidyup.domain(app_name.get("content")) @@ -310,7 +330,7 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str: if software is not None and software != "": logger.debug("domain='%s' has application-name='%s' - Setting detection_mode=app_name ...", domain, software) instances.set_detection_mode(domain, "APP_NAME") - elif isinstance(site_name, bs4.element.Tag) and isinstance(site_name.get("content"), str): + elif isinstance(site_name, bs4.element.Tag) and isinstance(site_name.get("content"), str) and site_name.get("content") != "": logger.debug("Found property=og:site_name, domain='%s'", domain) software = tidyup.domain(site_name.get("content")) @@ -318,7 +338,7 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str: if software is not None and software != "": logger.debug("domain='%s' has og:site_name='%s' - Setting detection_mode=SITE_NAME ...", domain, software) instances.set_detection_mode(domain, "SITE_NAME") - elif not domain_helper.is_in_url(domain, response.url): + elif not domain_helper.is_in_url(domain, response.url.split("#")[0]): logger.warning("domain='%s' doesn't match response.url='%s', maybe redirect to other domain?", domain, response.url) components = urlparse(response.url) @@ -348,7 +368,7 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str: logger.debug("software='%s' may contain a version number, domain='%s', removing it ...", software, domain) software = version.remove(software) - logger.debug("software[]='%s'", type(software)) + logger.debug("software[%s]='%s'", type(software), software) if isinstance(software, str) and "powered by " in software: logger.debug("software='%s' has 'powered by' in it", software) software = version.remove(software_helper.strip_powered_by(software)) @@ -362,15 +382,19 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str: logger.debug("software='%s' has ' see ' in it", software) software = software_helper.strip_until(software, " see ") - logger.debug("software='%s' - EXIT!", software) + logger.debug("software[%s]='%s' - EXIT!", type(software), software) return software def determine_software(domain: str, path: str = None) -> str: logger.debug("domain='%s',path='%s' - CALLED!", domain, path) domain_helper.raise_on(domain) - if not isinstance(path, str) and path is not None: + if blacklist.is_blacklisted(domain): + raise Exception(f"domain='{domain}' is blacklisted but function was invoked") + elif not isinstance(path, str) and path is not None: raise ValueError(f"Parameter path[]='{type(path)}' is not of type 'str'") + elif path is not None and not path.startswith("/"): + raise ValueError(f"path='{path}' does not start with a slash") logger.debug("Fetching nodeinfo from domain='%s',path='%s' ...", domain, path) data = nodeinfo.fetch(domain, path) @@ -427,15 +451,18 @@ def determine_software(domain: str, path: str = None) -> str: logger.debug("Generator for domain='%s' is: '%s'", domain, software) logger.debug("software[%s]='%s'", type(software), software) - if software is None: + if software in [None, ""]: logger.debug("Returning None - EXIT!") return None + logger.debug("Setting original software='%s' for domain='%s' ...", software, domain) + instances.set_original_software(domain, software) + logger.debug("software='%s'- BEFORE!", software) software = software_helper.alias(software) logger.debug("software['%s']='%s' - AFTER!", type(software), software) - if str(software) == "": + if software in [None, ""]: logger.debug("software for domain='%s' was not detected, trying generator ...", domain) software = fetch_generator_from_path(domain) elif len(str(software)) > 0 and ("." in software or " " in software): @@ -449,11 +476,12 @@ def determine_software(domain: str, path: str = None) -> str: software = software.strip() - logger.debug("software='%s' - EXIT!", software) + logger.debug("software[%s]='%s' - EXIT!", type(software), software) return software def find_domains(tag: bs4.element.Tag) -> list: logger.debug("tag[]='%s' - CALLED!", type(tag)) + if not isinstance(tag, bs4.element.Tag): raise ValueError(f"Parameter tag[]='{type(tag)}' is not type of bs4.element.Tag") elif len(tag.select("tr")) == 0: @@ -475,7 +503,7 @@ def find_domains(tag: bs4.element.Tag) -> list: logger.debug("domain='%s' is blacklisted - SKIPPED!", domain) continue elif domain == "gab.com/.ai, develop.gab.com": - logger.debug("Multiple domains detected in one row") + logger.debug("Multiple gab.com domains detected in one row") domains.append({ "domain": "gab.com", "reason": reason, @@ -504,12 +532,15 @@ def find_domains(tag: bs4.element.Tag) -> list: def add_peers(rows: dict) -> list: logger.debug("rows[]='%s' - CALLED!", type(rows)) + if not isinstance(rows, dict): raise ValueError(f"Parameter rows[]='{type(rows)}' is not of type 'dict'") + elif len(rows) == 0: + raise ValueError("Parameter 'rows' is empty") peers = list() for key in ["linked", "allowed", "blocked"]: - logger.debug("Checking key='%s'", key) + logger.debug("key='%s'", key) if key not in rows or rows[key] is None: logger.debug("Cannot find key='%s' or it is NoneType - SKIPPED!", key) continue @@ -517,7 +548,7 @@ def add_peers(rows: dict) -> list: logger.debug("Adding %d peer(s) to peers list ...", len(rows[key])) for peer in rows[key]: logger.debug("peer[%s]='%s' - BEFORE!", type(peer), peer) - if peer is None or peer == "": + if peer in [None, ""]: logger.debug("peer is empty - SKIPPED") continue elif isinstance(peer, dict) and "domain" in peer: @@ -544,7 +575,9 @@ def fetch_blocks(domain: str) -> list: logger.debug("domain='%s' - CALLED!", domain) domain_helper.raise_on(domain) - if not instances.is_registered(domain): + if blacklist.is_blacklisted(domain): + raise Exception(f"domain='{domain}' is blacklisted but function was invoked") + elif not instances.is_registered(domain): raise Exception(f"domain='{domain}' is not registered but function is invoked.") # Init block list @@ -569,19 +602,23 @@ def fetch_blocks(domain: str) -> list: data = network.get_json_api( domain, "/api/v1/instance/domain_blocks", - headers, - (config.get("connection_timeout"), config.get("read_timeout")) + headers=headers, + timeout=(config.get("connection_timeout"), config.get("read_timeout")) ) rows = list() - logger.debug("data[]='%s'", type(data)) + logger.debug("data(%d)[]='%s'", len(data), type(data)) if "error_message" in data: logger.debug("Was not able to fetch domain_blocks from domain='%s': status_code=%d,error_message='%s'", domain, data['status_code'], data['error_message']) instances.set_last_error(domain, data) + + logger.debug("blocklist()=%d - EXIT!", len(blocklist)) return blocklist elif "json" in data and "error" in data["json"]: logger.warning("JSON API returned error message: '%s'", data["json"]["error"]) instances.set_last_error(domain, data) + + logger.debug("blocklist()=%d - EXIT!", len(blocklist)) return blocklist else: # Getting blocklist @@ -590,7 +627,7 @@ def fetch_blocks(domain: str) -> list: logger.debug("Marking domain='%s' as successfully handled ...", domain) instances.set_success(domain) - logger.debug("rows[%s]()=%d", type(rows), len(rows)) + logger.debug("rows(%d)[]='%s'", len(rows), type(rows)) if len(rows) > 0: logger.debug("Checking %d entries from domain='%s' ...", len(rows), domain) for block in rows: @@ -614,7 +651,7 @@ def fetch_blocks(domain: str) -> list: reason = tidyup.reason(block["comment"]) if "comment" in block and block["comment"] is not None and block["comment"] != "" else None - logger.debug("Appending blocker='%s',blocked='%s',reason='%s',block_level='%s'", domain, block["domain"], reason, block["severity"]) + logger.debug("Appending blocker='%s',blocked='%s',reason='%s',block_level='%s' ...", domain, block["domain"], reason, block["severity"]) blocklist.append({ "blocker" : domain, "blocked" : block["domain"],