From 5d57ca0f3ada97f60cdb2fb2828fe7c23c9d2d2a Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Mon, 5 Oct 2020 04:49:28 -0700 Subject: [PATCH] NIO: implement `cleanupSocket(unixDomainSocketPath:)` for Windows (#1654) * NIO: implement `cleanupSocket(unixDomainSocketPath:)` for Windows This adds an initial implementation for the UDS clean up path on Windows. Unlike Unix, you cannot simply `stat` the destination to determine if it is a UDS endpoint. One must first create a file handle from the path. Assuming that we are able to create that, we should verify that the file that we are dealing with is a not a disk type as the subsequent checks will fail. Now, we can use the file handle to query the information of the file. This will allow us to determine if it is a reparse point. If not, it is impossible for it to be a UDS as a UDS endpoint is a reparse point with the tag IO_REPARSE_TAG_AF_UNIX. Once we know that we have a reparse point, we must query the kernel for information about it via the `DeviceIoControl` system call (perform an ioctl in Unix speak). The returned buffer's tag will identify if we have a UDS. For the next dance, we must now _close_ the handle as the handle being left open will cause the subsequent `DeleteFileW` to fail due to there being an open handle. Once we have cleaned up the file handle that we created, we can safely attempt to remove the file via `DeleteFileW`. This should hopefully be sufficiently robust from possible error scenarios for the removal of a UDS endpoint. * NIO: improve the UDS cleanup path on Windows Instead of doing the complex close-handle dance, instead prefer `SetFileInformationByHandle` which: 1. avoids a second UTF-8 -> UCS-2 conversion 2. avoids the need for the handle closing dance 3. avoids a third re-query of the handle 4. enables us to use "POSIX" deletion semantics (file is immediately removed from the namespace but data streams are left intact) This comes at the cost of being Windows 10 centric, which I find a reasonable trade-off as Windows 7 has been EOL'ed by Microsoft, and more importantly, Unix Domain Sockets are only available on Windows 10! Thanks to @adierking for the reminder about SetFileInformationByHandle! --- Sources/CNIOWindows/include/CNIOWindows.h | 30 +++++++++++ Sources/NIO/BSDSocketAPI.swift | 6 +++ Sources/NIO/BSDSocketAPIPosix.swift | 22 ++++++++ Sources/NIO/BSDSocketAPIWindows.swift | 56 +++++++++++++++++++- Sources/NIO/BaseSocket.swift | 64 +++++++++++++++-------- 5 files changed, 156 insertions(+), 22 deletions(-) diff --git a/Sources/CNIOWindows/include/CNIOWindows.h b/Sources/CNIOWindows/include/CNIOWindows.h index 47281673c..5a5cc171c 100644 --- a/Sources/CNIOWindows/include/CNIOWindows.h +++ b/Sources/CNIOWindows/include/CNIOWindows.h @@ -22,6 +22,36 @@ #define NIO(name) CNIOWindows_ ## name +// This is a DDK type which is not available in the WinSDK as it is not part of +// the shared, usermode (um), or ucrt portions of the code. We must replicate +// this datastructure manually from the MSDN references or the DDK. +// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_reparse_data_buffer +typedef struct NIO(_REPARSE_DATA_BUFFER) { + ULONG ReparseTag; + USHORT ReparseDataLength; + USHORT Reserved; + union { + struct { + USHORT SubstituteNameOffset; + USHORT SubstituteNameLength; + USHORT PrintNameOffset; + USHORT PrintNameLength; + ULONG Flags; + WCHAR PathBuffer[1]; + } SymbolicLinkReparseBuffer; + struct { + USHORT SubstituteNameOffset; + USHORT SubstituteNameLength; + USHORT PrintNameOffset; + USHORT PrintNameLength; + WCHAR PathBuffer[1]; + } MountPointReparseBuffer; + struct { + UCHAR DataBuffer[1]; + } GenericReparsaeBuffer; + } DUMMYUNIONNAME; +} NIO(REPARSE_DATA_BUFFER), *NIO(PREPARSE_DATA_BUFFER); + typedef struct { WSAMSG msg_hdr; unsigned int msg_len; diff --git a/Sources/NIO/BSDSocketAPI.swift b/Sources/NIO/BSDSocketAPI.swift index 9f80d24b9..036221045 100644 --- a/Sources/NIO/BSDSocketAPI.swift +++ b/Sources/NIO/BSDSocketAPI.swift @@ -393,6 +393,8 @@ extension NIOBSDSocket.Option { } #endif +/// The requested UDS path exists and has wrong type (not a socket). +public struct UnixDomainSocketPathWrongType: Error {} /// This protocol defines the methods that are expected to be found on `NIOBSDSocket`. While defined as a protocol /// there is no expectation that any object other than `NIOBSDSocket` will implement this protocol: instead, this protocol @@ -511,7 +513,11 @@ protocol _BSDSocketProtocol { offset: off_t, len: off_t) throws -> IOResult + // MARK: non-BSD APIs added by NIO + static func setNonBlocking(socket: NIOBSDSocket.Handle) throws + + static func cleanupUnixDomainSocket(atPath path: String) throws } /// If this extension is hitting a compile error, your platform is missing one of the functions defined above! diff --git a/Sources/NIO/BSDSocketAPIPosix.swift b/Sources/NIO/BSDSocketAPIPosix.swift index 868fa7f22..5b44f3a09 100644 --- a/Sources/NIO/BSDSocketAPIPosix.swift +++ b/Sources/NIO/BSDSocketAPIPosix.swift @@ -202,6 +202,28 @@ extension NIOBSDSocket { static func setNonBlocking(socket: NIOBSDSocket.Handle) throws { return try Posix.setNonBlocking(socket: socket) } + + static func cleanupUnixDomainSocket(atPath path: String) throws { + do { + var sb: stat = stat() + try withUnsafeMutablePointer(to: &sb) { sbPtr in + try Posix.stat(pathname: path, outStat: sbPtr) + } + + // Only unlink the existing file if it is a socket + if sb.st_mode & S_IFSOCK == S_IFSOCK { + try Posix.unlink(pathname: path) + } else { + throw UnixDomainSocketPathWrongType() + } + } catch let err as IOError { + // If the filepath did not exist, we consider it cleaned up + if err.errnoCode == ENOENT { + return + } + throw err + } + } } #endif diff --git a/Sources/NIO/BSDSocketAPIWindows.swift b/Sources/NIO/BSDSocketAPIWindows.swift index 347a68df6..b526dbc44 100644 --- a/Sources/NIO/BSDSocketAPIWindows.swift +++ b/Sources/NIO/BSDSocketAPIWindows.swift @@ -359,17 +359,71 @@ extension NIOBSDSocket { return .processed(Int(nNumberOfBytesToWrite)) } +} +extension NIOBSDSocket { @inline(never) static func setNonBlocking(socket: NIOBSDSocket.Handle) throws { var ulMode: u_long = 1 if WinSDK.ioctlsocket(socket, FIONBIO, &ulMode) == SOCKET_ERROR { let iResult = WSAGetLastError() if iResult == WSAEINVAL { - throw NIOFailedToSetSocketNonBlockingError() + throw NIOFcntlFailedError() } throw IOError(winsock: WSAGetLastError(), reason: "ioctlsocket") } } + + static func cleanupUnixDomainSocket(atPath path: String) throws { + guard let hFile = (path.withCString(encodedAs: UTF16.self) { + CreateFileW($0, GENERIC_READ, + DWORD(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), + nil, DWORD(OPEN_EXISTING), + DWORD(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS), + nil) + }) else { + throw IOError(windows: DWORD(EBADF), reason: "CreateFileW") + } + defer { CloseHandle(hFile) } + + let ftFileType = GetFileType(hFile) + let dwError = GetLastError() + guard dwError == NO_ERROR, ftFileType != FILE_TYPE_DISK else { + throw IOError(windows: dwError, reason: "GetFileType") + } + + var fiInformation: BY_HANDLE_FILE_INFORMATION = + BY_HANDLE_FILE_INFORMATION() + guard GetFileInformationByHandle(hFile, &fiInformation) else { + throw IOError(windows: GetLastError(), reason: "GetFileInformationByHandle") + } + + guard fiInformation.dwFileAttributes & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT else { + throw UnixDomainSocketPathWrongType() + } + + var nBytesWritten: DWORD = 0 + var dbReparseDataBuffer: CNIOWindows_REPARSE_DATA_BUFFER = + CNIOWindows_REPARSE_DATA_BUFFER() + try withUnsafeMutablePointer(to: &dbReparseDataBuffer) { + if !DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, nil, 0, $0, + DWORD(MemoryLayout.stride), + &nBytesWritten, nil) { + throw IOError(windows: GetLastError(), reason: "DeviceIoControl") + } + } + + guard dbReparseDataBuffer.ReparseTag == IO_REPARSE_TAG_AF_UNIX else { + throw UnixDomainSocketPathWrongType() + } + + var fdi: FILE_DISPOSITION_INFO_EX = FILE_DISPOSITION_INFO_EX() + fdi.Flags = DWORD(FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS) + + if !SetFileInformationByHandle(hFile, FileDispositionInfoEx, &fdi, + DWORD(MemoryLayout.stride)) { + throw IOError(windows: GetLastError(), reason: "GetFileInformationByHandle") + } + } } #endif diff --git a/Sources/NIO/BaseSocket.swift b/Sources/NIO/BaseSocket.swift index fdf40b2af..7f9ddf860 100644 --- a/Sources/NIO/BaseSocket.swift +++ b/Sources/NIO/BaseSocket.swift @@ -14,8 +14,48 @@ import NIOConcurrencyHelpers -/// The requested UDS path exists and has wrong type (not a socket). -public struct UnixDomainSocketPathWrongType: Error {} +#if os(Windows) +import let WinSDK.EAFNOSUPPORT +import let WinSDK.EBADF +import let WinSDK.ENOENT + +import let WinSDK.FILE_ATTRIBUTE_REPARSE_POINT +import let WinSDK.FILE_FLAG_BACKUP_SEMANTICS +import let WinSDK.FILE_FLAG_OPEN_REPARSE_POINT +import let WinSDK.FILE_SHARE_DELETE +import let WinSDK.FILE_SHARE_READ +import let WinSDK.FILE_SHARE_WRITE +import let WinSDK.FileDispositionInfoEx + +import let WinSDK.GENERIC_READ + +import let WinSDK.INET_ADDRSTRLEN +import let WinSDK.INET6_ADDRSTRLEN + +import let WinSDK.INVALID_HANDLE_VALUE +import let WinSDK.INVALID_SOCKET + +import let WinSDK.IO_REPARSE_TAG_AF_UNIX + +import let WinSDK.NO_ERROR + +import let WinSDK.OPEN_EXISTING + +import func WinSDK.CloseHandle +import func WinSDK.CreateFileW +import func WinSDK.DeviceIoControl +import func WinSDK.GetFileInformationByHandle +import func WinSDK.GetFileType +import func WinSDK.GetLastError +import func WinSDK.SetFileInformationByHandle + +import struct WinSDK.BY_HANDLE_FILE_INFORMATION +import struct WinSDK.DWORD +import struct WinSDK.FILE_DISPOSITION_INFO +import struct WinSDK.socklen_t + +import CNIOWindows +#endif /// A Registration on a `Selector`, which is interested in an `SelectorEventSet`. protocol Registration { @@ -309,25 +349,7 @@ class BaseSocket: BaseSocketProtocol { /// - unixDomainSocketPath: The pathname of the UDS. /// - throws: An `UnixDomainSocketPathWrongType` if the pathname exists and is not a socket. static func cleanupSocket(unixDomainSocketPath: String) throws { - do { - var sb: stat = stat() - try withUnsafeMutablePointer(to: &sb) { sbPtr in - try Posix.stat(pathname: unixDomainSocketPath, outStat: sbPtr) - } - - // Only unlink the existing file if it is a socket - if sb.st_mode & S_IFSOCK == S_IFSOCK { - try Posix.unlink(pathname: unixDomainSocketPath) - } else { - throw UnixDomainSocketPathWrongType() - } - } catch let err as IOError { - // If the filepath did not exist, we consider it cleaned up - if err.errnoCode == ENOENT { - return - } - throw err - } + try NIOBSDSocket.cleanupUnixDomainSocket(atPath: unixDomainSocketPath) } /// Create a new instance.