public CygwinSocket(string path)
{
this.path = path;
guid = Guid.NewGuid();
using (var stream = new FileStream(path, FileMode.CreateNew))
using (var writer = new StreamWriter(stream)) {
try {
File.SetAttributes(path, FileAttributes.System);
var fileSecurity = File.GetAccessControl(path);
// This turns off ACL inheritance and removes all inherited rules
fileSecurity.SetAccessRuleProtection(true, false);
// We are left with no permissions at all, so we have to add them
// back for the current user
var userOnlyRule = new FileSystemAccessRule(
WindowsIdentity.GetCurrent().User,
FileSystemRights.FullControl,
AccessControlType.Allow);
fileSecurity.SetAccessRule(userOnlyRule);
File.SetAccessControl(path, fileSecurity);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
var endpoint = new IPEndPoint(IPAddress.Loopback, 0);
socket.Bind(endpoint);
socket.Listen(5);
var socketThread = new Thread(AcceptConnections);
socketThread.Name = "CygwinSocket";
socketThread.Start();
writer.Write("!<socket >");
var actualPort = ((IPEndPoint)socket.LocalEndPoint).Port;
writer.Write(actualPort);
writer.Write(" s ");
var guidBytes = guid.ToByteArray();
for (int i = 0; i < 4; i++) {
writer.Write(string.Format("{0:X8}",
BitConverter.ToUInt32(guidBytes, i * 4)));
if (i < 3)
writer.Write("-");
}
} catch (Exception) {
if (socket != null)
socket.Close();
File.Delete(path);
throw;
}
}
}