]> 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 import csrf
22
23 from fba.helpers import config
24 from fba.helpers import domain as domain_helper
25
26 from fba.http import network
27
28 from fba.models import instances
29
30 _DEPTH = 0
31
32 logging.basicConfig(level=logging.INFO)
33 logger = logging.getLogger(__name__)
34
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)
38
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'")
43
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)
46
47     logger.debug("is_url='%s'", is_url)
48     if not is_url:
49         logger.debug("Fetching well-known nodeinfo from domain='%s' ...", domain)
50         data = fetch_wellknown_nodeinfo(domain)
51
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)
59
60             logger.debug("Found data[json]()=%d - EXIT!", len(data['json']))
61             return data
62
63     # No CSRF by default, you don't have to add network.api_headers by yourself here
64     headers = tuple()
65     data = dict()
66
67     try:
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)
73         return {
74             "status_code"  : 500,
75             "error_message": f"exception[{type(exception)}]='{str(exception)}'",
76             "exception"    : exception,
77         }
78
79     request_paths = [
80        "/nodeinfo/2.1.json",
81        "/nodeinfo/2.1",
82        "/nodeinfo/2.0.json",
83        "/nodeinfo/2.0",
84        "/nodeinfo/1.0.json",
85        "/nodeinfo/1.0",
86        "/api/v1/instance",
87     ]
88
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 '/'}"
93
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(
98                 domain,
99                 request,
100                 headers,
101                 (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
102             )
103
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}")
110                 break
111
112             logger.warning("Failed fetching nodeinfo from domain='%s',status_code='%s',error_message='%s'", domain, data['status_code'], data['error_message'])
113
114     logger.debug("data()=%d - EXIT!", len(data))
115     return data
116
117 def fetch_wellknown_nodeinfo(domain: str) -> dict:
118     logger.debug("domain='%s' - CALLED!", domain)
119     domain_helper.raise_on(domain)
120
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",
131     ]
132
133     # No CSRF by default, you don't have to add network.api_headers by yourself here
134     headers = tuple()
135
136     try:
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)
142         return {
143             "status_code"  : 500,
144             "error_message": type(exception),
145             "exception"    : exception,
146         }
147
148     data = dict()
149
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(
154             domain,
155             path,
156             headers,
157             (config.get("nodeinfo_connection_timeout"), config.get("nodeinfo_read_timeout"))
158         )
159         logger.debug("data[]='%s'", type(data))
160
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"]))
163             break
164
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"])
171         return data
172     elif "json" not in data:
173         logger.warning("domain='%s' returned no 'json' key", domain)
174         return dict()
175
176     infos = data["json"]
177     logger.debug("infos()=%d has been returned", len(infos))
178
179     if "links" in infos:
180         logger.debug("Marking domain='%s' as successfully handled ...", domain)
181         instances.set_success(domain)
182
183         logger.debug("Found infos[links]()=%d record(s),", len(infos["links"]))
184         for niid in nodeinfo_identifier:
185             data = dict()
186
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))
192                     continue
193                 elif link["rel"] != niid:
194                     logger.debug("link[re]='%s' does not matched niid='%s' - SKIPPED!", link["rel"], niid)
195                     continue
196                 elif "href" not in link:
197                     logger.warning("link[rel]='%s' has no element 'href' - SKIPPED!", link["rel"])
198                     continue
199                 elif link["href"] is None:
200                     logger.debug("link[href] is None, link[rel]='%s' - SKIPPED!", link["rel"])
201                     continue
202
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)
205                 url = link["href"]
206                 components = urlparse(url)
207
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)
217
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)
221                     continue
222
223                 logger.debug("Fetching nodeinfo from url='%s' ...", url)
224                 data = network.fetch_api_url(
225                     url,
226                     (config.get("connection_timeout"), config.get("read_timeout"))
227                  )
228
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"])
234
235                     logger.debug("Marking domain='%s' as successfully handled ...", domain)
236                     instances.set_success(domain)
237                     break
238                 else:
239                     logger.debug("Setting last error for domain='%s',data[]='%s'", domain, type(data))
240                     instances.set_last_error(domain, data)
241
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)
245                 break
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")
250
251         logger.debug("Marking domain='%s' as successfully handled ...", domain)
252         instances.set_success(domain)
253     else:
254         logger.warning("nodeinfo does not contain 'links' or 'server': domain='%s'", domain)
255
256     logger.debug("Returning data[]='%s' - EXIT!", type(data))
257     return data