1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published
6 # by the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <https://www.gnu.org/licenses/>.
20 from fba import blacklist
21 from fba import blocks
22 from fba import config
24 from fba import instances
28 "Silenced instances" : "Silenced servers",
29 "Suspended instances" : "Suspended servers",
30 "Limited instances" : "Limited servers",
31 "Filtered media" : "Filtered media",
32 # Mappuing German -> English
33 "Gesperrte Server" : "Suspended servers",
34 "Gefilterte Medien" : "Filtered media",
35 "Stummgeschaltete Server" : "Silenced servers",
37 "停止済みのサーバー" : "Suspended servers",
38 "制限中のサーバー" : "Limited servers",
39 "メディアを拒否しているサーバー": "Filtered media",
40 "サイレンス済みのサーバー" : "Silenced servers",
42 "שרתים מושעים" : "Suspended servers",
43 "מדיה מסוננת" : "Filtered media",
44 "שרתים מוגבלים" : "Silenced servers",
46 "Serveurs suspendus" : "Suspended servers",
47 "Médias filtrés" : "Filtered media",
48 "Serveurs limités" : "Limited servers",
49 "Serveurs modérés" : "Limited servers",
52 def fetch_blocks_from_about(domain: str) -> dict:
53 # DEBUG: print(f"DEBUG: domain='{domain}' - CALLED!")
54 if type(domain) != str:
55 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
57 raise ValueError(f"Parameter 'domain' is empty")
59 # DEBUG: print("DEBUG: Fetching mastodon blocks from domain:", domain)
61 "Suspended servers": [],
62 "Filtered media" : [],
63 "Limited servers" : [],
64 "Silenced servers" : [],
68 doc = bs4.BeautifulSoup(
69 fba.get_response(domain, "/about/more", fba.headers, (config.get("connection_timeout"), config.get("read_timeout"))).text,
72 except BaseException as e:
73 print("ERROR: Cannot fetch from domain:", domain, e)
74 fba.update_last_error(domain, e)
77 for header in doc.find_all("h3"):
78 header_text = fba.tidyup_reason(header.text)
80 # DEBUG: print(f"DEBUG: header_text='{header_text}'")
81 if header_text in language_mapping:
82 # DEBUG: print(f"DEBUG: header_text='{header_text}'")
83 header_text = language_mapping[header_text]
85 print(f"WARNING: header_text='{header_text}' not found in language mapping table")
87 if header_text in blocklist or header_text.lower() in blocklist:
88 # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
89 for line in header.find_all_next("table")[0].find_all("tr")[1:]:
90 blocklist[header_text].append(
92 "domain": fba.tidyup_domain(line.find("span").text),
93 "hash" : fba.tidyup_domain(line.find("span")["title"][9:]),
94 "reason": fba.tidyup_domain(line.find_all("td")[1].text),
98 print(f"WARNING: header_text='{header_text}' not found in blocklist()={len(blocklist)}")
100 # DEBUG: print("DEBUG: Returning blocklist for domain:", domain)
102 "reject" : blocklist["Suspended servers"],
103 "media_removal" : blocklist["Filtered media"],
104 "followers_only": blocklist["Limited servers"] + blocklist["Silenced servers"],
107 def fetch_blocks(domain: str, origin: str, nodeinfo_url: str):
108 print(f"DEBUG: domain='{domain}',origin='{origin}',nodeinfo_url='{nodeinfo_url}' - CALLED!")
109 if type(domain) != str:
110 raise ValueError(f"Parameter domain[]={type(domain)} is not 'str'")
112 raise ValueError(f"Parameter 'domain' is empty")
113 elif type(origin) != str and origin != None:
114 raise ValueError(f"Parameter origin[]={type(origin)} is not 'str'")
116 raise ValueError(f"Parameter 'origin' is empty")
117 elif type(nodeinfo_url) != str:
118 raise ValueError(f"Parameter nodeinfo_url[]={type(nodeinfo_url)} is not 'str'")
119 elif nodeinfo_url == "":
120 raise ValueError(f"Parameter 'nodeinfo_url' is empty")
123 # json endpoint for newer mastodongs
128 "media_removal" : [],
129 "followers_only": [],
133 # handling CSRF, I've saw at least one server requiring it to access the endpoint
134 # DEBUG: print("DEBUG: Fetching meta:", domain)
135 meta = bs4.BeautifulSoup(
136 fba.get_response(domain, "/", fba.headers, (config.get("connection_timeout"), config.get("read_timeout"))).text,
140 csrf = meta.find("meta", attrs={"name": "csrf-token"})["content"]
141 # DEBUG: print("DEBUG: Adding CSRF token:", domain, csrf)
142 reqheaders = {**fba.api_headers, **{"X-CSRF-Token": csrf}}
143 except BaseException as e:
144 # DEBUG: print("DEBUG: No CSRF token found, using normal headers:", domain, e)
145 reqheaders = fba.api_headers
147 # DEBUG: print("DEBUG: Querying API domain_blocks:", domain)
148 blocklist = fba.get_response(domain, "/api/v1/instance/domain_blocks", reqheaders, (config.get("connection_timeout"), config.get("read_timeout"))).json()
150 print(f"INFO: Checking {len(blocklist)} entries from domain='{domain}',software='mastodon' ...")
151 for block in blocklist:
153 'domain': block['domain'],
154 'hash' : block['digest'],
155 'reason': block['comment']
158 # DEBUG: print("DEBUG: severity,domain,hash,comment:", block['severity'], block['domain'], block['digest'], block['comment'])
159 if block['severity'] == 'suspend':
160 # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
161 json['reject'].append(entry)
162 elif block['severity'] == 'silence':
163 # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
164 json['followers_only'].append(entry)
165 elif block['severity'] == 'reject_media':
166 # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
167 json['media_removal'].append(entry)
168 elif block['severity'] == 'reject_reports':
169 # DEBUG: print(f"DEBUG: Adding entry='{entry}' with severity='{block['severity']}' ...")
170 json['report_removal'].append(entry)
172 print("WARNING: Unknown severity:", block['severity'], block['domain'])
174 except BaseException as e:
175 # DEBUG: print(f"DEBUG: Failed, trying mastodon-specific fetches: domain='{domain}',exception[{type(e)}]={str(e)}")
176 json = fetch_blocks_from_about(domain)
178 print(f"INFO: Checking {len(json.items())} entries from domain='{domain}',software='mastodon' ...")
179 for block_level, blocklist in json.items():
180 # DEBUG: print("DEBUG: domain,block_level,blocklist():", domain, block_level, len(blocklist))
181 block_level = fba.tidyup_domain(block_level)
183 # DEBUG: print("DEBUG: AFTER-block_level:", block_level)
184 if block_level == "":
185 print("WARNING: block_level is empty, domain:", domain)
188 # DEBUG: print(f"DEBUG: Checking {len(blocklist)} entries from domain='{domain}',software='mastodon',block_level='{block_level}' ...")
189 for block in blocklist:
190 blocked, blocked_hash, reason = block.values()
191 # DEBUG: print("DEBUG: blocked,hash,reason:", blocked, blocked_hash, reason)
192 blocked = fba.tidyup_domain(blocked)
193 # DEBUG: print("DEBUG: AFTER-blocked:", blocked)
196 print("WARNING: blocked is empty:", domain)
198 elif blacklist.is_blacklisted(blocked):
199 # DEBUG: print(f"DEBUG: blocked='{blocked}' is blacklisted - skipping!")
201 elif blocked.count("*") > 0:
202 # Doing the hash search for instance names as well to tidy up DB
204 "SELECT domain, origin, nodeinfo_url FROM instances WHERE hash = ? LIMIT 1", [blocked_hash]
206 searchres = fba.cursor.fetchone()
208 if searchres == None:
209 print(f"WARNING: Cannot deobsfucate blocked='{blocked}',blocked_hash='{blocked_hash}' - SKIPPED!")
212 # DEBUG: print("DEBUG: Updating domain: ", searchres[0])
213 blocked = searchres[0]
214 origin = searchres[1]
215 nodeinfo_url = searchres[2]
217 # DEBUG: print("DEBUG: Looking up instance by domain:", blocked)
218 if not validators.domain(blocked):
219 print(f"WARNING: blocked='{blocked}',software='mastodon' is not a valid domain name - skipped!")
221 elif not instances.is_registered(blocked):
222 # DEBUG: print(f"DEBUG: Domain blocked='{blocked}' wasn't found, adding ..., domain='{domain}',origin='{origin}',nodeinfo_url='{nodeinfo_url}'")
223 instances.add(blocked, domain, inspect.currentframe().f_code.co_name, nodeinfo_url)
224 elif not validators.domain(blocked):
225 print(f"WARNING: blocked='{blocked}',software='mastodon' is not a valid domain name - skipped!")
228 # DEBUG: print("DEBUG: Looking up instance by domain:", blocked)
229 if not validators.domain(blocked):
230 print(f"WARNING: blocked='{blocked}',software='mastodon' is not a valid domain name - skipped!")
232 elif not instances.is_registered(blocked):
233 # DEBUG: print("DEBUG: Hash wasn't found, adding:", blocked, domain)
234 instances.add(blocked, domain, inspect.currentframe().f_code.co_name, nodeinfo_url)
236 blocking = blocked if blocked.count("*") <= 1 else blocked_hash
237 # DEBUG: print(f"DEBUG: blocking='{blocking}',blocked='{blocked}',blocked_hash='{blocked_hash}'")
239 if not blocks.is_instance_blocked(domain, blocked, block_level):
240 # DEBUG: print("DEBUG: Blocking:", domain, blocked, block_level)
241 blocks.add_instance(domain, blocking, reason, block_level)
243 if block_level == "reject":
249 # DEBUG: print(f"DEBUG: Updating block last seen and reason for domain='{domain}',blocking='{blocking}' ...")
250 blocks.update_last_seen(domain, blocking, block_level)
251 blocks.update_reason(reason, domain, blocking, block_level)
253 # DEBUG: print("DEBUG: Committing changes ...")
254 fba.connection.commit()
255 except Exception as e:
256 print(f"ERROR: domain='{domain}',software='mastodon',exception[{type(e)}]:'{str(e)}'")
258 # DEBUG: print("DEBUG: EXIT!")