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/>.
18 from urllib.parse import urlparse
20 from fba.helpers import blacklist
21 from fba.helpers import config
22 from fba.helpers import domain as domain_helper
24 from fba.http import csrf
25 from fba.http import network
27 from fba.models import instances
29 logging.basicConfig(level=logging.INFO)
30 logger = logging.getLogger(__name__)
43 # "rel" identifiers (no real URLs)
44 _nodeinfo_identifier = [
45 "https://nodeinfo.diaspora.software/ns/schema/2.1",
46 "http://nodeinfo.diaspora.software/ns/schema/2.1",
47 "https://nodeinfo.diaspora.software/ns/schema/2.0",
48 "http://nodeinfo.diaspora.software/ns/schema/2.0",
49 "https://nodeinfo.diaspora.software/ns/schema/1.1",
50 "http://nodeinfo.diaspora.software/ns/schema/1.1",
51 "https://nodeinfo.diaspora.software/ns/schema/1.0",
52 "http://nodeinfo.diaspora.software/ns/schema/1.0",
55 def fetch(domain: str, path: str = None, update_mode: bool = True) -> dict:
56 logger.debug("domain='%s',path='%s',update_mode='%s' - CALLED!", domain, path, update_mode)
57 domain_helper.raise_on(domain)
59 if blacklist.is_blacklisted(domain):
60 raise Exception(f"domain='{domain}' is blacklisted but function was invoked")
61 elif not isinstance(path, str) and path is not None:
62 raise ValueError(f"Parameter path[]='{type(path)}' is not of type 'str'")
63 elif path is not None and not path.startswith("/"):
64 raise ValueError(f"path='{path}' does not start with a slash")
65 elif not isinstance(update_mode, bool) and update_mode is not None:
66 raise ValueError(f"Parameter update_mode[]='{type(update_mode)}' is not of type 'bool'")
68 if path is None and update_mode:
69 logger.debug("Fetching well-known nodeinfo from domain='%s' ...", domain)
70 data = fetch_wellknown_nodeinfo(domain)
72 logger.debug("data[%s](%d)='%s'", type(data), len(data), data)
73 if "exception" in data:
74 logger.warning("Exception returned: '%s', raising again ...", type(data["exception"]))
75 raise data["exception"]
76 elif "error_message" not in data and "json" in data and len(data["json"]) > 0:
77 logger.debug("Invoking instances.set_last_nodeinfo(%s) ...", domain)
78 instances.set_last_nodeinfo(domain)
80 logger.debug("Found data[json]()=%d - EXIT!", len(data['json']))
83 # No CSRF by default, you don't have to add network.api_headers by yourself here
88 logger.debug("Checking CSRF for domain='%s'", domain)
89 headers = csrf.determine(domain, dict())
90 logger.debug("headers()=%d", len(headers))
91 except network.exceptions as exception:
92 logger.warning("Exception '%s' during checking CSRF (nodeinfo,%s) - EXIT!", type(exception), __name__)
93 instances.set_last_error(domain, exception)
96 "error_message": f"exception[{type(exception)}]='{str(exception)}'",
97 "exception" : exception,
100 logger.debug("Checking %d request paths ...", len(_request_paths))
101 for request in _request_paths:
102 logger.debug("request='%s'", request)
103 http_url = f"http://{domain}{str(path) if path is not None else '/'}"
104 https_url = f"https://{domain}{str(path) if path is not None else '/'}"
106 logger.debug("path[%s]='%s',request='%s',http_url='%s',https_url='%s'", type(path), path, request, http_url, https_url)
107 if path is None or path in [request, http_url, https_url]:
108 logger.debug("Fetching request='%s' from domain='%s' ...", request, domain)
109 data = network.get_json_api(
113 timeout=(config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
116 logger.debug("data(%d)[]='%s'", len(data), type(data))
117 if "error_message" not in data and "json" in data:
118 logger.debug("Updating last_nodeinfo for domain='%s' ....", domain)
119 instances.set_last_nodeinfo(domain)
121 logger.debug("update_mode='%s'", update_mode)
123 logger.debug("Success: request='%s' - Setting detection_mode=STATIC_CHECK for domain='%s' ...", request, domain)
124 instances.set_detection_mode(domain, "STATIC_CHECK")
126 logger.debug("domain='%s',request='%s'", domain, request)
127 instances.set_nodeinfo_url(domain, "https://{domain}{request}")
129 logger.debug("BREAK!")
132 logger.warning("Failed fetching nodeinfo from domain='%s',status_code='%s',error_message='%s'", domain, data['status_code'], data['error_message'])
134 logger.debug("data()=%d - EXIT!", len(data))
137 def fetch_wellknown_nodeinfo(domain: str) -> dict:
138 logger.debug("domain='%s' - CALLED!", domain)
139 domain_helper.raise_on(domain)
141 if blacklist.is_blacklisted(domain):
142 raise Exception(f"domain='{domain}' is blacklisted but function was invoked")
144 # No CSRF by default, you don't have to add network.api_headers by yourself here
148 logger.debug("Checking CSRF for domain='%s'", domain)
149 headers = csrf.determine(domain, dict())
150 except network.exceptions as exception:
151 logger.warning("Exception '%s' during checking CSRF (fetch_wellknown_nodeinfo,%s) - EXIT!", type(exception), __name__)
152 instances.set_last_error(domain, exception)
155 "error_message": type(exception),
156 "exception" : exception,
161 logger.debug("Fetching .well-known info for domain='%s'", domain)
162 for path in ["/.well-known/x-nodeinfo2", "/.well-known/nodeinfo"]:
163 logger.debug("Fetching path='%s' from domain='%s' ...", path, domain)
164 data = network.get_json_api(
168 (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
171 logger.debug("data(%d)[]='%s'", len(data), type(data))
172 if "error_message" not in data and "json" in data and len(data["json"]) > 0:
173 logger.debug("path='%s' returned valid json()=%d - BREAK!", path, len(data["json"]))
176 logger.debug("data[]='%s'", type(data))
177 if "exception" in data:
178 logger.warning("domain='%s' returned exception '%s' - RAISE!", domain, str(data["exception"]))
179 raise data["exception"]
180 elif "error_message" in data:
181 logger.warning("domain='%s' returned error message: '%s' - EXIT!", domain, data["error_message"])
183 elif "json" not in data:
184 logger.warning("domain='%s' returned no 'json' key - EXIT!", domain)
188 logger.debug("infos(%d)[]='%s' has been returned", len(infos), type(infos))
191 logger.debug("Marking domain='%s' as successfully handled ...", domain)
192 instances.set_success(domain)
194 logger.debug("Found infos[links]()=%d record(s),", len(infos["links"]))
195 for niid in _nodeinfo_identifier:
198 logger.debug("Checking niid='%s' ...", niid)
199 for link in infos["links"]:
200 logger.debug("link[%s]='%s'", type(link), link)
201 if not isinstance(link, dict) or not "rel" in link:
202 logger.debug("link[]='%s' is not of type 'dict' or no element 'rel' found - SKIPPED!", type(link))
204 elif link["rel"] != niid:
205 logger.debug("link[re]='%s' does not matched niid='%s' - SKIPPED!", link["rel"], niid)
207 elif "href" not in link:
208 logger.warning("link[rel]='%s' has no element 'href' - SKIPPED!", link["rel"])
210 elif link["href"] is None or link["href"] == "":
211 logger.debug("link[href]='%s',link[rel]='%s' - SKIPPED!", link["href"], link["rel"])
214 # Default is that 'href' has a complete URL, but some hosts don't send that
215 logger.debug("link[rel]='%s' matches niid='%s'", link["rel"], niid)
216 url = link["href"].lower()
217 components = urlparse(url)
219 logger.debug("components[%s]='%s'", type(components), components)
220 if components.scheme == "" and components.netloc == "":
221 logger.warning("link[href]='%s' has no scheme and host name in it, prepending from domain='%s'", link['href'], domain)
222 url = f"https://{domain}{url}"
223 components = urlparse(url)
224 elif components.netloc == "":
225 logger.warning("link[href]='%s' has no netloc set, setting domain='%s'", link["href"], domain)
226 url = f"{components.scheme}://{domain}{components.path}"
227 components = urlparse(url)
229 domain2 = components.netloc.lower().split(":")[0]
230 logger.debug("domain2='%s'", domain2)
231 if not domain_helper.is_wanted(domain2):
232 logger.debug("domain2='%s' is not wanted - SKIPPED!", domain2)
235 logger.debug("Fetching nodeinfo from url='%s' ...", url)
236 data = network.fetch_api_url(
238 (config.get("connection_timeout"), config.get("read_timeout"))
241 logger.debug("link[href]='%s',data[]='%s'", link["href"], type(data))
242 if "error_message" not in data and "json" in data:
243 logger.debug("Found JSON data()=%d,link[href]='%s' - Setting detection_mode=AUTO_DISCOVERY ...", len(data), link["href"])
244 instances.set_detection_mode(domain, "AUTO_DISCOVERY")
245 instances.set_nodeinfo_url(domain, link["href"])
247 logger.debug("Marking domain='%s' as successfully handled - BREAK!", domain)
248 instances.set_success(domain)
251 logger.debug("Setting last error for domain='%s',data[]='%s'", domain, type(data))
252 instances.set_last_error(domain, data)
254 logger.debug("data()=%d", len(data))
255 if "error_message" not in data and "json" in data:
256 logger.debug("Auto-discovery successful: domain='%s' - BREAK!", domain)
258 elif "server" in infos:
259 logger.debug("Found infos[server][software]='%s'", infos["server"]["software"])
260 instances.set_detection_mode(domain, "AUTO_DISCOVERY")
261 instances.set_nodeinfo_url(domain, f"https://{domain}/.well-known/x-nodeinfo2")
263 logger.debug("Marking domain='%s' as successfully handled ...", domain)
264 instances.set_success(domain)
266 logger.warning("nodeinfo does not contain 'links' or 'server': domain='%s',infos[%s]='%s'", domain, type(infos), infos)
268 logger.debug("Returning data[]='%s' - EXIT!", type(data))