]> git.mxchange.org Git - fba.git/blobdiff - fba/http/federation.py
Continued:
[fba.git] / fba / http / federation.py
index aa1adf9224e58c511003a0fe431bc304fd73a909..50f66c37eb0ccea179e207a05010d11d213ed54c 100644 (file)
@@ -21,8 +21,6 @@ import bs4
 import requests
 import validators
 
-from fba import csrf
-
 from fba.helpers import config
 from fba.helpers import cookies
 from fba.helpers import domain as domain_helper
@@ -30,9 +28,11 @@ from fba.helpers import software as software_helper
 from fba.helpers import tidyup
 from fba.helpers import version
 
+from fba.http import csrf
 from fba.http import network
 from fba.http import nodeinfo
 
+from fba.models import blocks
 from fba.models import instances
 
 from fba.networks import lemmy
@@ -84,6 +84,11 @@ def fetch_instances(domain: str, origin: str, software: str, command: str, path:
         logger.debug("Adding new domain='%s',origin='%s',command='%s',path='%s',software='%s'", domain, origin, command, path, software)
         instances.add(domain, origin, command, path, software)
 
+        logger.debug("software='%s'", software)
+        if software_helper.is_relay(software):
+            logger.debug("software='%s' is a relay software - EXIT!", software)
+            return
+
     logger.debug("Updating last_instance_fetch for domain='%s' ...", domain)
     instances.set_last_instance_fetch(domain)
 
@@ -107,7 +112,7 @@ def fetch_instances(domain: str, origin: str, software: str, command: str, path:
 
         if instances.has_pending(domain):
             logger.debug("Flushing updates for domain='%s' ...", domain)
-            instances.update_data(domain)
+            instances.update(domain)
 
         logger.debug("Invoking cookies.clear(%s) ...", domain)
         cookies.clear(domain)
@@ -151,7 +156,7 @@ def fetch_instances(domain: str, origin: str, software: str, command: str, path:
             logger.debug("Checking if domain='%s' has pending updates ...", domain)
             if instances.has_pending(domain):
                 logger.debug("Flushing updates for domain='%s' ...", domain)
-                instances.update_data(domain)
+                instances.update(domain)
 
             logger.debug("instance='%s',origin='%s',_DEPTH=%d reached!", instance, origin, _DEPTH)
             if _DEPTH <= config.get("max_crawl_depth") and len(peerlist) >= config.get("min_peers_length"):
@@ -167,7 +172,7 @@ def fetch_instances(domain: str, origin: str, software: str, command: str, path:
     logger.debug("Checking if domain='%s' has pending updates ...", domain)
     if instances.has_pending(domain):
         logger.debug("Flushing updates for domain='%s' ...", domain)
-        instances.update_data(domain)
+        instances.update(domain)
 
     _DEPTH = _DEPTH - 1
     logger.debug("EXIT!")
@@ -178,6 +183,8 @@ def fetch_peers(domain: str, software: str, origin: str) -> list:
 
     if 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):
+        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'")
     elif isinstance(origin, str) and origin == "":
@@ -255,7 +262,6 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str:
     elif path == "":
         raise ValueError("Parameter 'path' is empty")
 
-    logger.debug("domain='%s',path='%s' - CALLED!", domain, path)
     software = None
 
     logger.debug("Fetching path='%s' from domain='%s' ...", path, domain)
@@ -268,7 +274,7 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str:
     )
 
     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 < 300) or response.status_code == 410) and response.text.find("<html") > 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("<html") > 0 and domain_helper.is_in_url(domain, response.url):
         logger.debug("Parsing response.text()=%d Bytes ...", len(response.text))
         doc = bs4.BeautifulSoup(response.text, "html.parser")
 
@@ -279,7 +285,7 @@ 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"))
 
@@ -287,7 +293,7 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str:
             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"))
 
@@ -295,7 +301,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"))
 
@@ -303,7 +309,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"))
 
@@ -315,11 +321,15 @@ def fetch_generator_from_path(domain: str, path: str = "/") -> str:
         logger.warning("domain='%s' doesn't match response.url='%s', maybe redirect to other domain?", domain, response.url)
 
         components = urlparse(response.url)
+        domain2 = components.netloc.lower().split(":")[0]
 
-        logger.debug("components[]='%s'", type(components))
-        if not instances.is_registered(components.netloc):
+        logger.debug("domain2='%s'", domain2)
+        if not domain_helper.is_wanted(domain2):
+            logger.debug("domain2='%s' is not wanted - EXIT!", domain2)
+            return None
+        elif not instances.is_registered(domain2):
             logger.info("components.netloc='%s' is not registered, adding ...", components.netloc)
