Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for unix domain sockets to the sockets transport #10560

Merged
merged 1 commit into from
May 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/Servers/Kestrel/Core/src/KestrelServerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
Expand Down Expand Up @@ -295,7 +296,8 @@ public void ListenUnixSocket(string socketPath, Action<ListenOptions> configure)
{
throw new ArgumentNullException(nameof(socketPath));
}
if (socketPath.Length == 0 || socketPath[0] != '/')

if (!Path.IsPathRooted(socketPath))
{
throw new ArgumentException(CoreStrings.UnixSocketPathMustBeAbsolute, nameof(socketPath));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ internal SocketConnectionListener(
SocketTransportOptions options,
ISocketsTrace trace)
{
Debug.Assert(endpoint != null);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

endpoint != null is still a valid assert I believe.

Debug.Assert(endpoint is IPEndPoint);
Debug.Assert(trace != null);

EndPoint = endpoint;
_trace = trace;
_options = options;
Expand Down Expand Up @@ -66,9 +62,12 @@ internal void Bind()
throw new InvalidOperationException(SocketsStrings.TransportAlreadyBound);
}

// TODO: Add support for UnixDomainSocket
Socket listenSocket;
davidfowl marked this conversation as resolved.
Show resolved Hide resolved

// Unix domain sockets are unspecified
var protocolType = EndPoint is UnixDomainSocketEndPoint ? ProtocolType.Unspecified : ProtocolType.Tcp;

var listenSocket = new Socket(EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listenSocket = new Socket(EndPoint.AddressFamily, SocketType.Stream, protocolType);

// Kestrel expects IPv6Any to bind to both IPv6 and IPv4
if (EndPoint is IPEndPoint ip && ip.Address == IPAddress.IPv6Any)
Expand Down Expand Up @@ -99,7 +98,12 @@ public async ValueTask<ConnectionContext> AcceptAsync(CancellationToken cancella
try
{
var acceptSocket = await _listenSocket.AcceptAsync();
acceptSocket.NoDelay = _options.NoDelay;

// Only apply no delay to Tcp based endpoints
if (acceptSocket.LocalEndPoint is IPEndPoint)
{
acceptSocket.NoDelay = _options.NoDelay;
}

var connection = new SocketConnection(acceptSocket, _memoryPool, _schedulers[_schedulerIndex], _trace, _options.MaxReadBufferSize, _options.MaxWriteBufferSize);

Expand Down
117 changes: 117 additions & 0 deletions src/Servers/Kestrel/test/FunctionalTests/UnixDomainSocketsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Buffers;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Testing;
using Microsoft.AspNetCore.Testing.xunit;
using Xunit;

namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{
public class UnixDomainSocketsTest : TestApplicationErrorLoggerLoggedTest
{
#if LIBUV
[OSSkipCondition(OperatingSystems.Windows, SkipReason = "Libuv does not support unix domain sockets on Windows.")]
#else
[OSSkipCondition(OperatingSystems.Windows, WindowsVersions.Win7, WindowsVersions.Win8, WindowsVersions.Win81, WindowsVersions.Win2008R2, SkipReason = "UnixDomainSocketEndPoint is not supported on older versions of Windows")]
#endif
[ConditionalFact]
public async Task TestUnixDomainSocket()
{
var path = Path.GetTempFileName();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be creating the file.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this is a bit jank.

Copy link
Contributor

@analogrelay analogrelay May 31, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Especially when you're using it just to get a name and then immediately deleting it. This is a bit of a flake-farm waiting to happen... why not just use Path.Combine(Path.GetTempPath(), $"Kestrel_TestUnixDomainSocket_{Guid.NewGuid():N}.socket") or something?


Delete(path);

try
{
async Task EchoServer(ConnectionContext connection)
{
// For graceful shutdown
var notificationFeature = connection.Features.Get<IConnectionLifetimeNotificationFeature>();

try
{
while (true)
{
var result = await connection.Transport.Input.ReadAsync(notificationFeature.ConnectionClosedRequested);

if (result.IsCompleted)
{
break;
}

await connection.Transport.Output.WriteAsync(result.Buffer.ToArray());

connection.Transport.Input.AdvanceTo(result.Buffer.End);
}
}
catch (OperationCanceledException)
{

}
}

var hostBuilder = TransportSelector.GetWebHostBuilder()
.UseKestrel(o =>
{
o.ListenUnixSocket(path, builder =>
{
builder.Run(EchoServer);
});
})
.ConfigureServices(AddTestLogging)
.Configure(c => { });
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity, is this line necessary?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea, the webhost throws without it.


using (var host = hostBuilder.Build())
{
await host.StartAsync();

using (var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
await socket.ConnectAsync(new UnixDomainSocketEndPoint(path));

var data = Encoding.ASCII.GetBytes("Hello World");
await socket.SendAsync(data, SocketFlags.None);

var buffer = new byte[data.Length];
var read = 0;
while (read < data.Length)
{
read += await socket.ReceiveAsync(buffer.AsMemory(read, buffer.Length - read), SocketFlags.None);
}

Assert.Equal(data, buffer);
}

await host.StopAsync();
}
}
finally
{
Delete(path);
}
}

private static void Delete(string path)
{
try
{
File.Delete(path);
}
catch (FileNotFoundException)
{

}
}
}
}