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/>.
25 "SELECT domain, software FROM instances WHERE software IN ('pleroma', 'mastodon', 'friendica', 'misskey', 'gotosocial', 'bookwyrm', 'takahe') AND (last_blocked IS NULL OR last_blocked < ?) ORDER BY rowid DESC", [time.time() - fba.config["recheck_block"]]
28 rows = fba.cursor.fetchall()
29 print(f"INFO: Checking {len(rows)} entries ...")
30 for blocker, software in rows:
31 # NOISY-DEBUG: print("DEBUG: BEFORE blocker,software:", blocker, software)
33 blocker = fba.tidyup(blocker)
34 # NOISY-DEBUG: print("DEBUG: AFTER blocker,software:", blocker, software)
37 print("WARNING: blocker is now empty!")
39 elif fba.is_blacklisted(blocker):
40 print(f"WARNING: blocker='{blocker}' is blacklisted now!")
43 # NOISY-DEBUG: print(f"DEBUG: blocker='{blocker}'")
44 fba.update_last_blocked(blocker)
46 if software == "pleroma":
47 print("INFO: blocker:", blocker)
50 json = fba.fetch_nodeinfo(blocker)
52 print("WARNING: Could not fetch nodeinfo from blocker:", blocker)
55 print("DEBUG: Updating nodeinfo:", blocker)
56 fba.update_last_nodeinfo(blocker)
58 federation = json["metadata"]["federation"]
60 if "enabled" in federation:
61 # NOISY-DEBUG: print("DEBUG: Instance has no block list to analyze:", blocker)
64 if "mrf_simple" in federation:
65 for block_level, blocks in (
66 {**federation["mrf_simple"],
67 **{"quarantined_instances": federation["quarantined_instances"]}}
69 # NOISY-DEBUG: print("DEBUG: block_level, blocks():", block_level, len(blocks))
70 block_level = fba.tidyup(block_level)
71 # NOISY-DEBUG: print("DEBUG: BEFORE block_level:", block_level)
74 print("WARNING: block_level is now empty!")
77 for blocked in blocks:
78 # NOISY-DEBUG: print("DEBUG: BEFORE blocked:", blocked)
79 blocked = fba.tidyup(blocked)
80 # NOISY-DEBUG: print("DEBUG: AFTER blocked:", blocked)
83 print("WARNING: blocked is empty after fba.tidyup():", blocker, block_level)
86 if blocked.count("*") > 1:
87 # -ACK!-oma also started obscuring domains without hash
89 "SELECT domain FROM instances WHERE domain LIKE ? ORDER BY rowid LIMIT 1", [blocked.replace("*", "_")]
91 searchres = fba.cursor.fetchone()
92 # NOISY-DEBUG: print("DEBUG: searchres[]:", type(searchres))
94 blocked = searchres[0]
95 # NOISY-DEBUG: print("DEBUG: Looked up domain:", blocked)
97 # NOISY-DEBUG: print("DEBUG: Looking up instance by domain:", blocked)
98 if not fba.is_instance_registered(blocked):
99 # NOISY-DEBUG: print("DEBUG: Domain wasn't found, adding:", blocked, blocker)
100 fba.add_instance(blocked, blocker, argv[0])
103 "SELECT * FROM blocks WHERE blocker = ? AND blocked = ? AND block_level = ? LIMIT 1",
111 if fba.cursor.fetchone() == None:
112 # NOISY-DEBUG: print("DEBUG: Blocking:", blocker, blocked, block_level)
113 fba.block_instance(blocker, blocked, "unknown", block_level)
115 if block_level == "reject":
116 # NOISY-DEBUG: print("DEBUG: Adding to blockdict:", blocked)
123 # NOISY-DEBUG: print("DEBUG: Updating last_seen:", blocker, blocked, block_level)
124 fba.update_last_seen(blocker, blocked, block_level)
126 fba.connection.commit()
129 if "mrf_simple_info" in federation:
130 # NOISY-DEBUG: print("DEBUG: Found mrf_simple_info:", blocker)
131 for block_level, info in (
132 {**federation["mrf_simple_info"],
133 **(federation["quarantined_instances_info"]
134 if "quarantined_instances_info" in federation
137 # NOISY-DEBUG: print("DEBUG: block_level, info.items():", block_level, len(info.items()))
138 block_level = fba.tidyup(block_level)
139 # NOISY-DEBUG: print("DEBUG: BEFORE block_level:", block_level)
141 if block_level == "":
142 print("WARNING: block_level is now empty!")
145 for blocked, reason in info.items():
146 # NOISY-DEBUG: print("DEBUG: BEFORE blocked:", blocked)
147 blocked = fba.tidyup(blocked)
148 # NOISY-DEBUG: print("DEBUG: AFTER blocked:", blocked)
151 print("WARNING: blocked is empty after fba.tidyup():", blocker, block_level)
153 elif blocked.count("*") > 1:
154 # same domain guess as above, but for reasons field
156 "SELECT domain FROM instances WHERE domain LIKE ? ORDER BY rowid LIMIT 1", [blocked.replace("*", "_")]
158 searchres = fba.cursor.fetchone()
160 if searchres != None:
161 blocked = searchres[0]
163 # NOISY-DEBUG: print("DEBUG: Updating block reason:", blocker, blocked, reason["reason"])
164 fba.update_block_reason(reason["reason"], blocker, blocked, block_level)
166 for entry in blockdict:
167 if entry["blocked"] == blocked:
168 # NOISY-DEBUG: print("DEBUG: Updating entry reason:", blocked)
169 entry["reason"] = reason["reason"]
171 fba.connection.commit()
172 except Exception as e:
173 print(f"ERROR: blocker='{blocker}',software='{software}',exception='{str(e)}'")
174 elif software == "mastodon":
175 print("INFO: blocker:", blocker)
177 # json endpoint for newer mastodongs
182 "followers_only": [],
186 # handling CSRF, I've saw at least one server requiring it to access the endpoint
187 # NOISY-DEBUG: print("DEBUG: Fetching meta:", blocker)
188 meta = bs4.BeautifulSoup(
189 reqto.get(f"https://{blocker}/about", headers=fba.headers, timeout=(fba.config["connection_timeout"], config["read_timeout"])).text,
193 csrf = meta.find("meta", attrs={"name": "csrf-token"})["content"]
194 # NOISY-DEBUG: print("DEBUG: Adding CSRF token:", blocker, csrf)
195 reqheaders = {**fba.api_headers, **{"X-CSRF-Token": csrf}}
197 # NOISY-DEBUG: print("DEBUG: No CSRF token found, using normal headers:", blocker)
198 reqheaders = fba.api_headers
200 # NOISY-DEBUG: print("DEBUG: Quering API domain_blocks:", blocker)
201 blocks = reqto.get(f"https://{blocker}/api/v1/instance/domain_blocks", headers=reqheaders, timeout=(fba.config["connection_timeout"], config["read_timeout"])).json()
203 # NOISY-DEBUG: print("DEBUG: blocks():", len(blocks))
206 'domain': block['domain'],
207 'hash': block['digest'],
208 'reason': block['comment']
211 # NOISY-DEBUG: print("DEBUG: severity,domain,hash,comment:", block['severity'], block['domain'], block['digest'], block['comment'])
212 if block['severity'] == 'suspend':
213 json['reject'].append(entry)
214 elif block['severity'] == 'silence':
215 json['followers_only'].append(entry)
216 elif block['severity'] == 'reject_media':
217 json['media_removal'].append(entry)
218 elif block['severity'] == 'reject_reports':
219 json['report_removal'].append(entry)
221 print("WARNING: Unknown severity:", block['severity'], block['domain'])
223 # NOISY-DEBUG: print("DEBUG: Failed, Trying mastodon-specific fetches:", blocker)
224 json = fba.get_mastodon_blocks(blocker)
226 # NOISY-DEBUG: print("DEBUG: json.items():", blocker, len(json.items()))
227 for block_level, blocks in json.items():
228 # NOISY-DEBUG: print("DEBUG: blocker,block_level,blocks():", blocker, block_level, len(blocks))
229 block_level = fba.tidyup(block_level)
230 # NOISY-DEBUG: print("DEBUG: AFTER-block_level:", block_level)
231 if block_level == "":
232 print("WARNING: block_level is empty, blocker:", blocker)
235 for instance in blocks:
236 blocked, blocked_hash, reason = instance.values()
237 # NOISY-DEBUG: print("DEBUG: blocked,hash,reason:", blocked, blocked_hash, reason)
238 blocked = fba.tidyup(blocked)
239 # NOISY-DEBUG: print("DEBUG: AFTER-blocked:", blocked)
242 print("WARNING: blocked is empty:", blocker)
244 elif blocked.count("*") < 1:
245 # No obsfucation for this instance
247 "SELECT hash FROM instances WHERE domain = ? LIMIT 1", [blocked]
250 if fba.cursor.fetchone() == None:
251 # NOISY-DEBUG: print("DEBUG: Hash wasn't found, adding:", blocked, blocker)
252 fba.add_instance(blocked, blocker, argv[0])
254 # Doing the hash search for instance names as well to tidy up DB
256 "SELECT domain FROM instances WHERE hash = ? LIMIT 1", [blocked_hash]
258 searchres = fba.cursor.fetchone()
260 if searchres != None:
261 # NOISY-DEBUG: print("DEBUG: Updating domain: ", searchres[0])
262 blocked = searchres[0]
265 "SELECT * FROM blocks WHERE blocker = ? AND blocked = ? AND block_level = ? LIMIT 1",
268 blocked if blocked.count("*") <= 1 else blocked_hash,
273 if fba.cursor.fetchone() == None:
274 fba.block_instance(blocker, blocked if blocked.count("*") <= 1 else blocked_hash, reason, block_level)
276 if block_level == "reject":
283 fba.update_last_seen(blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level)
286 # NOISY-DEBUG: print("DEBUG: Updating block reason:", blocker, blocked, reason)
287 fba.update_block_reason(reason, blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level)
289 fba.connection.commit()
290 except Exception as e:
291 print(f"ERROR: blocker='{blocker}',software='{software}',exception='{str(e)}'")
292 elif software == "friendica" or software == "misskey" or software == "bookwyrm" or software == "takahe":
293 print("INFO: blocker:", blocker)
295 if software == "friendica":
296 json = fba.get_friendica_blocks(blocker)
297 elif software == "misskey":
298 json = fba.get_misskey_blocks(blocker)
299 elif software == "bookwyrm":
300 print("WARNING: bookwyrm is not fully supported for fetching blacklist!", blocker)
301 #json = fba.get_bookwyrm_blocks(blocker)
302 elif software == "takahe":
303 print("WARNING: takahe is not fully supported for fetching blacklist!", blocker)
304 #json = fba.get_takahe_blocks(blocker)
306 for block_level, blocks in json.items():
307 # NOISY-DEBUG: print("DEBUG: blocker,block_level,blocks():", blocker, block_level, len(blocks))
308 block_level = fba.tidyup(block_level)
309 # NOISY-DEBUG: print("DEBUG: AFTER-block_level:", block_level)
310 if block_level == "":
311 print("WARNING: block_level is empty, blocker:", blocker)
314 for instance in blocks:
315 blocked, reason = instance.values()
316 # NOISY-DEBUG: print("DEBUG: BEFORE blocked:", blocked)
317 blocked = fba.tidyup(blocked)
318 # NOISY-DEBUG: print("DEBUG: AFTER blocked:", blocked)
321 print("WARNING: blocked is empty:", blocker)
323 if blocked.count("*") > 0:
324 # Some friendica servers also obscure domains without hash
326 "SELECT domain FROM instances WHERE domain LIKE ? ORDER BY rowid LIMIT 1", [blocked.replace("*", "_")]
328 searchres = fba.cursor.fetchone()
329 if searchres != None:
330 blocked = searchres[0]
332 if blocked.count("?") > 0:
333 # Some obscure them with question marks, not sure if that's dependent on version or not
335 "SELECT domain FROM instances WHERE domain LIKE ? ORDER BY rowid LIMIT 1", [blocked.replace("?", "_")]
337 searchres = fba.cursor.fetchone()
338 if searchres != None:
339 blocked = searchres[0]
341 # NOISY-DEBUG: print("DEBUG: AFTER-blocked:", blocked)
342 if not fba.is_instance_registered(blocked):
343 # NOISY-DEBUG: print("DEBUG: Hash wasn't found, adding:", blocked, blocker)
344 fba.add_instance(blocked, blocker)
347 "SELECT * FROM blocks WHERE blocker = ? AND blocked = ?",
351 if fba.cursor.fetchone() == None:
352 fba.block_instance(blocker, blocked, reason, block_level)
354 if block_level == "reject":
361 fba.update_last_seen(blocker, blocked, block_level)
364 # NOISY-DEBUG: print("DEBUG: Updating block reason:", blocker, blocked, reason)
365 fba.update_block_reason(reason, blocker, blocked, block_level)
367 fba.connection.commit()
368 except Exception as e:
369 print(f"ERROR: blocker='{blocker}',software='{software}',exception='{str(e)}'")
370 elif software == "gotosocial":
371 print("INFO: blocker:", blocker)
374 federation = reqto.get(f"https://{blocker}{get_peers_url}?filter=suspended", headers=fba.api_headers, timeout=(fba.config["connection_timeout"], config["read_timeout"])).json()
376 if (federation == None):
377 print("WARNING: No valid response:", blocker);
378 elif "error" in federation:
379 print("WARNING: API returned error:", federation["error"])
381 # NOISY-DEBUG: print("DEBUG: Checking fenderation():", len(federation))
382 for peer in federation:
383 blocked = peer["domain"].lower()
384 # NOISY-DEBUG: print("DEBUG: BEFORE blocked:", blocked)
385 blocked = fba.tidyup(blocked)
386 # NOISY-DEBUG: print("DEBUG: AFTER blocked:", blocked)
389 print("WARNING: blocked is empty:", blocker)
391 elif blocked.count("*") > 0:
392 # GTS does not have hashes for obscured domains, so we have to guess it
394 "SELECT domain FROM instances WHERE domain LIKE ? ORDER BY rowid LIMIT 1", [blocked.replace("*", "_")]
396 searchres = fba.cursor.fetchone()
398 if searchres != None:
399 blocked = searchres[0]
401 if not fba.is_instance_registered(blocked):
402 # NOISY-DEBUG: print("DEBUG: Domain wasn't found, adding:", blocked, blocker)
403 fba.add_instance(blocked, blocker)
406 "SELECT * FROM blocks WHERE blocker = ? AND blocked = ? AND block_level = ? LIMIT 1",
414 if fba.cursor.fetchone() == None:
415 # NOISY-DEBUG: print(f"DEBUG: blocker='{blocker}' is blocking '{blocked}' for unknown reason at this point")
416 fba.block_instance(blocker, blocked, "unknown", "reject")
424 fba.update_last_seen(blocker, blocked, "reject")
426 if "public_comment" in peer:
427 # NOISY-DEBUG: print("DEBUG: Updating block reason:", blocker, blocked, peer["public_comment"])
428 fba.update_block_reason(peer["public_comment"], blocker, blocked, "reject")
430 for entry in blockdict:
431 if entry["blocked"] == blocked:
432 # NOISY-DEBUG: print(f"DEBUG: Setting block reason for blocked='{blocked}':'{peer['public_comment']}'")
433 entry["reason"] = peer["public_comment"]
435 fba.connection.commit()
436 except Exception as e:
437 print(f"ERROR: blocker='{blocker}',software='{software}',exception='{str(e)}'")
439 print("WARNING: Unknown software:", blocker, software)
441 if fba.config["bot_enabled"] and len(blockdict) > 0:
442 send_bot_post(blocker, blockdict)
446 fba.connection.close()