-            fetch_instances(components.netloc, domain, None, "fetch_generator")
+            instances.add(domain2, domain, "redirect_target")
 
         message = f"Redirect from domain='{domain}' to response.url='{response.url}'"
         instances.set_last_error(domain, message)
@@ -361,12 +371,10 @@ def determine_software(domain: str, path: str = None) -> str:
     if not isinstance(path, str) and path is not None:
         raise ValueError(f"Parameter path[]='{type(path)}' is not of type 'str'")
 
-    logger.debug("Determining software for domain='%s',path='%s'", domain, path)
+    logger.debug("Fetching nodeinfo from domain='%s',path='%s' ...", domain, path)
+    data = nodeinfo.fetch(domain, path)
     software = None
 
-    logger.debug("Fetching nodeinfo from domain='%s' ...", domain)
-    data = nodeinfo.fetch_nodeinfo(domain, path)
-
     logger.debug("data[%s]='%s'", type(data), data)
     if "exception" in data:
         # Continue raising it
@@ -418,7 +426,7 @@ 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 is None or software == "":
         logger.debug("Returning None - EXIT!")
         return None
 
@@ -438,6 +446,8 @@ def determine_software(domain: str, path: str = None) -> str:
         logger.debug("software='%s' has 'powered by' in it", software)
         software = version.remove(software_helper.strip_powered_by(software))
 
+    software = software.strip()
+
     logger.debug("software='%s' - EXIT!", software)
     return software
 
@@ -528,3 +538,95 @@ def add_peers(rows: dict) -> list:
 
     logger.debug("peers()=%d - EXIT!", len(peers))
     return peers
+
+def fetch_blocks(domain: str) -> list:
+    logger.debug("domain='%s' - CALLED!", domain)
+    domain_helper.raise_on(domain)
+
+    if not instances.is_registered(domain):
+        raise Exception(f"domain='{domain}' is not registered but function is invoked.")
+
+    # Init block list
+    blocklist = list()
+
+    # No CSRF by default, you don't have to add network.api_headers by yourself here
+    headers = tuple()
+
+    try:
+        logger.debug("Checking CSRF for domain='%s'", domain)
+        headers = csrf.determine(domain, dict())
+    except network.exceptions as exception:
+        logger.warning("Exception '%s' during checking CSRF (fetch_blocks,%s)", type(exception), __name__)
+        instances.set_last_error(domain, exception)
+
+        logger.debug("Returning empty list ... - EXIT!")
+        return list()
+
+    try:
+        # json endpoint for newer mastodongs
+        logger.info("Fetching domain_blocks from domain='%s' ...", domain)
+        data = network.get_json_api(
+            domain,
+            "/api/v1/instance/domain_blocks",
+            headers,
+            (config.get("connection_timeout"), config.get("read_timeout"))
+        )
+        rows = list()
+
+        logger.debug("data[]='%s'", 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)
+            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)
+            return blocklist
+        else:
+            # Getting blocklist
+            rows = data["json"]
+
+            logger.debug("Marking domain='%s' as successfully handled ...", domain)
+            instances.set_success(domain)
+
+        logger.debug("rows[%s]()=%d", type(rows), len(rows))
+        if len(rows) > 0:
+            logger.debug("Checking %d entries from domain='%s' ...", len(rows), domain)
+            for block in rows:
+                # Check type
+                logger.debug("block[]='%s'", type(block))
+                if not isinstance(block, dict):
+                    logger.debug("block[]='%s' is of type 'dict' - SKIPPED!", type(block))
+                    continue
+                elif "domain" not in block:
+                    logger.warning("block()=%d does not contain element 'domain' - SKIPPED!", len(block))
+                    continue
+                elif "severity" not in block:
+                    logger.warning("block()=%d does not contain element 'severity' - SKIPPED!", len(block))
+                    continue
+                elif block["severity"] in ["accept", "accepted"]:
+                    logger.debug("block[domain]='%s' has unwanted severity level '%s' - SKIPPED!", block["domain"], block["severity"])
+                    continue
+                elif "digest" in block and not validators.hashes.sha256(block["digest"]):
+                    logger.warning("block[domain]='%s' has invalid block[digest]='%s' - SKIPPED!", block["domain"], block["digest"])
+                    continue
+
+                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"])
+                blocklist.append({
+                    "blocker"    : domain,
+                    "blocked"    : block["domain"],
+                    "digest"     : block["digest"] if "digest" in block else None,
+                    "reason"     : reason,
+                    "block_level": blocks.alias_block_level(block["severity"]),
+                })
+        else:
+            logger.debug("domain='%s' has no block list", domain)
+
+    except network.exceptions as exception:
+        logger.warning("domain='%s',exception[%s]='%s'", domain, type(exception), str(exception))
+        instances.set_last_error(domain, exception)
+
+    logger.debug("blocklist()=%d - EXIT!", len(blocklist))
+    return blocklist