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