]> git.mxchange.org Git - fba.git/blob - fba/http/nodeinfo.py
Continued:
[fba.git] / fba / http / nodeinfo.py
1 # Copyright (C) 2023 Free Software Foundation
2 #
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.
7 #
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.
12 #
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/>.
15
16 import logging
17
18 from urllib.parse import urlparse
19
20 from fba.helpers import blacklist
21 from fba.helpers import config
22 from fba.helpers import domain as domain_helper
23
24 from fba.http import csrf
25 from fba.http import network
26
27 from fba.models import instances
28
29 logging.basicConfig(level=logging.INFO)
30 logger = logging.getLogger(__name__)
31
32 # Request paths
33 _request_paths = [
34     "/nodeinfo/2.1.json",
35     "/nodeinfo/2.1",
36     "/nodeinfo/2.0.json",
37     "/nodeinfo/2.0",
38     "/nodeinfo/1.0.json",
39     "/nodeinfo/1.0",
40     "/api/v1/instance",
41 ]
42
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",
53 ]
54
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)
58
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'")
67
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)
71
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)
79
80             logger.debug("Found data[json]()=%d - EXIT!", len(data['json']))
81             return data
82
83     # No CSRF by default, you don't have to add network.api_headers by yourself here
84     headers = tuple()
85     data = dict()
86
87     try:
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)
94         return {
95             "status_code"  : 500,
96             "error_message": f"exception[{type(exception)}]='{str(exception)}'",
97             "exception"    : exception,
98         }
99
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 '/'}"
105
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(
110                 domain,
111                 request,
112                 headers=headers,
113                 timeout=(config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
114             )
115
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)
120
121                 logger.debug("update_mode='%s'", update_mode)
122                 if 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")
125
126                     logger.debug("domain='%s',request='%s'", domain, request)
127                     instances.set_nodeinfo_url(domain, "https://{domain}{request}")
128
129                 logger.debug("BREAK!")
130                 break
131
132             logger.warning("Failed fetching nodeinfo from domain='%s',status_code='%s',error_message='%s'", domain, data['status_code'], data['error_message'])
133
134     logger.debug("data()=%d - EXIT!", len(data))
135     return data
136
137 def fetch_wellknown_nodeinfo(domain: str) -> dict:
138     logger.debug("domain='%s' - CALLED!", domain)
139     domain_helper.raise_on(domain)
140
141     if blacklist.is_blacklisted(domain):
142         raise Exception(f"domain='{domain}' is blacklisted but function was invoked")
143
144     # No CSRF by default, you don't have to add network.api_headers by yourself here
145     headers = tuple()
146
147     try:
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)
153         return {
154             "status_code"  : 500,
155             "error_message": type(exception),
156             "exception"    : exception,
157         }
158
159     data = dict()
160
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(
165             domain,
166             path,
167             headers,
168             (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
169         )
170
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"]))
174             break
175
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"])
182         return data
183     elif "json" not in data:
184         logger.warning("domain='%s' returned no 'json' key - EXIT!", domain)
185         return dict()
186
187     infos = data["json"]
188     logger.debug("infos(%d)[]='%s' has been returned", len(infos), type(infos))
189
190     if "links" in infos:
191         logger.debug("Marking domain='%s' as successfully handled ...", domain)
192         instances.set_success(domain)
193
194         logger.debug("Found infos[links]()=%d record(s),", len(infos["links"]))
195         for niid in _nodeinfo_identifier:
196             data = dict()
197
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))
203                     continue
204                 elif link["rel"] != niid:
205                     logger.debug("link[re]='%s' does not matched niid='%s' - SKIPPED!", link["rel"], niid)
206                     continue
207                 elif "href" not in link:
208                     logger.warning("link[rel]='%s' has no element 'href' - SKIPPED!", link["rel"])
209                     continue
210                 elif link["href"] is None or link["href"] == "":
211                     logger.debug("link[href]='%s',link[rel]='%s' - SKIPPED!", link["href"], link["rel"])
212                     continue
213
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)
218
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)
228
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)
233                     continue
234
235                 logger.debug("Fetching nodeinfo from url='%s' ...", url)
236                 data = network.fetch_api_url(
237                     url,
238                     (config.get("connection_timeout"), config.get("read_timeout"))
239                  )
240
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"])
246
247                     logger.debug("Marking domain='%s' as successfully handled - BREAK!", domain)
248                     instances.set_success(domain)
249                     break
250                 else:
251                     logger.debug("Setting last error for domain='%s',data[]='%s'", domain, type(data))
252                     instances.set_last_error(domain, data)
253
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)
257                 break
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")
262
263         logger.debug("Marking domain='%s' as successfully handled ...", domain)
264         instances.set_success(domain)
265     else:
266         logger.warning("nodeinfo does not contain 'links' or 'server': domain='%s',infos[%s]='%s'", domain, type(infos), infos)
267
268     logger.debug("Returning data[]='%s' - EXIT!", type(data))
269     return data