]> 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 import validators
18
19 from urllib.parse import urlparse
20
21 from fba.helpers import blacklist
22 from fba.helpers import config
23 from fba.helpers import domain as domain_helper
24
25 from fba.http import csrf
26 from fba.http import network
27
28 from fba.models import instances
29
30 logging.basicConfig(level=logging.INFO)
31 logger = logging.getLogger(__name__)
32
33 # Request paths
34 _request_paths = [
35     "/nodeinfo/2.1.json",
36     "/nodeinfo/2.1",
37     "/nodeinfo/2.0.json",
38     "/nodeinfo/2.0",
39     "/nodeinfo/1.0.json",
40     "/nodeinfo/1.0",
41     "/api/v1/instance",
42 ]
43
44 # "rel" identifiers (no real URLs)
45 _nodeinfo_identifier = [
46     "https://nodeinfo.diaspora.software/ns/schema/2.1",
47     "http://nodeinfo.diaspora.software/ns/schema/2.1",
48     "https://nodeinfo.diaspora.software/ns/schema/2.0",
49     "http://nodeinfo.diaspora.software/ns/schema/2.0",
50     "https://nodeinfo.diaspora.software/ns/schema/1.1",
51     "http://nodeinfo.diaspora.software/ns/schema/1.1",
52     "https://nodeinfo.diaspora.software/ns/schema/1.0",
53     "http://nodeinfo.diaspora.software/ns/schema/1.0",
54 ]
55
56 def fetch(domain: str, path: str = None, update_mode: bool = True) -> dict:
57     logger.debug("domain='%s',path='%s',update_mode='%s' - CALLED!", domain, path, update_mode)
58     domain_helper.raise_on(domain)
59
60     if blacklist.is_blacklisted(domain):
61         raise Exception(f"domain='{domain}' is blacklisted but function was invoked")
62     elif not isinstance(path, str) and path is not None:
63         raise ValueError(f"Parameter path[]='{type(path)}' is not of type 'str'")
64     elif path is not None and not path.startswith("/"):
65         raise ValueError(f"path='{path}' does not start with a slash")
66     elif not isinstance(update_mode, bool) and update_mode is not None:
67         raise ValueError(f"Parameter update_mode[]='{type(update_mode)}' is not of type 'bool'")
68
69     if path is None and update_mode:
70         logger.debug("Fetching well-known nodeinfo from domain='%s' ...", domain)
71         data = fetch_wellknown_nodeinfo(domain)
72
73         logger.debug("data[%s](%d)='%s'", type(data), len(data), data)
74         if "exception" in data:
75             logger.warning("Exception returned: '%s', raising again ...", type(data["exception"]))
76             raise data["exception"]
77         elif "error_message" not in data and "json" in data and len(data["json"]) > 0:
78             logger.debug("Invoking instances.set_last_nodeinfo(%s) ...", domain)
79             instances.set_last_nodeinfo(domain)
80
81             logger.debug("Found data[json]()=%d - EXIT!", len(data['json']))
82             return data
83
84     # No CSRF by default, you don't have to add network.api_headers by yourself here
85     headers = tuple()
86     data = dict()
87
88     try:
89         logger.debug("Checking CSRF for domain='%s'", domain)
90         headers = csrf.determine(domain, dict())
91         logger.debug("headers()=%d", len(headers))
92     except network.exceptions as exception:
93         logger.warning("Exception '%s' during checking CSRF (nodeinfo,%s) - EXIT!", type(exception), __name__)
94         instances.set_last_error(domain, exception)
95         return {
96             "status_code"  : 500,
97             "error_message": f"exception[{type(exception)}]='{str(exception)}'",
98             "exception"    : exception,
99         }
100
101     logger.debug("Checking %d request paths ...", len(_request_paths))
102     for request in _request_paths:
103         logger.debug("request='%s'", request)
104         http_url  = f"http://{domain}{str(path) if path is not None else '/'}"
105         https_url = f"https://{domain}{str(path) if path is not None else '/'}"
106
107         logger.debug("path[%s]='%s',request='%s',http_url='%s',https_url='%s'", type(path), path, request, http_url, https_url)
108         if path is None or path in [request, http_url, https_url]:
109             logger.debug("Fetching request='%s' from domain='%s' ...", request, domain)
110             data = network.get_json_api(
111                 domain,
112                 request,
113                 headers=headers,
114                 timeout=(config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
115             )
116
117             logger.debug("data(%d)[]='%s'", len(data), type(data))
118             if "error_message" not in data and "json" in data:
119                 logger.debug("Updating last_nodeinfo for domain='%s' ....", domain)
120                 instances.set_last_nodeinfo(domain)
121
122                 logger.debug("update_mode='%s'", update_mode)
123                 if update_mode:
124                     logger.debug("Success: request='%s' - Setting detection_mode=STATIC_CHECK for domain='%s' ...", request, domain)
125                     instances.set_detection_mode(domain, "STATIC_CHECK")
126
127                     logger.debug("domain='%s',request='%s'", domain, request)
128                     instances.set_nodeinfo_url(domain, f"https://{domain}{request}")
129
130                 logger.debug("BREAK!")
131                 break
132
133             logger.warning("Failed fetching nodeinfo from domain='%s',status_code='%s',error_message='%s'", domain, data['status_code'], data['error_message'])
134
135     logger.debug("data()=%d - EXIT!", len(data))
136     return data
137
138 def fetch_wellknown_nodeinfo(domain: str) -> dict:
139     logger.debug("domain='%s' - CALLED!", domain)
140     domain_helper.raise_on(domain)
141
142     if blacklist.is_blacklisted(domain):
143         raise Exception(f"domain='{domain}' is blacklisted but function was invoked")
144
145     # No CSRF by default, you don't have to add network.api_headers by yourself here
146     headers = tuple()
147
148     try:
149         logger.debug("Checking CSRF for domain='%s'", domain)
150         headers = csrf.determine(domain, dict())
151     except network.exceptions as exception:
152         logger.warning("Exception '%s' during checking CSRF (fetch_wellknown_nodeinfo,%s) - EXIT!", type(exception), __name__)
153         instances.set_last_error(domain, exception)
154         return {
155             "status_code"  : 500,
156             "error_message": type(exception),
157             "exception"    : exception,
158         }
159
160     data = dict()
161
162     logger.debug("Fetching .well-known info for domain='%s'", domain)
163     for path in ["/.well-known/x-nodeinfo2", "/.well-known/nodeinfo"]:
164         logger.debug("Fetching path='%s' from domain='%s' ...", path, domain)
165         data = network.get_json_api(
166             domain,
167             path,
168             headers,
169             (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
170         )
171
172         logger.debug("data(%d)[]='%s'", len(data), type(data))
173         if "error_message" not in data and "json" in data and len(data["json"]) > 0:
174             logger.debug("path='%s' returned valid json()=%d - BREAK!", path, len(data["json"]))
175             break
176
177     logger.debug("data[]='%s'", type(data))
178     if "exception" in data:
179         logger.warning("domain='%s' returned exception '%s' - RAISE!", domain, str(data["exception"]))
180         raise data["exception"]
181     elif "error_message" in data:
182         logger.warning("domain='%s' returned error message: '%s' - EXIT!", domain, data["error_message"])
183         return data
184     elif "json" not in data:
185         logger.warning("domain='%s' returned no 'json' key - EXIT!", domain)
186         return dict()
187
188     infos = data["json"]
189     logger.debug("infos(%d)[]='%s' has been returned", len(infos), type(infos))
190
191     if "links" in infos:
192         logger.debug("Marking domain='%s' as successfully handled ...", domain)
193         instances.set_success(domain)
194
195         logger.debug("Checking %d nodeinfo ids ...", len(_nodeinfo_identifier))
196         for niid in _nodeinfo_identifier:
197             data = dict()
198
199             logger.debug("Checking niid='%s' for infos[links]()=%d ...", niid, len(infos["links"]))
200             for link in infos["links"]:
201                 logger.debug("link[%s]='%s'", type(link), link)
202                 if not isinstance(link, dict) or not "rel" in link:
203                     logger.debug("link[]='%s' is not of type 'dict' or no element 'rel' found - SKIPPED!", type(link))
204                     continue
205                 elif link["rel"] != niid:
206                     logger.debug("link[re]='%s' does not matched niid='%s' - SKIPPED!", link["rel"], niid)
207                     continue
208                 elif "href" not in link:
209                     logger.warning("link[rel]='%s' has no element 'href' - SKIPPED!", link["rel"])
210                     continue
211                 elif link["href"] in [None, ""]:
212                     logger.debug("link[href]='%s' is empty, link[rel]='%s' - SKIPPED!", link["href"], link["rel"])
213                     continue
214                 elif not validators.url(link["href"]):
215                     logger.warning("link[href]='%s' is not a valid domain - SKIPPED!", link["href"])
216                     continue
217
218                 # Default is that 'href' has a complete URL, but some hosts don't send that
219                 logger.debug("link[rel]='%s' matches niid='%s'", link["rel"], niid)
220                 url = link["href"].lower()
221
222                 logger.debug("Parsing url='%s' ...", url)
223                 components = urlparse(url)
224
225                 logger.debug("components[%s]='%s'", type(components), components)
226                 if components.scheme == "" and components.netloc == "":
227                     logger.warning("link[href]='%s' has no scheme and host name in it, prepending from domain='%s'", link['href'], domain)
228                     url = f"https://{domain}{url}"
229                     components = urlparse(url)
230                 elif components.netloc == "":
231                     logger.warning("link[href]='%s' has no netloc set, setting domain='%s'", link["href"], domain)
232                     url = f"{components.scheme}://{domain}{components.path}"
233                     components = urlparse(url)
234
235                 domain2 = components.netloc.lower().split(":")[0]
236                 logger.debug("domain2='%s'", domain2)
237                 if not domain_helper.is_wanted(domain2):
238                     logger.debug("domain2='%s' is not wanted - SKIPPED!", domain2)
239                     continue
240
241                 logger.debug("Fetching nodeinfo from url='%s' ...", url)
242                 data = network.fetch_api_url(
243                     url,
244                     (config.get("connection_timeout"), config.get("read_timeout"))
245                  )
246
247                 logger.debug("link[href]='%s',data[]='%s'", link["href"], type(data))
248                 if "error_message" not in data and "json" in data:
249                     logger.debug("Found JSON data()=%d,link[href]='%s' - Setting detection_mode=AUTO_DISCOVERY ...", len(data), link["href"])
250                     instances.set_detection_mode(domain, "AUTO_DISCOVERY")
251                     instances.set_nodeinfo_url(domain, link["href"])
252
253                     logger.debug("Marking domain='%s' as successfully handled - BREAK!", domain)
254                     instances.set_success(domain)
255                     break
256                 else:
257                     logger.debug("Setting last error for domain='%s',data[]='%s'", domain, type(data))
258                     instances.set_last_error(domain, data)
259
260             logger.debug("data()=%d", len(data))
261             if "error_message" not in data and "json" in data:
262                 logger.debug("Auto-discovery successful: domain='%s' - BREAK!", domain)
263                 break
264     elif "server" in infos:
265         logger.debug("Found infos[server][software]='%s'", infos["server"]["software"])
266         instances.set_detection_mode(domain, "AUTO_DISCOVERY")
267         instances.set_nodeinfo_url(domain, f"https://{domain}/.well-known/x-nodeinfo2")
268
269         logger.debug("Marking domain='%s' as successfully handled ...", domain)
270         instances.set_success(domain)
271     else:
272         logger.warning("nodeinfo does not contain 'links' or 'server': domain='%s',infos[%s]='%s'", domain, type(infos), infos)
273
274     logger.debug("Returning data[]='%s' - EXIT!", type(data))
275     return data