Skip to content

Commit

Permalink
Fix content type parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
cristipufu committed Aug 25, 2024
1 parent 35de32e commit 33ab1a7
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/Tunnelite.Client/HttpTunnel/HttpTunnelClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,11 @@ public async Task ConnectAsync()
private async Task TunnelHttpConnectionAsync(HttpConnection httpConnection)
{
var publicUrl = Tunnel.PublicUrl;

var requestUrl = $"{publicUrl}/tunnelite/request/{httpConnection.RequestId}";

try
{
// Start the request to the public server
using var publicResponse = await ServerHttpClient.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead);

publicResponse.EnsureSuccessStatusCode();

// Prepare the request to the local server
Expand All @@ -110,10 +107,9 @@ private async Task TunnelHttpConnectionAsync(HttpConnection httpConnection)

// Set the content of the local request to stream the data from the public response
localRequest.Content = new StreamContent(await publicResponse.Content.ReadAsStreamAsync());

if (httpConnection.ContentType != null)
{
localRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(httpConnection.ContentType);
localRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(httpConnection.ContentType);
}

// Send the request to the local server and get the response
Expand All @@ -134,21 +130,26 @@ private async Task TunnelHttpConnectionAsync(HttpConnection httpConnection)
// Copy content headers from local response to public request
foreach (var (key, value) in localResponse.Content.Headers)
{
publicRequest.Headers.TryAddWithoutValidation($"X-TC-{key}", value);
if (key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase))
{
publicRequest.Headers.TryAddWithoutValidation($"X-TC-{key}", value.First());
}
else
{
publicRequest.Headers.TryAddWithoutValidation($"X-TC-{key}", value);
}
}

// Set the content of the public request to stream from the local response
publicRequest.Content = new StreamContent(await localResponse.Content.ReadAsStreamAsync());

// Send the response back to the public server
using var response = await ServerHttpClient.SendAsync(publicRequest);

response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error tunneling request: {ex.Message}");

using var errorRequest = new HttpRequestMessage(HttpMethod.Delete, requestUrl);
using var response = await ServerHttpClient.SendAsync(errorRequest);
}
Expand Down

0 comments on commit 33ab1a7

Please sign in to comment.