-
Notifications
You must be signed in to change notification settings - Fork 1
/
GeminiRequestHandler.cs
122 lines (100 loc) · 3.69 KB
/
GeminiRequestHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System.IO.Pipelines;
/// <summary>
/// Based on https://gemini.circumlunar.space/docs/specification.gmi
/// </summary>
public class GeminiRequestHandler : ConnectionHandler
{
private const string GMI_EXT = ".gmi";
private const string MIME_GMI = "text/gemini";
private const string PUBLIC = "public";
private const string CRLF = "\r\n";
private const string SCHEME = "gemini";
private static readonly FileExtensionContentTypeProvider _mime = new();
private readonly ILogger<GeminiRequestHandler> _logger;
private readonly StringBuilder _sb;
public GeminiRequestHandler(ILogger<GeminiRequestHandler> logger)
{
_logger = logger;
_sb = new();
_logger.LogInformation("GeminiRequestHandler created");
}
public async override Task OnConnectedAsync(ConnectionContext connection)
{
var result = await connection.Transport.Input.ReadAsync();
var buffer = result.Buffer;
if (buffer.IsSingleSegment)
{
_logger.LogInformation("New connection handling");
var req = Encoding.UTF8.GetString(buffer.FirstSpan);
if (req.EndsWith(CRLF))
{
await HandleAsync(connection, new Uri(req));
}
await connection.Transport.Output.CompleteAsync();
await connection.Transport.Output.FlushAsync();
}
else
{
throw new NotImplementedException();
}
}
async Task HandleAsync(ConnectionContext connection, Uri _uri)
{
var req = _uri.Segments.Last();
if (_uri.Scheme != SCHEME)
{
AddLine($"59");
await Flush(connection);
}
else if (req == "/")
{
AddLine($"20 {MIME_GMI}");
AddLine($">{RuntimeInformation.OSArchitecture}, {RuntimeInformation.OSDescription}, {RuntimeInformation.ProcessArchitecture}");
AddLine($">{Environment.Version} / {RuntimeInformation.FrameworkDescription}");
AddLine($">");
AddLine($">{DateTime.Now:O}");
await Flush(connection);
}
else
{
var filename = Path.Combine(AppContext.BaseDirectory, PUBLIC, req);
if (File.Exists(filename + GMI_EXT))
{
filename += GMI_EXT;
}
if (File.Exists(filename))
{
if (Path.GetExtension(filename) == GMI_EXT)
{
await SendFile(connection, MIME_GMI, filename);
}
else
{
await SendFile(connection, _mime.TryGetContentType(filename, out var contentType) ? contentType : "application/octet-stream", filename);
}
}
else
{
AddLine("51 Not found.");
await Flush(connection);
}
}
}
async Task SendFile(ConnectionContext connection, string contentType, string filename)
{
var finfo = new FileInfo(filename);
var buffer = new Memory<byte>(new byte[1024 * 16]);
var bytesRead = 0L;
AddLine($"20 {contentType}");
await Flush(connection);
using var reader = new FileStream(filename, FileMode.Open);
while (bytesRead < finfo.Length)
{
var read = await reader.ReadAsync(buffer);
await connection.Transport.Output.WriteAsync(buffer[0..read]);
bytesRead += read;
}
}
void AddLine(string s = "") => _sb.Append($"{s}{CRLF}");
ValueTask<FlushResult> Flush(ConnectionContext connection) => connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes(_sb.ToString()));
}