// Zweite Prüfung aller Websites, die der erste Abruf nicht eindeutig als Gemeindeseite bestätigt hat. // Lädt die Startseite des Zielhosts und höchstens eine Impressum- oder Kontaktseite. Beachtet robots.txt. // Es wird kein Seiteninhalt gespeichert. Ergebnis: daten/nachpruefung.jsonl import dnsCb from 'node:dns'; import { appendFileSync, existsSync, readFileSync } from 'node:fs'; import http from 'node:http'; import https from 'node:https'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import zlib from 'node:zlib'; const hier = dirname(fileURLToPath(import.meta.url)); const pfad = (d) => join(hier, 'daten', d); const jsonl = (d) => (existsSync(pfad(d)) ? readFileSync(pfad(d), 'utf8').trim().split('\n').filter(Boolean).map((z) => JSON.parse(z)) : []); const UA = 'Mozilla/5.0 (compatible; municipal-hosting-study/1.0)'; const MAX = 512 * 1024; setTimeout(() => process.exit(3), 60 * 60 * 1000).unref(); function privat(ip) { const a = ip.toLowerCase().replace(/^::ffff:/, ''); if (a.includes(':')) return a === '::1' || a === '::' || /^f[cd]/.test(a) || /^fe[89ab]/.test(a); const [x, y] = a.split('.').map(Number); return x === 0 || x === 10 || x === 127 || (x === 169 && y === 254) || (x === 172 && y >= 16 && y <= 31) || (x === 192 && y === 168) || (x === 100 && y >= 64 && y <= 127) || x >= 224; } function suche(host, o, cb) { dnsCb.lookup(host, { all: true }, (e, l) => { if (e) return cb(e); const gut = l.filter((a) => !privat(a.address)); if (!gut.length) return cb(Object.assign(new Error('PRIVATE_IP'), { code: 'PRIVATE_IP' })); return o?.all ? cb(null, gut) : cb(null, gut[0].address, gut[0].family); }); } function hole(url, grenze = MAX) { return new Promise((fertig) => { let u; try { u = new URL(url); } catch { return fertig({ fehler: 'URL' }); } if (!/^https?:$/.test(u.protocol)) return fertig({ fehler: 'PROTOKOLL' }); let ende = false; const schluss = (w) => { if (!ende) { ende = true; clearTimeout(uhr); fertig(w); } }; const a = (u.protocol === 'https:' ? https : http).request(u, { method: 'GET', lookup: suche, rejectUnauthorized: false, agent: false, headers: { 'User-Agent': UA, Accept: 'text/html,*/*;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'de', Connection: 'close' }, }, (r) => { if (r.statusCode >= 300 && r.statusCode < 400) { r.destroy(); return schluss({ status: r.statusCode, kopf: r.headers, koerper: Buffer.alloc(0) }); } const art = String(r.headers['content-encoding'] ?? '').toLowerCase(); const s = art.includes('br') ? r.pipe(zlib.createBrotliDecompress()) : art.includes('gzip') ? r.pipe(zlib.createGunzip()) : art.includes('deflate') ? r.pipe(zlib.createInflate()) : r; const teile = []; let n = 0; const ab = () => schluss({ status: r.statusCode, kopf: r.headers, koerper: Buffer.concat(teile) }); s.on('data', (t) => { teile.push(t); n += t.length; if (n >= grenze) { ab(); r.destroy(); } }); s.on('end', ab); s.on('error', ab); r.on('error', ab); }); const uhr = setTimeout(() => { a.destroy(); schluss({ fehler: 'ZEITLIMIT' }); }, 15000); a.on('error', (e) => schluss({ fehler: e.code ?? e.message })); a.end(); }); } function text(k, kopf) { const roh = k.subarray(0, 4096).toString('latin1'); const c = /charset=["']?([\w-]+)/i.exec(String(kopf?.['content-type'] ?? ''))?.[1] ?? /charset=["']?([\w-]+)/i.exec(roh)?.[1] ?? 'utf-8'; try { return new TextDecoder(c.toLowerCase()).decode(k); } catch { return new TextDecoder().decode(k); } } const robotsCache = new Map(); function robots(o) { if (!robotsCache.has(o)) robotsCache.set(o, (async () => { const r = await hole(`${o}/robots.txt`, 128 * 1024); if (r.fehler || r.status !== 200) return []; const regeln = []; let aktiv = false; let warAgent = false; for (const zeile of text(r.koerper, r.kopf).split(/\r?\n/)) { const z = zeile.replace(/#.*/, '').trim(); const p = z.indexOf(':'); if (p < 0) continue; const k = z.slice(0, p).trim().toLowerCase(); const w = z.slice(p + 1).trim(); if (k === 'user-agent') { const passt = w === '*' || 'municipal-hosting-study'.includes(w.toLowerCase()); aktiv = warAgent ? aktiv || passt : passt; warAgent = true; } else { warAgent = false; if (aktiv && w && (k === 'allow' || k === 'disallow')) regeln.push({ erlaubt: k === 'allow', pfad: w }); } } return regeln; })()); return robotsCache.get(o); } async function darf(url) { const u = new URL(url); const p = u.pathname + u.search; let best = null; for (const r of await robots(u.origin)) { const m = r.pfad.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\\\$$/, '$'); if (new RegExp(`^${m}`).test(p) && (!best || r.pfad.length > best.pfad.length || (r.pfad.length === best.pfad.length && r.erlaubt))) best = r; } return !best || best.erlaubt; } async function seite(start) { let url = start; for (let i = 0; i < 6; i++) { if (!(await darf(url))) return { url, robots: true }; const r = await hole(url); if (r.fehler) return { url, fehler: r.fehler }; let ziel = r.status >= 300 && r.status < 400 ? r.kopf.location : null; const html = r.koerper.length ? text(r.koerper, r.kopf) : ''; if (!ziel && r.status === 200) ziel = /]+http-equiv=["']?refresh["']?[^>]+content=["']?\s*\d+\s*;\s*url=['"]?([^"'>\s]+)/i.exec(html.slice(0, 8192))?.[1] ?? null; if (!ziel) return { url, status: r.status, html }; try { url = new URL(ziel, url).href; } catch { return { url, status: r.status, html }; } } return { url, fehler: 'ZU_VIELE_WEITERLEITUNGEN' }; } const norm = (s) => String(s ?? '').toLowerCase().replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss').replace(/[^a-z0-9]/g, ''); const kern = (n) => norm(String(n ?? '').split(',')[0].split('(')[0].split('/')[0].replace(/\b(Stadt|Gemeinde|Flecken|Markt)\b/gi, '')); const reinerText = (h) => h.replace(//gi, ' ').replace(//gi, ' ').replace(/<[^>]+>/g, ' ').replace(/&[a-z]+;/gi, ' ').replace(/\s+/g, ' '); const KOMMUNAL = /rathaus|b(ue|ü)rgermeister|gemeinderat|stadtrat|verbandsgemeinde|samtgemeinde|amtsverwaltung|amtsdirektor|verwaltungsgemeinschaft|verwaltungsverband|gemeindeverwaltung|stadtverwaltung|ortsgemeinde|k(oe|ö)rperschaft des (oe|ö)ffentlichen rechts/i; const PARK = /buy this domain|this domain (is|may be) for sale|domain (is|steht) (for sale|zum verkauf)|diese domain (steht|ist|kann)[^.]{0,40}(verkauf|erwerben|reserviert|registriert)|domain parking|sedoparking|parkingcrew|bodis\.com|afternic|default web site page|apache2 (debian|ubuntu) default page|welcome to nginx/i; const start = new Map(jsonl('startseiten.jsonl').map((z) => [z.host, z])); const proHost = new Map(); for (const g of jsonl('universum.jsonl')) { if (!g.host) continue; if (!proHost.has(g.host)) proHost.set(g.host, new Set()); proHost.get(g.host).add(kern(g.name)); } const klar = (z) => z.status === 200 && z.nameTreffer > 0 && z.kommunal && !z.parkverdacht; const fertig = new Set(jsonl('nachpruefung.jsonl').map((z) => z.host)); const offen = [...proHost.keys()].filter((h) => !fertig.has(h) && !(start.get(h) && klar(start.get(h)))); console.log(`Nachprüfung: ${offen.length} Hosts`); async function pruefe(host) { const s = start.get(host); const basis = s?.finalHost ?? host; const ursprung = s?.finalUrl ? new URL(s.finalUrl).origin : `https://${basis}`; let haupt = await seite(`${ursprung}/`); if (haupt.fehler && ursprung.startsWith('https:')) { const alt = await seite(`http://${basis}/`); if (!alt.fehler) haupt = alt; } const zeile = { host, zeit: new Date().toISOString(), zielUrl: haupt.url, zielHost: new URL(haupt.url).hostname.toLowerCase(), status: haupt.status ?? null, fehler: haupt.fehler ?? null, robots: Boolean(haupt.robots), impressumUrl: null, nameImText: false, kommunal: false, park: false, klasse: 'nicht_pruefbar' }; if (haupt.robots) { zeile.klasse = 'robots'; return zeile; } if (haupt.status !== 200 || !haupt.html) { zeile.klasse = 'nicht_erreichbar'; return zeile; } let gesamt = reinerText(haupt.html); zeile.park = PARK.test(gesamt.slice(0, 5000)) && gesamt.length < 8000; const links = [...haupt.html.matchAll(/]*href=["']([^"'#]+)["'][^>]*>([\s\S]{0,120}?)<\/a>/gi)] .filter((m) => /impressum|imprint/i.test(`${m[1]} ${m[2]}`)) .concat([...haupt.html.matchAll(/]*href=["']([^"'#]+)["'][^>]*>([\s\S]{0,120}?)<\/a>/gi)].filter((m) => /kontakt/i.test(`${m[1]} ${m[2]}`))); for (const l of links) { let ziel; try { ziel = new URL(l[1], haupt.url); } catch { continue; } if (!/^https?:$/.test(ziel.protocol) || ziel.hostname.replace(/^www\./, '') !== new URL(haupt.url).hostname.replace(/^www\./, '')) continue; const imp = await seite(ziel.href); if (imp.status === 200 && imp.html) { zeile.impressumUrl = imp.url; gesamt += ` ${reinerText(imp.html)}`; } break; } const n = norm(gesamt); zeile.nameImText = [...proHost.get(host)].some((k) => k.length >= 3 && n.includes(k)); zeile.kommunal = KOMMUNAL.test(gesamt); zeile.klasse = zeile.park ? 'geparkt' : zeile.nameImText && zeile.kommunal ? 'bestaetigt' : zeile.nameImText ? 'name_ohne_verwaltung' : 'nicht_bestaetigt'; return zeile; } let pos = 0; await Promise.all(Array.from({ length: 10 }, async () => { while (pos < offen.length) { const host = offen[pos++]; let z; try { z = await pruefe(host); } catch (e) { z = { host, zeit: new Date().toISOString(), klasse: 'nicht_pruefbar', fehler: String(e.message ?? e) }; } appendFileSync(pfad('nachpruefung.jsonl'), `${JSON.stringify(z)}\n`); await new Promise((r) => setTimeout(r, 300)); } })); const zaehl = {}; for (const z of jsonl('nachpruefung.jsonl')) zaehl[z.klasse] = (zaehl[z.klasse] ?? 0) + 1; console.log(JSON.stringify(zaehl)); process.exit(0);