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