1 # Copyright (C) 2023 Free Software Foundation
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU Affero General Public License as published
5 # by the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU Affero General Public License for more details.
13 # You should have received a copy of the GNU Affero General Public License
14 # along with this program. If not, see <https://www.gnu.org/licenses/>.
19 from urllib.parse import urlparse
23 from fba.helpers import config
24 from fba.helpers import domain as domain_helper
26 from fba.http import network
28 from fba.models import instances
32 logging.basicConfig(level=logging.INFO)
33 logger = logging.getLogger(__name__)
35 def fetch(domain: str, path: str = None, nodeinfo_url: str = None) -> dict:
36 logger.debug("domain='%s',path='%s',nodeinfo_url='%s' - CALLED!", domain, path, nodeinfo_url)
37 domain_helper.raise_on(domain)
39 if not isinstance(path, str) and path is not None:
40 raise ValueError(f"Parameter path[]='{type(path)}' is not of type 'str'")
41 elif not isinstance(nodeinfo_url, str) and nodeinfo_url is not None:
42 raise ValueError(f"Parameter nodeinfo_url[]='{type(nodeinfo_url)}' is not of type 'str'")
44 logger.debug("nodeinfo_url='%s'", nodeinfo_url)
45 is_url = nodeinfo_url is not None and not nodeinfo_url.startswith("/") and validators.url(nodeinfo_url)
47 logger.debug("is_url='%s'", is_url)
49 logger.debug("Fetching well-known nodeinfo from domain='%s' ...", domain)
50 data = fetch_wellknown_nodeinfo(domain)
52 logger.debug("data[%s](%d)='%s'", type(data), len(data), data)
53 if "exception" in data:
54 logger.warning("Exception returned: '%s', raising again ...", type(data["exception"]))
55 raise data["exception"]
56 elif "error_message" not in data and "json" in data and len(data["json"]) > 0:
57 logger.debug("Invoking instances.set_last_nodeinfo(%s) ...", domain)
58 instances.set_last_nodeinfo(domain)
60 logger.debug("Found data[json]()=%d - EXIT!", len(data['json']))
63 # No CSRF by default, you don't have to add network.api_headers by yourself here
68 logger.debug("Checking CSRF for domain='%s'", domain)
69 headers = csrf.determine(domain, dict())
70 except network.exceptions as exception:
71 logger.warning("Exception '%s' during checking CSRF (nodeinfo,%s) - EXIT!", type(exception), __name__)
72 instances.set_last_error(domain, exception)
75 "error_message": f"exception[{type(exception)}]='{str(exception)}'",
76 "exception" : exception,
89 for request in request_paths:
90 logger.debug("request='%s'", request)
91 http_url = f"http://{domain}{str(path) if path is not None else '/'}"
92 https_url = f"https://{domain}{str(path) if path is not None else '/'}"
94 logger.debug("path[%s]='%s',request='%s',http_url='%s',https_url='%s'", type(path), path, request, http_url, https_url)
95 if (path is None and nodeinfo_url is None) or path in [request, http_url, https_url] or (is_url and nodeinfo_url.endswith(request)):
96 logger.debug("Fetching request='%s' from domain='%s' ...", request, domain)
97 data = network.get_json_api(
101 (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
104 logger.debug("data[]='%s'", type(data))
105 if "error_message" not in data and "json" in data:
106 logger.debug("Success: request='%s' - Setting detection_mode=STATIC_CHECK ...", request)
107 instances.set_last_nodeinfo(domain)
108 instances.set_detection_mode(domain, "STATIC_CHECK")
109 instances.set_nodeinfo_url(domain, "https://{domain}{request}")
112 logger.warning("Failed fetching nodeinfo from domain='%s',status_code='%s',error_message='%s'", domain, data['status_code'], data['error_message'])
114 logger.debug("data()=%d - EXIT!", len(data))
117 def fetch_wellknown_nodeinfo(domain: str) -> dict:
118 logger.debug("domain='%s' - CALLED!", domain)
119 domain_helper.raise_on(domain)
121 # "rel" identifiers (no real URLs)
122 nodeinfo_identifier = [
123 "https://nodeinfo.diaspora.software/ns/schema/2.1",
124 "http://nodeinfo.diaspora.software/ns/schema/2.1",
125 "https://nodeinfo.diaspora.software/ns/schema/2.0",
126 "http://nodeinfo.diaspora.software/ns/schema/2.0",
127 "https://nodeinfo.diaspora.software/ns/schema/1.1",
128 "http://nodeinfo.diaspora.software/ns/schema/1.1",
129 "https://nodeinfo.diaspora.software/ns/schema/1.0",
130 "http://nodeinfo.diaspora.software/ns/schema/1.0",
133 # No CSRF by default, you don't have to add network.api_headers by yourself here
137 logger.debug("Checking CSRF for domain='%s'", domain)
138 headers = csrf.determine(domain, dict())
139 except network.exceptions as exception:
140 logger.warning("Exception '%s' during checking CSRF (fetch_wellknown_nodeinfo,%s) - EXIT!", type(exception), __name__)
141 instances.set_last_error(domain, exception)
144 "error_message": type(exception),
145 "exception" : exception,
150 logger.debug("Fetching .well-known info for domain='%s'", domain)
151 for path in ["/.well-known/x-nodeinfo2", "/.well-known/nodeinfo"]:
152 logger.debug("Fetching path='%s' from domain='%s' ...", path, domain)
153 data = network.get_json_api(
157 (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
159 logger.debug("data[]='%s'", type(data))
161 if "error_message" not in data and "json" in data and len(data["json"]) > 0:
162 logger.debug("path='%s' returned valid json()=%d", path, len(data["json"]))
165 logger.debug("data[]='%s'", type(data))
166 if "exception" in data:
167 logger.warning("domain='%s' returned exception '%s'", domain, str(data["exception"]))
168 raise data["exception"]
169 elif "error_message" in data:
170 logger.warning("domain='%s' returned error message: '%s'", domain, data["error_message"])
172 elif "json" not in data:
173 logger.warning("domain='%s' returned no 'json' key", domain)
177 logger.debug("infos()=%d has been returned", len(infos))
180 logger.debug("Marking domain='%s' as successfully handled ...", domain)
181 instances.set_success(domain)
183 logger.debug("Found infos[links]()=%d record(s),", len(infos["links"]))
184 for niid in nodeinfo_identifier:
187 logger.debug("Checking niid='%s' ...", niid)
188 for link in infos["links"]:
189 logger.debug("link[%s]='%s'", type(link), link)
190 if not isinstance(link, dict) or not "rel" in link:
191 logger.debug("link[]='%s' is not of type 'dict' or no element 'rel' found - SKIPPED!", type(link))
193 elif link["rel"] != niid:
194 logger.debug("link[re]='%s' does not matched niid='%s' - SKIPPED!", link["rel"], niid)
196 elif "href" not in link:
197 logger.warning("link[rel]='%s' has no element 'href' - SKIPPED!", link["rel"])
199 elif link["href"] is None:
200 logger.debug("link[href] is None, link[rel]='%s' - SKIPPED!", link["rel"])
203 # Default is that 'href' has a complete URL, but some hosts don't send that
204 logger.debug("link[rel]='%s' matches niid='%s'", link["rel"], niid)
206 components = urlparse(url)
208 logger.debug("components[%s]='%s'", type(components), components)
209 if components.scheme == "" and components.netloc == "":
210 logger.warning("link[href]='%s' has no scheme and host name in it, prepending from domain='%s'", link['href'], domain)
211 url = f"https://{domain}{url}"
212 components = urlparse(url)
213 elif components.netloc == "":
214 logger.warning("link[href]='%s' has no netloc set, setting domain='%s'", link["href"], domain)
215 url = f"{components.scheme}://{domain}{components.path}"
216 components = urlparse(url)
218 logger.debug("components.netloc[]='%s'", type(components.netloc))
219 if not domain_helper.is_wanted(components.netloc):
220 logger.debug("components.netloc='%s' is not wanted - SKIPPED!", components.netloc)
223 logger.debug("Fetching nodeinfo from url='%s' ...", url)
224 data = network.fetch_api_url(
226 (config.get("connection_timeout"), config.get("read_timeout"))
229 logger.debug("link[href]='%s',data[]='%s'", link["href"], type(data))
230 if "error_message" not in data and "json" in data:
231 logger.debug("Found JSON data()=%d,link[href]='%s' - Setting detection_mode=AUTO_DISCOVERY ...", len(data), link["href"])
232 instances.set_detection_mode(domain, "AUTO_DISCOVERY")
233 instances.set_nodeinfo_url(domain, link["href"])
235 logger.debug("Marking domain='%s' as successfully handled ...", domain)
236 instances.set_success(domain)
239 logger.debug("Setting last error for domain='%s',data[]='%s'", domain, type(data))
240 instances.set_last_error(domain, data)
242 logger.debug("data()=%d", len(data))
243 if "error_message" not in data and "json" in data:
244 logger.debug("Auto-discovery successful: domain='%s'", domain)
246 elif "server" in infos:
247 logger.debug("Found infos[server][software]='%s'", infos["server"]["software"])
248 instances.set_detection_mode(domain, "AUTO_DISCOVERY")
249 instances.set_nodeinfo_url(domain, f"https://{domain}/.well-known/x-nodeinfo2")
251 logger.debug("Marking domain='%s' as successfully handled ...", domain)
252 instances.set_success(domain)
254 logger.warning("nodeinfo does not contain 'links' or 'server': domain='%s'", domain)
256 logger.debug("Returning data[]='%s' - EXIT!", type(data))