febe-sonda legge un HAR troncato senza perdere la parte buona
Chrome ha troncato due esportazioni del giro A quater (a 200 000 byte e a 57 MB, a meta di un corpo di risposta) e la sonda le rifiutava come file sbagliati. Ora da-har e richieste tengono le voci complete, scartano quella dentro cui il file finisce e lo dicono; un file rotto in qualunque altro modo resta rifiutato. Per richieste la voce scartata conta comunque come dati: si chiude dove si ferma e passa per le stesse regole di una voce intera, e ogni stringa JSON del testo interrotto conta come valore, cosi un nome che e un dato solo li non arriva nel file delle forme. In A quater: come esportare senza che il file si tronchi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8d2f85693c
commit
78aa32bdb2
8 files changed
+831
-41
No files matched your search
@@ -0,0 +1,388 @@
|
||||
using System.Buffers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Febe.Sonda;
|
||||
|
||||
/// <summary>
|
||||
/// A HAR exported from the browser's DevTools, read whole into one <see cref="JsonDocument"/>, with its
|
||||
/// <c>log.entries</c>. An export cut short (Chrome may stop writing a large HAR in the middle of a response body) is
|
||||
/// still read: the entries that are complete are kept, the one the file ends inside is left out of
|
||||
/// <see cref="Entries"/>, and <see cref="Truncated"/> says so. A file broken in any other way is refused, as before.
|
||||
/// </summary>
|
||||
internal sealed class HarFile : IDisposable
|
||||
{
|
||||
private static readonly byte[] Utf8Bom = [0xEF, 0xBB, 0xBF];
|
||||
|
||||
private static readonly byte[] Prefix = Encoding.UTF8.GetBytes("{\"log\":{\"entries\":[");
|
||||
|
||||
private static readonly byte[] Suffix = Encoding.UTF8.GetBytes("]}}");
|
||||
|
||||
private readonly ReadOnlyMemory<byte> _dropped;
|
||||
|
||||
private readonly int _maxDepth;
|
||||
|
||||
private HarFile(JsonDocument document, JsonElement entries, bool truncated, ReadOnlyMemory<byte> dropped, int maxDepth)
|
||||
{
|
||||
Document = document;
|
||||
Entries = entries;
|
||||
Truncated = truncated;
|
||||
_dropped = dropped;
|
||||
_maxDepth = maxDepth;
|
||||
}
|
||||
|
||||
public JsonDocument Document { get; }
|
||||
|
||||
/// <summary>The array <c>log.entries</c>: in a cut file, its complete entries only.</summary>
|
||||
public JsonElement Entries { get; }
|
||||
|
||||
/// <summary>The file ends before its JSON does.</summary>
|
||||
public bool Truncated { get; }
|
||||
|
||||
/// <summary>The file ends inside an entry, which is not in <see cref="Entries"/> (false if it ends between entries or after them).</summary>
|
||||
public bool DroppedAnEntry => !_dropped.IsEmpty;
|
||||
|
||||
/// <exception cref="InvalidDataException">The file is not JSON, or not a HAR, or is broken other than by being cut short.</exception>
|
||||
public static HarFile Open(string path, int maxDepth)
|
||||
{
|
||||
ReadOnlyMemory<byte> json = File.ReadAllBytes(path);
|
||||
if (json.Span.StartsWith(Utf8Bom))
|
||||
{
|
||||
json = json[Utf8Bom.Length..];
|
||||
}
|
||||
|
||||
var name = Path.GetFileName(path);
|
||||
JsonDocument document;
|
||||
var truncated = false;
|
||||
var dropped = ReadOnlyMemory<byte>.Empty;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = maxDepth });
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
if (Recover(json, maxDepth) is not { } recovered)
|
||||
{
|
||||
throw new InvalidDataException($"{name}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
|
||||
}
|
||||
|
||||
(document, dropped) = recovered;
|
||||
truncated = true;
|
||||
}
|
||||
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Object
|
||||
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object
|
||||
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
document.Dispose();
|
||||
throw new InvalidDataException($"{name}: non è un file HAR (manca «log.entries»).");
|
||||
}
|
||||
|
||||
return new HarFile(document, entries, truncated, dropped, maxDepth);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entry the file ends inside, closed where it stops (<see cref="CloseCut"/>), so that <c>richieste</c> can
|
||||
/// collect its values with the same rules as a whole entry; null if no entry was cut. Never written anywhere.
|
||||
/// </summary>
|
||||
public DroppedEntry? ReadDroppedEntry() => _dropped.IsEmpty ? null : CloseCut(_dropped.Span, _maxDepth);
|
||||
|
||||
public void Dispose() => Document.Dispose();
|
||||
|
||||
/// <summary>
|
||||
/// The complete entries of a HAR whose file ends early, as a new document <c>{"log":{"entries":[…]}}</c>, and the
|
||||
/// bytes of the entry the file ends inside (empty if it ends between entries or after them); null when the file is
|
||||
/// broken in any other way (a syntax error, a shape that is not a HAR, no complete entry).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The reader is told the data is NOT final: where the file simply stops, <see cref="Utf8JsonReader.Read"/> and
|
||||
/// <see cref="Utf8JsonReader.TrySkip"/> return false instead of throwing, while a real syntax error still throws.
|
||||
/// </remarks>
|
||||
internal static (JsonDocument Document, ReadOnlyMemory<byte> Dropped)? Recover(ReadOnlyMemory<byte> json, int maxDepth)
|
||||
{
|
||||
var options = new JsonReaderOptions { MaxDepth = maxDepth };
|
||||
var ranges = new List<(int Start, int End)>();
|
||||
var droppedFrom = -1;
|
||||
try
|
||||
{
|
||||
var reader = new Utf8JsonReader(json.Span, isFinalBlock: false, new JsonReaderState(options));
|
||||
if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject
|
||||
|| !MoveToProperty(ref reader, "log") || !reader.Read() || reader.TokenType != JsonTokenType.StartObject
|
||||
|| !MoveToProperty(ref reader, "entries") || !reader.Read() || reader.TokenType != JsonTokenType.StartArray)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (!reader.Read())
|
||||
{
|
||||
break; // the file ends between two entries
|
||||
}
|
||||
|
||||
if (reader.TokenType == JsonTokenType.EndArray)
|
||||
{
|
||||
// Every entry is whole: the file must end later, after the array, and not because of a syntax error.
|
||||
while (reader.Read())
|
||||
{
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (reader.TokenType != JsonTokenType.StartObject)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var start = (int)reader.TokenStartIndex;
|
||||
if (!reader.TrySkip())
|
||||
{
|
||||
droppedFrom = start; // the file ends inside this entry
|
||||
break;
|
||||
}
|
||||
|
||||
ranges.Add((start, (int)reader.BytesConsumed));
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ranges.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var length = Prefix.Length + Suffix.Length + ranges.Sum(r => r.End - r.Start + 1);
|
||||
var buffer = new byte[length];
|
||||
var at = 0;
|
||||
Prefix.CopyTo(buffer, at);
|
||||
at += Prefix.Length;
|
||||
for (var i = 0; i < ranges.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
buffer[at++] = (byte)',';
|
||||
}
|
||||
|
||||
var (start, end) = ranges[i];
|
||||
json.Span[start..end].CopyTo(buffer.AsSpan(at));
|
||||
at += end - start;
|
||||
}
|
||||
|
||||
Suffix.CopyTo(buffer, at);
|
||||
at += Suffix.Length;
|
||||
var document = JsonDocument.Parse(buffer.AsMemory(0, at), new JsonDocumentOptions { MaxDepth = maxDepth });
|
||||
return (document, droppedFrom < 0 ? ReadOnlyMemory<byte>.Empty : json[droppedFrom..]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes a JSON object that stops early: every token read whole is kept; a string value the data ends inside is
|
||||
/// kept up to the cut (it is <see cref="DroppedEntry.CutText"/> too, usually the response body Chrome stopped
|
||||
/// writing); a name left without its value gets null; then the open objects and arrays are closed.
|
||||
/// </summary>
|
||||
internal static DroppedEntry CloseCut(ReadOnlySpan<byte> json, int maxDepth)
|
||||
{
|
||||
var buffer = new ArrayBufferWriter<byte>();
|
||||
var open = new Stack<JsonTokenType>();
|
||||
var pendingName = false;
|
||||
string? cut = null;
|
||||
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { MaxDepth = maxDepth + 1 }))
|
||||
{
|
||||
writer.WriteStartArray();
|
||||
var reader = new Utf8JsonReader(json, isFinalBlock: false, new JsonReaderState(new JsonReaderOptions { MaxDepth = maxDepth }));
|
||||
while (reader.Read())
|
||||
{
|
||||
switch (reader.TokenType)
|
||||
{
|
||||
case JsonTokenType.StartObject:
|
||||
writer.WriteStartObject();
|
||||
open.Push(JsonTokenType.StartObject);
|
||||
pendingName = false;
|
||||
break;
|
||||
case JsonTokenType.StartArray:
|
||||
writer.WriteStartArray();
|
||||
open.Push(JsonTokenType.StartArray);
|
||||
pendingName = false;
|
||||
break;
|
||||
case JsonTokenType.EndObject:
|
||||
writer.WriteEndObject();
|
||||
open.Pop();
|
||||
break;
|
||||
case JsonTokenType.EndArray:
|
||||
writer.WriteEndArray();
|
||||
open.Pop();
|
||||
break;
|
||||
case JsonTokenType.PropertyName:
|
||||
writer.WritePropertyName(Text(ref reader));
|
||||
pendingName = true;
|
||||
break;
|
||||
case JsonTokenType.String:
|
||||
writer.WriteStringValue(Text(ref reader));
|
||||
pendingName = false;
|
||||
break;
|
||||
case JsonTokenType.Number:
|
||||
writer.WriteRawValue(reader.ValueSpan, skipInputValidation: true);
|
||||
pendingName = false;
|
||||
break;
|
||||
case JsonTokenType.True:
|
||||
case JsonTokenType.False:
|
||||
writer.WriteBooleanValue(reader.TokenType == JsonTokenType.True);
|
||||
pendingName = false;
|
||||
break;
|
||||
default:
|
||||
writer.WriteNullValue();
|
||||
pendingName = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (open.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// What the reader could not finish: separators, then perhaps the start of a string.
|
||||
var rest = json[(int)reader.BytesConsumed..];
|
||||
var skip = 0;
|
||||
while (skip < rest.Length && rest[skip] is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n' or (byte)',' or (byte)':')
|
||||
{
|
||||
skip++;
|
||||
}
|
||||
|
||||
rest = rest[skip..];
|
||||
var valueExpected = pendingName || (open.Count > 0 && open.Peek() == JsonTokenType.StartArray);
|
||||
if (valueExpected && rest.Length > 0 && rest[0] == (byte)'"')
|
||||
{
|
||||
cut = PartialString(rest[1..]);
|
||||
writer.WriteStringValue(cut);
|
||||
pendingName = false;
|
||||
}
|
||||
|
||||
if (pendingName)
|
||||
{
|
||||
writer.WriteNullValue();
|
||||
}
|
||||
|
||||
while (open.Count > 0)
|
||||
{
|
||||
if (open.Pop() == JsonTokenType.StartObject)
|
||||
{
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
}
|
||||
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
|
||||
return new DroppedEntry(JsonDocument.Parse(buffer.WrittenMemory, new JsonDocumentOptions { MaxDepth = maxDepth + 1 }), cut);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the reader to the value of the property <paramref name="name"/> of the object it is in, skipping the others;
|
||||
/// false if the object ends, or the file does, first.
|
||||
/// </summary>
|
||||
private static bool MoveToProperty(ref Utf8JsonReader reader, string name)
|
||||
{
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader.TokenType != JsonTokenType.PropertyName)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (reader.ValueTextEquals(name))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!reader.Read() || !reader.TrySkip())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A string token as text; one that is not valid UTF-8 or UTF-16 is decoded leniently, never refused.</summary>
|
||||
private static string Text(ref Utf8JsonReader reader)
|
||||
{
|
||||
try
|
||||
{
|
||||
return reader.GetString() ?? string.Empty;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
return Encoding.UTF8.GetString(reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The text of a JSON string whose closing quote never came: the bytes after the opening quote, without an escape
|
||||
/// or a UTF-8 character the cut left half written, unescaped; decoded leniently if it still does not read.
|
||||
/// </summary>
|
||||
internal static string PartialString(ReadOnlySpan<byte> raw)
|
||||
{
|
||||
// A closing quote inside the rest would mean the reader stopped for another reason: keep only up to it.
|
||||
var end = 0;
|
||||
while (end < raw.Length && raw[end] != (byte)'"')
|
||||
{
|
||||
end += raw[end] == (byte)'\\' ? 2 : 1;
|
||||
}
|
||||
|
||||
var text = raw[..Math.Min(end, raw.Length)];
|
||||
|
||||
// An escape cut in two: a lone backslash, or «\u» with fewer than four hexadecimal digits.
|
||||
var backslash = text.LastIndexOf((byte)'\\');
|
||||
if (backslash >= 0 && text.Length - backslash < 6)
|
||||
{
|
||||
var run = 0;
|
||||
while (backslash - run >= 0 && text[backslash - run] == (byte)'\\')
|
||||
{
|
||||
run++;
|
||||
}
|
||||
|
||||
var escape = text[backslash..];
|
||||
var whole = run % 2 == 0 || (escape.Length >= 2 && escape[1] != (byte)'u') || escape.Length == 6;
|
||||
if (!whole)
|
||||
{
|
||||
text = text[..backslash];
|
||||
}
|
||||
}
|
||||
|
||||
for (var trim = 0; trim <= 3 && trim <= text.Length; trim++)
|
||||
{
|
||||
var candidate = new byte[text.Length - trim + 2];
|
||||
candidate[0] = (byte)'"';
|
||||
text[..^trim].CopyTo(candidate.AsSpan(1));
|
||||
candidate[^1] = (byte)'"';
|
||||
try
|
||||
{
|
||||
var reader = new Utf8JsonReader(candidate);
|
||||
if (reader.Read() && reader.TokenType == JsonTokenType.String)
|
||||
{
|
||||
return reader.GetString() ?? string.Empty;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidOperationException)
|
||||
{
|
||||
// A UTF-8 character cut in two, or bytes that are not UTF-8: one byte less, then lenient decoding.
|
||||
}
|
||||
}
|
||||
|
||||
return Encoding.UTF8.GetString(text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The entry a cut HAR ends inside, closed where it stops, as a one-element array; and the text cut short.</summary>
|
||||
internal sealed record DroppedEntry(JsonDocument Document, string? CutText) : IDisposable
|
||||
{
|
||||
public void Dispose() => Document.Dispose();
|
||||
}
|
||||
@@ -20,6 +20,13 @@ namespace Febe.Sonda;
|
||||
/// <param name="DocumentsWithoutData">Left out: page documents that embed no JSON.</param>
|
||||
public sealed record HarImportReport(int Entries, int DataResponses, int Documents, int DocumentBlocks, int OtherHosts, int NotData, int WithoutBody, int NotJson, int DocumentsWithoutData)
|
||||
{
|
||||
/// <summary>The file ends before its JSON does: <see cref="Entries"/> counts the complete entries only, the one the
|
||||
/// file ends inside is left out (<see cref="HarFile"/>).</summary>
|
||||
public bool Truncated { get; init; }
|
||||
|
||||
/// <summary>The file ends inside an entry, which is left out (not counted in <see cref="Entries"/>).</summary>
|
||||
public bool DroppedEntry { get; init; }
|
||||
|
||||
public int Written => DataResponses + DocumentBlocks;
|
||||
}
|
||||
|
||||
@@ -67,26 +74,9 @@ public static partial class HarImporter
|
||||
throw new InvalidOperationException($"La cartella «{folder}» non è vuota: indica una cartella nuova, solo per questa conversione.");
|
||||
}
|
||||
|
||||
JsonDocument document;
|
||||
try
|
||||
using (var file = HarFile.Open(har, BodyOptions.MaxDepth))
|
||||
{
|
||||
using var stream = File.OpenRead(har);
|
||||
document = JsonDocument.Parse(stream);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Object
|
||||
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object
|
||||
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR (manca «log.entries»).");
|
||||
}
|
||||
|
||||
var entries = file.Entries;
|
||||
Directory.CreateDirectory(folder);
|
||||
File.WriteAllText(
|
||||
Path.Combine(folder, "LEGGIMI.txt"),
|
||||
@@ -147,7 +137,7 @@ public static partial class HarImporter
|
||||
}
|
||||
}
|
||||
|
||||
return new HarImportReport(count, data, documents, blocks, otherHosts, notData, withoutBody, notJson, documentsWithoutData);
|
||||
return new HarImportReport(count, data, documents, blocks, otherHosts, notData, withoutBody, notJson, documentsWithoutData) { Truncated = file.Truncated, DroppedEntry = file.DroppedAnEntry };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -143,6 +143,7 @@ static int FromHar(string[] args)
|
||||
}
|
||||
|
||||
// Counts only: what the answers contain stays on this machine.
|
||||
Truncation(report.Truncated, report.DroppedEntry);
|
||||
Console.WriteLine($"Lette {report.Entries} voci del file HAR; scritti {report.Written} campioni grezzi: {report.DataResponses} risposte di dati del sito, {report.DocumentBlocks} blocchi di dati incorporati in {report.Documents} pagine.");
|
||||
Console.WriteLine($"Lasciate fuori: {report.OtherHosts} di altri indirizzi (CDN, altri siti), {report.NotData} che non sono dati (file, immagini, script...), {report.WithoutBody} senza corpo, {report.NotJson} non JSON, {report.DocumentsWithoutData} pagine senza dati incorporati.");
|
||||
if (report.Written == 0 && report.WithoutBody > 0)
|
||||
@@ -155,6 +156,24 @@ static int FromHar(string[] args)
|
||||
return report.Written > 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static void Truncation(bool truncated, bool droppedEntry)
|
||||
{
|
||||
if (!truncated)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (droppedEntry)
|
||||
{
|
||||
Console.WriteLine("Il file HAR è troncato: finisce a metà di una voce, che è stata scartata; le voci complete prima di lei sono tenute.");
|
||||
Console.WriteLine("Ciò che la pagina ha ricevuto dopo non c'è. Se manca qualcosa che serve, esporta di nuovo un giro più corto.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Il file HAR è troncato, ma fuori dalle voci: sono tutte intere e tutte tenute.");
|
||||
}
|
||||
}
|
||||
|
||||
static int RequestsFromHar(string[] args)
|
||||
{
|
||||
var har = Option(args, "--har");
|
||||
@@ -176,6 +195,7 @@ static int RequestsFromHar(string[] args)
|
||||
return 3;
|
||||
}
|
||||
|
||||
Truncation(report.Truncated, report.DroppedEntry);
|
||||
Console.WriteLine($"Lette {report.Entries} voci del file HAR; descritte {report.SiteRequests} richieste della pagina al sito in {report.Shapes} forme distinte.");
|
||||
Console.WriteLine($"Nomi tolti perché potevano essere dati: {report.RemovedNames}.");
|
||||
Console.WriteLine($"Forme delle richieste in: {Path.GetFullPath(to)}");
|
||||
|
||||
@@ -12,7 +12,14 @@ namespace Febe.Sonda;
|
||||
/// <param name="SiteRequests">Requests the page made to the site (XHR, Fetch) that were described.</param>
|
||||
/// <param name="Shapes">Distinct shapes written: same method, path pattern, operation and query identifier.</param>
|
||||
/// <param name="RemovedNames">Names (parameters, fields, keys) replaced because they could be data.</param>
|
||||
public sealed record RequestShapesReport(int Entries, int SiteRequests, int Shapes, int RemovedNames);
|
||||
public sealed record RequestShapesReport(int Entries, int SiteRequests, int Shapes, int RemovedNames)
|
||||
{
|
||||
/// <summary>The file ends before its JSON does: only its complete entries are described (<see cref="HarFile"/>).</summary>
|
||||
public bool Truncated { get; init; }
|
||||
|
||||
/// <summary>The file ends inside an entry, which is not described (its values still count as data).</summary>
|
||||
public bool DroppedEntry { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes the SHAPE of the requests Instagram's own page makes to the site (decision of 12 November 2026, issue #34:
|
||||
@@ -126,31 +133,29 @@ public static partial class RequestShapes
|
||||
throw new InvalidOperationException($"Il file «{output}» esiste già: indica un file nuovo.");
|
||||
}
|
||||
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
using var stream = File.OpenRead(har);
|
||||
document = JsonDocument.Parse(stream, DeepDocuments);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
|
||||
}
|
||||
|
||||
var shapes = new Dictionary<string, Shape>(StringComparer.Ordinal);
|
||||
int count = 0, described = 0;
|
||||
Names names;
|
||||
using (document)
|
||||
bool truncated, droppedEntry;
|
||||
using (var file = HarFile.Open(har, DeepDocuments.MaxDepth))
|
||||
{
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Object
|
||||
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object
|
||||
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
|
||||
var entries = file.Entries;
|
||||
truncated = file.Truncated;
|
||||
|
||||
// First pass: every value the HAR holds, wherever it is, the entry a cut file ends inside included. A name
|
||||
// equal to one of them is never written.
|
||||
var values = ValueCollector.Collect(entries);
|
||||
droppedEntry = file.DroppedAnEntry;
|
||||
if (file.ReadDroppedEntry() is { } dropped)
|
||||
{
|
||||
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR (manca «log.entries»).");
|
||||
using (dropped)
|
||||
{
|
||||
values.UnionWith(ValueCollector.Collect(dropped.Document.RootElement));
|
||||
ValueCollector.AddCutText(values, dropped.CutText);
|
||||
}
|
||||
}
|
||||
|
||||
// First pass: every value the HAR holds, wherever it is. A name equal to one of them is never written.
|
||||
names = new Names(ValueCollector.Collect(entries));
|
||||
names = new Names(values);
|
||||
foreach (var entry in entries.EnumerateArray())
|
||||
{
|
||||
count++;
|
||||
@@ -191,7 +196,7 @@ public static partial class RequestShapes
|
||||
writer.Write('\n');
|
||||
}
|
||||
|
||||
return new RequestShapesReport(count, described, shapes.Count, names.Removed);
|
||||
return new RequestShapesReport(count, described, shapes.Count, names.Removed) { Truncated = truncated, DroppedEntry = droppedEntry };
|
||||
}
|
||||
|
||||
/// <summary>The path with each segment that is not a known word replaced by <c>{numero}</c> or <c>{testo}</c>.</summary>
|
||||
@@ -705,7 +710,7 @@ public static partial class RequestShapes
|
||||
/// Every value a HAR holds (addresses, cookies, header values, form values, strings of JSON requests and responses,
|
||||
/// data embedded in pages), to tell a name of the site's code from a piece of data used as a name.
|
||||
/// </summary>
|
||||
internal static class ValueCollector
|
||||
internal static partial class ValueCollector
|
||||
{
|
||||
private const int MaxBodyChars = 64 * 1024 * 1024;
|
||||
|
||||
@@ -780,6 +785,63 @@ internal static class ValueCollector
|
||||
return values;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The text a cut HAR ends inside (usually a response body, possibly base64 or a page): besides what
|
||||
/// <see cref="Collect"/> already took from the closed entry, every JSON string literal in it counts as a value, keys
|
||||
/// included, so that names inside a body or an embedded block cut in two are found too. More values only remove
|
||||
/// more names.
|
||||
/// </summary>
|
||||
public static void AddCutText(HashSet<string> values, string? text, bool decoded = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Body(values, text);
|
||||
foreach (Match literal in StringLiteral().Matches(text))
|
||||
{
|
||||
string? value;
|
||||
try
|
||||
{
|
||||
value = JsonSerializer.Deserialize<string>(literal.Value);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
value = literal.Groups[1].Value;
|
||||
}
|
||||
|
||||
Add(values, value);
|
||||
if (value is not null)
|
||||
{
|
||||
Address(values, value);
|
||||
}
|
||||
}
|
||||
|
||||
// A base64 body cut anywhere: its first whole groups of four characters still decode.
|
||||
if (!decoded && text.Length >= 8 && Base64Text().IsMatch(text))
|
||||
{
|
||||
var length = text.Length / 4 * 4;
|
||||
try
|
||||
{
|
||||
var bytes = Convert.FromBase64String(text[..length]);
|
||||
AddCutText(values, Encoding.UTF8.GetString(bytes), decoded: true);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// Not base64 after all.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("""
|
||||
"((?:[^"\\\r\n]|\\.){1,512})"
|
||||
""", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex StringLiteral();
|
||||
|
||||
[GeneratedRegex("^[A-Za-z0-9+/]+=*$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Base64Text();
|
||||
|
||||
private static void Add(HashSet<string> values, string? value)
|
||||
{
|
||||
var text = value?.Trim();
|
||||
|
||||
Reference in new issue
Block a user