Skip to content

Commit

Permalink
Merge pull request #7 from aschuhardt/beta
Browse files Browse the repository at this point in the history
Simplified URL parsing, fixing local links
  • Loading branch information
aschuhardt authored Jan 6, 2024
2 parents 4a62778 + 9b1037e commit 776c4d1
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 56 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: Build and Publish
on:
workflow_run:
workflows: [ Build ]
workflows: [ Test ]
types:
- completed
branches: [ main, beta ]
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ jobs:
with:
dotnet-version: 8.0.x
- name: Run Tests
run: dotnet test -f ${{ matrix.framework }
run: dotnet test -f ${{ matrix.framework }}
1 change: 0 additions & 1 deletion Opal.Console/Opal.Console.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down
29 changes: 18 additions & 11 deletions Opal.Console/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,12 @@
using Opal.Authentication.Certificate;
using Opal.Response;

string? _certPath = null;

string GetInput()
{
return (Console.ReadLine() ?? string.Empty).Trim();
}
string _certPath = null;

Task<IClientCertificate> GetClientCertificate()
{
if (string.IsNullOrEmpty(_certPath))
return Task.FromResult<IClientCertificate?>(null);
return Task.FromResult<IClientCertificate>(null);

var pkcs12 = X509Certificate2.CreateFromPemFile(_certPath).Export(X509ContentType.Pkcs12);
var cert = new X509Certificate2(pkcs12);
Expand All @@ -24,9 +19,10 @@ Task<IClientCertificate> GetClientCertificate()

Task.Run(async () =>
{
var client = new OpalClient();

client.GetActiveClientCertificateCallback = GetClientCertificate;
var client = new OpalClient
{
GetActiveClientCertificateCallback = GetClientCertificate
};

while (true)
{
Expand Down Expand Up @@ -55,7 +51,9 @@ Task<IClientCertificate> GetClientCertificate()
response = await client.UploadAsync(command, contents.Length, null, "text/plain; charset=utf-8", payload);
}
else
{
response = await client.SendRequestAsync(command);
}

if (response.IsSuccess && response is SuccessfulResponse successfulResponse)
{
Expand All @@ -68,6 +66,7 @@ Task<IClientCertificate> GetClientCertificate()
{
// save the file to a temporary location and open it in an OS-dependent fashion
var tempPath = Path.GetTempFileName();

await using (var file = File.OpenWrite(tempPath))
{
successfulResponse.Body.CopyTo(file);
Expand All @@ -77,8 +76,16 @@ Task<IClientCertificate> GetClientCertificate()
}
}
else
{
Console.WriteLine(response.ToString());
}
}
}).Wait();

Console.WriteLine("Goodbye!");
Console.WriteLine("Goodbye!");
return;

string GetInput()
{
return (Console.ReadLine() ?? string.Empty).Trim();
}
15 changes: 15 additions & 0 deletions Opal.Test/DocumentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,19 @@ public void DocumentParser_ParsesProtocolRelativeUrlsCorrectly(string line, stri
Assert.AreEqual(expectedHost, uri.Host);
Assert.AreEqual(expectedPath, uri.PathAndQuery);
}

[TestCase("=> thing", "gemini://localhost/some/thing", "/some/thing")]
[TestCase("=> thing/other", "gemini://localhost/some/thing", "/some/thing/other")]
[TestCase("=> me", "gemini://localhost/some/thing", "/some/me")]
public void DocumentParser_ParsesNonSlashRelativeUrlsCorrectly(string line, string baseUrl, string expectedPath)
{
var withLineEnding = new StringBuilder(line).AppendLine();
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(withLineEnding.ToString()));
if (new GemtextDocumentParser(new Uri(baseUrl)).ParseDocument(stream).Single() is not LinkLine linkLine)
throw new ArgumentException();

var uri = linkLine.Uri;
Assert.IsFalse(!uri.IsAbsoluteUri);
Assert.AreEqual(uri.PathAndQuery, expectedPath);
}
}
49 changes: 9 additions & 40 deletions Opal/Document/GemtextDocumentParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,50 +110,19 @@ private ILine ParseLinkLinePrefix(string line)

var rawUri = new StringBuilder(parts[0]);

// for protocol-relative URIs, prepend the scheme from the request
if (parts[0].StartsWith("//"))
rawUri.Insert(0, ':').Insert(0, _uri.Scheme);

if (!Uri.TryCreate(rawUri.ToString(), UriKind.RelativeOrAbsolute, out var parsed))
return new TextLine(line.Trim());

if (!parsed.IsAbsoluteUri)
{
var pathParts = parts[0].Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries);

var linePath = pathParts[0];
parsed = new UriBuilder
{
Host = _uri.Host, Scheme = _uri.Scheme, Port = _uri.IsDefaultPort ? -1 : _uri.Port,
Path = BuildRelativePath(linePath, _uri),
Query = pathParts.Length > 1 ? pathParts[1] : string.Empty
}.Uri;
}

return new LinkLine(parts.Length > 1 ? parts[1] : null, parsed);
}

private static string BuildRelativePath(string pagePath, Uri baseUri)
{
if (pagePath.StartsWith("/"))
return pagePath; // absolute uri

var path = new StringBuilder();

for (var i = 0; i < baseUri.Segments.Length; i++)
// first try to parse relative to the current URI
if (!Uri.TryCreate(_uri, rawUri.ToString(), out var parsed))
{
var segment = baseUri.Segments[i];
// for protocol-relative URIs, prepend the scheme from the request
if (parts[0].StartsWith("//"))
rawUri.Insert(0, ':').Insert(0, _uri.Scheme);

// if this is the last segment and it looks like a file, skip it
if (i == baseUri.Segments.Length - 1 && segment.Contains("."))
break;

path.Append(segment);
// try to parse as an absolute URI
if (!Uri.TryCreate(rawUri.ToString(), UriKind.Absolute, out parsed))
return new TextLine(line.Trim());
}

path.Append(pagePath);

return path.ToString();
return new LinkLine(parts.Length > 1 ? parts[1] : null, parsed);
}
}
}
5 changes: 3 additions & 2 deletions Opal/OpalClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ private static bool IsGemtextMimetype(string mimetype)
#endif
}

private static IGeminiResponse BuildResponse(Uri uri, GeminiHeader header, Stream contents)
private static IGeminiResponse BuildResponse(Uri uri, GeminiHeader header, MemoryStream contents)
{
// make sure the status code is recognizable
if (!Enum.IsDefined(typeof(StatusCode), header.StatusCode))
Expand Down Expand Up @@ -417,7 +417,8 @@ private static async Task SendUploadAsync(Uri uri, SslStream stream, UploadParam
await stream.FlushAsync().ConfigureAwait(false);
}

private static async Task SendRequestAsync(Uri uri, Stream stream)
// ReSharper disable once SuggestBaseTypeForParameter
private static async Task SendRequestAsync(Uri uri, SslStream stream)
{
var request = ConvertToUtf8($"{uri}\r\n");

Expand Down

0 comments on commit 776c4d1

Please sign in to comment.