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/>.
17 from urllib.parse import urlparse
22 from fba.helpers import config
23 from fba.helpers import domain as domain_helper
25 from fba.http import network
27 from fba.models import instances
31 logging.basicConfig(level=logging.INFO)
32 logger = logging.getLogger(__name__)
34 def fetch(domain: str, path: str = None, nodeinfo_url: str = None) -> dict:
35 logger.debug("domain='%s',path='%s',nodeinfo_url='%s' - CALLED!", domain, path, nodeinfo_url)
36 domain_helper.raise_on(domain)
38 if not isinstance(path, str) and path is not None:
39 raise ValueError(f"Parameter path[]='{type(path)}' is not of type 'str'")
40 elif not isinstance(nodeinfo_url, str) and nodeinfo_url is not None:
41 raise ValueError(f"Parameter nodeinfo_url[]='{type(nodeinfo_url)}' is not of type 'str'")
43 logger.debug("nodeinfo_url='%s'", nodeinfo_url)
44 is_url = nodeinfo_url is not None and not nodeinfo_url.startswith("/") and validators.url(nodeinfo_url)
46 logger.debug("is_url='%s'", is_url)
48 logger.debug("Fetching well-known nodeinfo from domain='%s' ...", domain)
49 data = fetch_wellknown_nodeinfo(domain)
51 logger.debug("data[%s](%d)='%s'", type(data), len(data), data)
52 if "exception" in data:
53 logger.warning("Exception returned: '%s', raising again ...", type(data["exception"]))
54 raise data["exception"]
55 elif "error_message" not in data and "json" in data and len(data["json"]) > 0:
56 logger.debug("Invoking instances.set_last_nodeinfo(%s) ...", domain)
57 instances.set_last_nodeinfo(domain)
59 logger.debug("Found data[json]()=%d - EXIT!", len(data['json']))
62 # No CSRF by default, you don't have to add network.api_headers by yourself here
67 logger.debug("Checking CSRF for domain='%s'", domain)
68 headers = csrf.determine(domain, dict())
69 except network.exceptions as exception:
70 logger.warning("Exception '%s' during checking CSRF (nodeinfo,%s) - EXIT!", type(exception), __name__)
71 instances.set_last_error(domain, exception)
74 "error_message": f"exception[{type(exception)}]='{str(exception)}'",
75 "exception" : exception,
88 for request in request_paths:
89 logger.debug("request='%s'", request)
90 http_url = f"http://{domain}{str(path) if path is not None else '/'}"
91 https_url = f"https://{domain}{str(path) if path is not None else '/'}"
93 logger.debug("path[%s]='%s',request='%s',http_url='%s',https_url='%s'", type(path), path, request, http_url, https_url)
94 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)):
95 logger.debug("Fetching request='%s' from domain='%s' ...", request, domain)
96 data = network.get_json_api(
100 (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
103 logger.debug("data[]='%s'", type(data))
104 if "error_message" not in data and "json" in data:
105 logger.debug("Success: request='%s' - Setting detection_mode=STATIC_CHECK ...", request)
106 instances.set_last_nodeinfo(domain)
107 instances.set_detection_mode(domain, "STATIC_CHECK")
108 instances.set_nodeinfo_url(domain, "https://{domain}{request}")
111 logger.warning("Failed fetching nodeinfo from domain='%s',status_code='%s',error_message='%s'", domain, data['status_code'], data['error_message'])
113 logger.debug("data()=%d - EXIT!", len(data))
116 def fetch_wellknown_nodeinfo(domain: str) -> dict:
117 logger.debug("domain='%s' - CALLED!", domain)
118 domain_helper.raise_on(domain)
120 # "rel" identifiers (no real URLs)
121 nodeinfo_identifier = [
122 "https://nodeinfo.diaspora.software/ns/schema/2.1",
123 "http://nodeinfo.diaspora.software/ns/schema/2.1",
124 "https://nodeinfo.diaspora.software/ns/schema/2.0",
125 "http://nodeinfo.diaspora.software/ns/schema/2.0",
126 "https://nodeinfo.diaspora.software/ns/schema/1.1",
127 "http://nodeinfo.diaspora.software/ns/schema/1.1",
128 "https://nodeinfo.diaspora.software/ns/schema/1.0",
129 "http://nodeinfo.diaspora.software/ns/schema/1.0",
132 # No CSRF by default, you don't have to add network.api_headers by yourself here
136 logger.debug("Checking CSRF for domain='%s'", domain)
137 headers = csrf.determine(domain, dict())
138 except network.exceptions as exception:
139 logger.warning("Exception '%s' during checking CSRF (fetch_wellknown_nodeinfo,%s) - EXIT!", type(exception), __name__)
140 instances.set_last_error(domain, exception)
143 "error_message": type(exception),
144 "exception" : exception,
149 logger.debug("Fetching .well-known info for domain='%s'", domain)
150 for path in ["/.well-known/x-nodeinfo2", "/.well-known/nodeinfo"]:
151 logger.debug("Fetching path='%s' from domain='%s' ...", path, domain)
152 data = network.get_json_api(
156 (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
158 logger.debug("data[]='%s'", type(data))
160 if "error_message" not in data and "json" in data and len(data["json"]) > 0:
161 logger.debug("path='%s' returned valid json()=%d", path, len(data["json"]))
164 logger.debug("data[]='%s'", type(data))
165 if "exception" in data:
166 logger.warning("domain='%s' returned exception '%s'", domain, str(data["exception"]))
167 raise data["exception"]
168 elif "error_message" in data:
169 logger.warning("domain='%s' returned error message: '%s'", domain, data["error_message"])
171 elif "json" not in data:
172 logger.warning("domain='%s' returned no 'json' key", domain)
176 logger.debug("infos()=%d has been returned", len(infos))
179 logger.debug("Marking domain='%s' as successfully handled ...", domain)
180 instances.set_success(domain)
182 logger.debug("Found infos[links]()=%d record(s),", len(infos["links"]))
183 for niid in nodeinfo_identifier:
186 logger.debug("Checking niid='%s' ...", niid)
187 for link in infos["links"]:
188 logger.debug("link[%s]='%s'", type(link), link)
189 if not isinstance(link, dict) or not "rel" in link:
190 logger.debug("link[]='%s' is not of type 'dict' or no element 'rel' found - SKIPPED!", type(link))
192 elif link["rel"] != niid:
193 logger.debug("link[re]='%s' does not matched niid='%s' - SKIPPED!", link["rel"], niid)
195 elif "href" not in link:
196 logger.warning("link[rel]='%s' has no element 'href' - SKIPPED!", link["rel"])
198 elif link["href"] is None:
199 logger.debug("link[href] is None, link[rel]='%s' - SKIPPED!", link["rel"])
202 # Default is that 'href' has a complete URL, but some hosts don't send that
203 logger.debug("link[rel]='%s' matches niid='%s'", link["rel"], niid)
205 components = urlparse(url)
207 logger.debug("components[%s]='%s'", type(components), components)
208 if components.scheme == "" and components.netloc == "":
209 logger.warning("link[href]='%s' has no scheme and host name in it, prepending from domain='%s'", link['href'], domain)
210 url = f"https://{domain}{url}"
211 components = urlparse(url)
212 elif components.netloc == "":
213 logger.warning("link[href]='%s' has no netloc set, setting domain='%s'", link["href"], domain)
214 url = f"{components.scheme}://{domain}{components.path}"
215 components = urlparse(url)
217 logger.debug("components.netloc[]='%s'", type(components.netloc))
218 if not domain_helper.is_wanted(components.netloc):
219 logger.debug("components.netloc='%s' is not wanted - SKIPPED!", components.netloc)
222 logger.debug("Fetching nodeinfo from url='%s' ...", url)
223 data = network.fetch_api_url(
225 (config.get("connection_timeout"), config.get("read_timeout"))
228 logger.debug("link[href]='%s',data[]='%s'", link["href"], type(data))
229 if "error_message" not in data and "json" in data:
230 logger.debug("Found JSON data()=%d,link[href]='%s' - Setting detection_mode=AUTO_DISCOVERY ...", len(data), link["href"])
231 instances.set_detection_mode(domain, "AUTO_DISCOVERY")
232 instances.set_nodeinfo_url(domain, link["href"])
234 logger.debug("Marking domain='%s' as successfully handled ...", domain)
235 instances.set_success(domain)
238 logger.debug("Setting last error for domain='%s',data[]='%s'", domain, type(data))
239 instances.set_last_error(domain, data)
241 logger.debug("data()=%d", len(data))
242 if "error_message" not in data and "json" in data:
243 logger.debug("Auto-discovery successful: domain='%s'", domain)
245 elif "server" in infos:
246 logger.debug("Found infos[server][software]='%s'", infos["server"]["software"])
247 instances.set_detection_mode(domain, "AUTO_DISCOVERY")
248 instances.set_nodeinfo_url(domain, f"https://{domain}/.well-known/x-nodeinfo2")
250 logger.debug("Marking domain='%s' as successfully handled ...", domain)
251 instances.set_success(domain)
253 logger.warning("nodeinfo does not contain 'links' or 'server': domain='%s'", domain)
255 logger.debug("Returning data[]='%s' - EXIT!", type(data))