packages feed

nova-nix-0.11.0.0 / src / Nix / Daemon / Pipe.hs

{-# LANGUAGE LambdaCase #-}{-# LANGUAGE ScopedTypeVariables #-}-- | The daemon's named pipe on Windows, and the accounts its clients are-- named by.  Windows has no Unix socket that names its peer, so the daemon-- listens on a named pipe, @\\\\.\\pipe\\nova-nix-daemon@ unless it is told-- another, and names each client by the token it connected with.  Built-- on Windows alone, through @cbits\/nn_winfs.c@.---- == The pipe---- The pipe's first instance is created with-- @FILE_FLAG_FIRST_PIPE_INSTANCE@, so a daemon refuses to start where any-- process already has the pipe, rather than adding instances to a pipe-- another account made and controls.  Every instance refuses clients on-- other machines (@PIPE_REJECT_REMOTE_CLIENTS@) and carries the security-- descriptor 'pipeSddl' describes: an owner ('processPipeOwner'), and a-- protected DACL that gives SYSTEM and Administrators full control and-- Users the right to read and write data and nothing more-- ('clientPipeAccess'), so while the daemon has the pipe no other user-- can create an instance of it and take a client in the daemon's place.-- An elevated daemon, which owns the pipe as Administrators, gives its own-- account no entry: the processes of that account that are not elevated-- hold Administrators for deny only and would otherwise create instances-- and rewrite the DACL.  A daemon that does not hold Administrators owns-- the pipe as its account and gives that account the access that creating-- the next instance takes ('daemonPipeAccess'), which leaves out the-- rights to change the DACL and the owner.  The pipe carries no mandatory-- label when a process at Medium integrity or above makes it, which-- Windows reads as Medium, so a Medium client can write it, and a process-- at Low integrity cannot.---- == Who serves the pipe---- Where no daemon has the pipe, any user can make it, so a client of the-- pipe checks who did before it sends anything ('connectPipe').  It reads-- the pipe's owner and integrity label from the handle it opened, with-- the read access it already holds, which any user may do against a pipe-- an elevated process or a service made.  The owner of a pipe is chosen by-- the process that makes it, from the accounts Windows lets that process-- own objects as, so it names who made the pipe-- ('Nix.Daemon.Auth.trustsPipeOwner' says which owners a client trusts).-- The daemon sets it explicitly, to Administrators where its token holds-- that group enabled and to its own account otherwise, rather than leave-- it to the default, which a security policy decides.  A process at Low-- integrity makes a pipe with the Low label, which a client refuses-- whoever owns it, since the daemon runs at Medium or above.  A client-- refuses a pipe no trusted account made, as it refuses one it cannot-- read the owner of.  A nova-nix command that reaches the store through a-- daemon connects with 'connectPipe'.---- == Who a client is---- The daemon impersonates a client as soon as it connects, before the-- client has sent anything, and reads its token's user and groups, in one-- C call, so the thread runs nothing else as the client ('clientAccount').-- A client the daemon refuses has sent nothing and holds nothing: its-- instance is closed and its thread ends.  The library's client opens the-- pipe letting the daemon identify it but not act as it ('connectPipe').-- A restricted token is not taken as its user's.  Which groups a client-- belongs to for @build-users-group@ is read from its account-- ('systemAccounts'), not from the token it presents, which it shapes.-- Whether the pipe is there is read without connecting to it-- ('pipePresent').---- == Waiting---- Every handle is opened for overlapped I/O, so a connection can be read-- and written at once.  Each call that waits, for a client, for bytes or-- for the pipe to take them, runs on a thread of its own with an event-- that ends its wait, and the thread that asks waits for it where an-- exception can interrupt the wait, as stopping a daemon or one of its-- connections does: a thread blocked in a foreign call could not be.  The-- interrupt sets the event and waits for the call to give up before it-- goes on.  The call runs beside the asking thread only under GHC's-- threaded runtime, which nova-nix is built with.module Nix.Daemon.Pipe  ( -- * The pipe's path    PipePath,    pipePath,    pipePathText,    defaultPipePath,    pipePresent,    -- * Who may use the pipe    PipeOwner (..),    pipeOwnerOf,    pipeSddl,    clientPipeAccess,    daemonPipeAccess,    processPipeOwner,    -- * The daemon's end    PipeInstance,    listenPipe,    nextInstance,    awaitClient,    dropClient,    clientAccount,    instanceTransport,    closeInstance,    -- * A client's end    PipeConnection,    connectPipe,    connectionTransport,    closeConnection,    -- * Accounts    systemAccounts,  )whereimport Control.Concurrent (forkIO)import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar)import Control.Exception (SomeException, bracket, finally, mask, onException, throwIO, try, uninterruptibleMask_)import Control.Monad (unless, void)import Control.Monad.Except (ExceptT (..), runExceptT, throwError)import Data.Bits ((.|.))import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Builder as BBimport qualified Data.ByteString.Lazy as BLimport Data.Char (ord)import Data.Maybe (fromMaybe)import Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Data.Word (Word32)import Foreign.C.String (CString, CWString, peekCString, peekCWString, peekCWStringLen, withCWString)import Foreign.C.Types (CInt (..), CULong (..))import Foreign.Marshal.Alloc (alloca, allocaBytes)import Foreign.Marshal.Utils (maybePeek)import Foreign.Ptr (Ptr, castPtr, nullPtr)import Foreign.Storable (peek)import Nix.Daemon.Auth (AccountDatabase (..), AccountKind (..), AccountPeer (..), trustsPipeOwner)import Nix.Daemon.Connection (Transport (..))import Nix.Store.Access (Sid, administratorsSid, sidFromText, sidText)import Numeric (showHex)import System.Win32.Event (setEvent)import System.Win32.File (closeHandle)import System.Win32.Types (BOOL, ErrCode, HANDLE, failIfFalse_, failIfNull, failWith, getErrorMessage, localFree, peekTString)-- ----------------------------------------------------------------------------- The pipe's path-- ----------------------------------------------------------------------------- | The path of a named pipe on this machine, @\\\\.\\pipe\\NAME@.-- 'pipePath' is the one way to make one.newtype PipePath = PipePath Text  deriving (Eq, Show)-- | A pipe's path from its bytes, UTF-8 as nova-nix holds a Windows path,-- or why they are not one: @\\\\.\\pipe\\@, its @pipe@ in either case,-- then a name of at least one character, at most 256 UTF-16 units in all,-- as Windows takes a pipe's name.  The name holds no separator of either-- kind and is not @.@ or @..@, which Windows would read as steps out of-- the pipes' namespace.pipePath :: ByteString -> Either Text PipePathpipePath bytes = case TE.decodeUtf8' bytes of  Left _ -> Left notAPipe  Right path    | let (prefix, name) = T.splitAt (T.length pipePrefix) path,      T.toLower prefix == pipePrefix,      name `notElem` ["", ".", ".."],      T.all (`notElem` ['\\', '/', '\0']) name,      utf16Length path <= maxPipePathUnits ->        Right (PipePath path)    | otherwise -> Left notAPipe  where    notAPipe = "not a named pipe's path, which is \\\\.\\pipe\\ and a name"    utf16Length = sum . map (\c -> if ord c > 0xFFFF then 2 else 1) . T.unpack-- | Where a pipe's path starts, as Windows spells the local machine's-- pipes, in lower case.pipePrefix :: TextpipePrefix = "\\\\.\\pipe\\"-- | The most UTF-16 units Windows takes in a pipe's whole path.maxPipePathUnits :: IntmaxPipePathUnits = 256-- | A pipe's path as text.pipePathText :: PipePath -> TextpipePathText (PipePath path) = path-- | The pipe a daemon listens on unless it is told another.defaultPipePath :: ByteStringdefaultPipePath = "\\\\.\\pipe\\nova-nix-daemon"-- | Whether a pipe exists at the path, as the pipe a daemon listens on-- does, read from the listing of the machine's pipes: nothing connects to-- it, so a daemon sees no client and loses no instance, and nothing-- waits.  A failure to list the pipes throws.pipePresent :: PipePath -> IO BoolpipePresent (PipePath path) =  withCWString (T.unpack path) $ \cPath ->    withCWString (T.unpack (T.drop (T.length pipePrefix) path)) $ \cName ->      alloca $ \presentOut -> alloca $ \failedOut -> do        code <- c_nn_pipe_present cPath cName presentOut failedOut        unless (code == 0) (throwFailure failedOut "nn_pipe_present" code)        (/= 0) <$> peek presentOut-- ----------------------------------------------------------------------------- Who may use the pipe-- ----------------------------------------------------------------------------- | Who owns the daemon's pipe, which decides who else the pipe's DACL-- names.data PipeOwner  = -- | Administrators, where the daemon's token holds the group enabled    -- and with the right to own objects as it, as an elevated    -- administrator's does.    OwnedByAdministrators  | -- | The daemon's own account, where its token does not.    OwnedByAccount !Sid  deriving (Eq, Show)-- | The owner a daemon makes of its pipe, given the SID its token lets it-- give one: Administrators, or its user.pipeOwnerOf :: Sid -> PipeOwnerpipeOwnerOf sid  | sid == administratorsSid = OwnedByAdministrators  | otherwise = OwnedByAccount sid-- | The SID of an owner.ownerSid :: PipeOwner -> SidownerSid = \case  OwnedByAdministrators -> administratorsSid  OwnedByAccount account -> account-- | The security descriptor every instance of the daemon's pipe is-- created with, given its owner: that owner, and a protected DACL that-- grants full control to SYSTEM and Administrators and 'clientPipeAccess'-- to Users, and, where the owner is the daemon's account and not-- Administrators, 'daemonPipeAccess' to that account.pipeSddl :: PipeOwner -> TextpipeSddl owner =  "O:"    <> sidText (ownerSid owner)    <> "D:P(A;;FA;;;SY)(A;;FA;;;BA)"    <> daemonEntry    <> "(A;;"    <> accessMask clientPipeAccess    <> ";;;BU)"  where    daemonEntry = case owner of      OwnedByAdministrators -> ""      OwnedByAccount account -> "(A;;" <> accessMask daemonPipeAccess <> ";;;" <> sidText account <> ")"    accessMask rights = "0x" <> T.pack (showHex rights "")-- | What the pipe grants Users, and the access the library's client opens-- it with: @FILE_GENERIC_READ@ and @FILE_WRITE_DATA@.  It leaves out-- @FILE_CREATE_PIPE_INSTANCE@, the bit @FILE_APPEND_DATA@ shares, which-- would let a user create an instance of the pipe; @GENERIC_WRITE@ asks-- for it, so a client asking for that is refused.  @FILE_GENERIC_READ@-- includes @READ_CONTROL@, the right a client reads the pipe's owner and-- label with.clientPipeAccess :: Word32clientPipeAccess = fileGenericRead .|. fileWriteData-- | What the pipe grants the daemon's own account, where it owns the pipe-- as that account: @FILE_GENERIC_READ@ and @FILE_GENERIC_WRITE@, which-- creating a further instance asks for (measured: leaving out-- @FILE_APPEND_DATA@, @FILE_WRITE_EA@ or @FILE_WRITE_ATTRIBUTES@ refuses-- it).  It has neither @WRITE_DAC@ nor @WRITE_OWNER@ nor @DELETE@.daemonPipeAccess :: Word32daemonPipeAccess = fileGenericRead .|. fileGenericWrite-- | @FILE_GENERIC_READ@, @FILE_GENERIC_WRITE@ and @FILE_WRITE_DATA@-- (winnt.h).fileGenericRead, fileGenericWrite, fileWriteData :: Word32fileGenericRead = 0x120089fileGenericWrite = 0x120116fileWriteData = 0x2-- | The owner the daemon makes of its pipe: Administrators where this-- process's token holds that group enabled, not for deny only, and with-- the right to own objects as it, as an elevated administrator's token-- does, and the token's user otherwise.  Windows lets a process give what-- it makes no other owner without the restore privilege, so a client that-- reads the owner ('connectPipe') learns who made the pipe.processPipeOwner :: IO PipeOwnerprocessPipeOwner = pipeOwnerOf <$> readSid "nn_token_pipe_owner" (c_nn_token_pipe_owner nullPtr)-- ----------------------------------------------------------------------------- The daemon's end-- ----------------------------------------------------------------------------- | An instance of the daemon's pipe: waiting for a client, or connected-- to one, with what the next instance is created with.data PipeInstance = PipeInstance  { instancePath :: !PipePath,    instanceSddl :: !Text,    instanceHandle :: !HANDLE  }-- | Which instance of a pipe is being created.data InstanceOrder  = -- | The first, which fails where the pipe already exists.    FirstInstance  | -- | Another of a pipe this daemon made.    LaterInstance-- | Create the pipe at the path, its first instance, owned by-- 'processPipeOwner' and open to whom 'pipeSddl' says, or say why it-- cannot be: among the reasons, that a process already has the pipe.listenPipe :: PipePath -> IO (Either Text PipeInstance)listenPipe path = do  owner <- processPipeOwner  createInstance FirstInstance path (pipeSddl owner)-- | Another instance of the pipe an instance is of, for the next client,-- or why it cannot be made.nextInstance :: PipeInstance -> IO (Either Text PipeInstance)nextInstance previous = createInstance LaterInstance (instancePath previous) (instanceSddl previous)-- | Create an instance of a pipe with a security descriptor.createInstance :: InstanceOrder -> PipePath -> Text -> IO (Either Text PipeInstance)createInstance order path sddl =  withCWString (T.unpack (pipePathText path)) $ \cPath ->    withCWString (T.unpack sddl) $ \cSddl ->      alloca $ \pipeOut -> alloca $ \failedOut -> do        code <- c_nn_pipe_create cPath firstFlag cSddl pipeOut failedOut        case (code, order) of          (0, _) -> Right . PipeInstance path sddl <$> peek pipeOut          (_, FirstInstance) | code == errorAccessDenied -> pure (Left "a process already has the pipe open")          _ -> Left <$> failureMessage failedOut "nn_pipe_create" code  where    firstFlag = case order of      FirstInstance -> 1      LaterInstance -> 0-- | Wait for a client to connect to the instance.  A failure throws, as a-- socket's accept does.awaitClient :: PipeInstance -> IO ()awaitClient inst =  alloca $ \failedOut -> do    code <- interruptibly (\stop -> c_nn_pipe_accept (instanceHandle inst) stop failedOut)    unless (code == 0) (throwFailure failedOut "nn_pipe_accept" code)-- | Disconnect the client of an instance, which then waits for another.dropClient :: PipeInstance -> IO ()dropClient inst = failIfFalse_ "DisconnectNamedPipe" (c_DisconnectNamedPipe (instanceHandle inst))-- | Who the client connected to the instance is, read from its token, or-- why that cannot be read or is not taken.  The client need not have sent-- anything.  A restricted token is not taken as its user's: it may hold-- the user's SID and still be kept from what the user may do.clientAccount :: PipeInstance -> IO (Either Text AccountPeer)clientAccount inst =  alloca $ \processOut -> alloca $ \restrictedOut -> alloca $ \sidsOut -> alloca $ \charsOut -> alloca $ \failedOut -> do    code <- c_nn_pipe_client (instanceHandle inst) processOut restrictedOut sidsOut charsOut failedOut    if code /= 0      then Left . ("cannot read who the client is: " <>) <$> failureMessage failedOut "nn_pipe_client" code      else do        process <- peek processOut        restricted <- peek restrictedOut        sids <- peek sidsOut        chars <- peek charsOut        spelled <- (T.pack <$> peekCWStringLen (sids, fromIntegral chars)) `finally` localFree sids        pure $          if restricted /= 0            then Left "the client's token is restricted, so it is not taken as its user's"            else maybe (Left ("cannot read who the client is: its token gave " <> T.pack (show spelled))) Right (accountFrom (Just (fromIntegral process)) spelled)-- | A client's account from the SIDs its token gave, as 'clientAccount'-- reads them: its user and then the groups it grants by, each ended by a-- NUL.accountFrom :: Maybe Word32 -> Text -> Maybe AccountPeeraccountFrom process spelled = case T.splitOn "\0" spelled of  userText : groupTexts -> do    user <- sidFromText userText    -- The last SID's NUL leaves an empty piece at the end.    groups <- traverse sidFromText (filter (not . T.null) groupTexts)    Just (AccountPeer process user groups)  [] -> Nothing-- | The connection to the client of an instance.instanceTransport :: PipeInstance -> Transport IOinstanceTransport = handleTransport . instanceHandle-- | Close an instance, and with it any connection to its client.  What-- it wrote and the client has not read stays for the client to read.closeInstance :: PipeInstance -> IO ()closeInstance = closeHandle . instanceHandle-- ----------------------------------------------------------------------------- A client's end-- ----------------------------------------------------------------------------- | A client's connection to a daemon's pipe.newtype PipeConnection = PipeConnection HANDLE-- | Connect to the daemon at a pipe, letting it identify this process's-- account but not act as it, or say why not: among the reasons, that no-- process has the pipe, as when no daemon runs, that no trusted account-- made it ('Nix.Daemon.Auth.trustsPipeOwner'), and that a process below-- Medium integrity did.  The pipe's owner and integrity are read before-- anything is sent, and a pipe whose owner is not trusted, or whose owner-- or integrity cannot be read, is closed unused.  While every instance is-- busy it waits a bounded while for one.connectPipe :: PipePath -> IO (Either Text PipeConnection)connectPipe path =  withCWString (T.unpack (pipePathText path)) $ \cPath ->    alloca $ \pipeOut -> alloca $ \failedOut -> do      code <- c_nn_pipe_open cPath (fromIntegral clientPipeAccess) pipeOut failedOut      if code == 0        then peek pipeOut >>= \handle -> vetServer path handle `onException` closeHandle handle        else Left <$> failureMessage failedOut "nn_pipe_open" code-- | Keep an opened pipe as the connection if a trusted account owns it-- and it is at least Medium integrity, and close it, saying why, if not.vetServer :: PipePath -> HANDLE -> IO (Either Text PipeConnection)vetServer path handle = do  client <- processAccount  verdict <- runExceptT $ do    owner <- ExceptT (handleOwner handle)    unless (trustsPipeOwner client owner) (throwError ("it belongs to " <> sidText owner <> ", not to you, SYSTEM, Administrators or the nova-nix service"))    level <- ExceptT (handleIntegrity handle)    unless (level >= mediumIntegrity) (throwError ("it was made by a process below Medium integrity (level 0x" <> T.pack (showHex level "") <> ")"))  case verdict of    Right () -> pure (Right (PipeConnection handle))    Left reason -> Left (notTrusted <> reason) <$ closeHandle handle  where    notTrusted = "the pipe '" <> pipePathText path <> "' is not served by a trusted account: "-- | The mandatory label RID of Medium integrity (winnt.h's-- @SECURITY_MANDATORY_MEDIUM_RID@): the lowest level a daemon runs at.mediumIntegrity :: Word32mediumIntegrity = 0x2000-- | The account that owns the pipe a handle is open to, or why that is-- not known.handleOwner :: HANDLE -> IO (Either Text Sid)handleOwner handle =  alloca $ \sidOut -> alloca $ \failedOut -> do    code <- c_nn_pipe_owner handle sidOut failedOut    if code /= 0      then Left . ("its owner cannot be read: " <>) <$> failureMessage failedOut "nn_pipe_owner" code      else do        found <- peek sidOut        if found == nullPtr          then pure (Left "it has no owner")          else either (Left . ("its owner is not a SID: " <>)) Right <$> takeSid found-- | The integrity level of the pipe a handle is open to, its mandatory-- label's RID, Medium where it has no label, or why that is not known.handleIntegrity :: HANDLE -> IO (Either Text Word32)handleIntegrity handle =  alloca $ \levelOut -> alloca $ \failedOut -> do    code <- c_nn_pipe_integrity handle levelOut failedOut    if code /= 0      then Left . ("its integrity level cannot be read: " <>) <$> failureMessage failedOut "nn_pipe_integrity" code      else Right . fromIntegral <$> peek levelOut-- | The connection to the daemon.connectionTransport :: PipeConnection -> Transport IOconnectionTransport (PipeConnection handle) = handleTransport handle-- | Close the connection.closeConnection :: PipeConnection -> IO ()closeConnection (PipeConnection handle) = closeHandle handle-- ----------------------------------------------------------------------------- Reading and writing-- ----------------------------------------------------------------------------- | How much a read from the pipe asks for.receiveChunkSize :: IntreceiveChunkSize = 65536-- | A connection's transport over its end of the pipe.  The other end's-- close is the end of input, which every read after it gives too; any-- other failure throws.handleTransport :: HANDLE -> Transport IOhandleTransport handle =  Transport    { transportReceive = receive,      transportSend = mapM_ (sendChunk handle) . concatMap writable . BL.toChunks . BB.toLazyByteString    }  where    receive =      allocaBytes receiveChunkSize $ \buffer -> alloca $ \gotOut -> alloca $ \failedOut -> do        code <- interruptibly (\stop -> c_nn_pipe_read handle buffer (fromIntegral receiveChunkSize) stop gotOut failedOut)        got <- peek gotOut        case code of          0            -- A write of nothing at the other end arrives as a read of            -- nothing, which is not the end of input.            | got == 0 -> receive            | otherwise -> Just <$> BS.packCStringLen (castPtr buffer, fromIntegral got)          _            | code `elem` [errorBrokenPipe, errorPipeNotConnected] -> pure Nothing            | otherwise -> throwFailure failedOut "nn_pipe_read" code-- | A chunk in pieces a write can take, a write's size being a DWORD.writable :: ByteString -> [ByteString]writable chunk  | BS.length chunk <= maxWriteBytes = [chunk]  | otherwise = let (piece, rest) = BS.splitAt maxWriteBytes chunk in piece : writable rest-- | The most bytes one write to the pipe takes.maxWriteBytes :: IntmaxWriteBytes = fromIntegral (maxBound :: Word32)-- | Write a chunk to the pipe, all of it, before returning.sendChunk :: HANDLE -> ByteString -> IO ()sendChunk handle chunk =  BS.useAsCStringLen chunk $ \(bytes, size) -> alloca $ \failedOut -> do    code <- interruptibly (\stop -> c_nn_pipe_write handle (castPtr bytes) (fromIntegral size) stop failedOut)    unless (code == 0) (throwFailure failedOut "nn_pipe_write" code)-- | Run a call that waits until it is done or the event it is given is-- set, on a thread of its own, and wait for it here, where an exception-- can interrupt the wait.  The exception sets the event, waits for the-- call to give up, so nothing the call uses is released under it, and-- goes on.  The call's outcome is read and left in place rather than-- taken, so an exception that arrives as the call ends still finds it.-- The call's own failure, which it cannot raise on the thread that asked,-- is carried to that thread and raised there.interruptibly :: (HANDLE -> IO a) -> IO ainterruptibly call =  bracket newStopEvent closeHandle $ \stop -> mask $ \restore -> do    outcome <- newEmptyMVar    _ <- forkIO (try (call stop) >>= putMVar outcome)    finished <- restore (readMVar outcome) `onException` (setEvent stop `finally` uninterruptibleMask_ (readMVar outcome))    either (\(failure :: SomeException) -> throwIO failure) pure finished-- | A manual-reset event, not set, with no name, for 'interruptibly'.newStopEvent :: IO HANDLEnewStopEvent = failIfNull "CreateEventW" (c_CreateEventW nullPtr True False nullPtr)-- ----------------------------------------------------------------------------- Accounts-- ----------------------------------------------------------------------------- | This machine's accounts as Windows resolves them: a name or a SID it-- finds no account for is not found, and one it fails to look up is a-- failure, which is not an answer.systemAccounts :: AccountDatabase IOsystemAccounts = AccountDatabase {adAccountSid = accountSid, adAccountName = accountName, adAccountGroups = groupsOf}-- | The SID an account's name, UTF-8, names, as LookupAccountNameW finds-- one of the kind: an account of this machine where the name names no-- domain.  A name with no UTF-8 reading, or holding a NUL, names no-- account.accountSid :: AccountKind -> ByteString -> IO (Either Text (Maybe Sid))accountSid kind bytes = case TE.decodeUtf8' bytes of  Right name    | not (T.any (== '\0') name) ->        withCWString (T.unpack name) $ \cName -> alloca $ \sidOut -> alloca $ \failedOut -> do          code <- c_nn_account_sid cName kindCode sidOut failedOut          if code /= 0            then Left <$> failureMessage failedOut "nn_account_sid" code            else do              found <- peek sidOut              if found == nullPtr                then pure (Right Nothing)                else either (Left . ("an account's SID is not one: " <>)) (Right . Just) <$> takeSid found  _ -> pure (Right Nothing)  where    -- NN_ACCOUNT_USER and NN_ACCOUNT_GROUP (cbits/nn_winfs.h).    kindCode = case kind of      UserAccount -> 0      GroupAccount -> 1-- | Every group an account belongs to, as Windows computes them from the-- account, or why it cannot say.groupsOf :: Sid -> IO (Either Text [Sid])groupsOf sid =  withCWString (T.unpack (sidText sid)) $ \cSid -> alloca $ \sidsOut -> alloca $ \charsOut -> alloca $ \failedOut -> do    code <- c_nn_account_groups cSid sidsOut charsOut failedOut    if code /= 0      then Left <$> failureMessage failedOut "nn_account_groups" code      else do        sids <- peek sidsOut        chars <- peek charsOut        spelled <- (T.pack <$> peekCWStringLen (sids, fromIntegral chars)) `finally` localFree sids        pure (maybe (Left ("the groups Windows gave are not SIDs: " <> T.pack (show spelled))) Right (traverse sidFromText (filter (not . T.null) (T.splitOn "\0" spelled))))-- | An account's name, @DOMAIN\\NAME@, UTF-8, as LookupAccountSidW finds-- it.accountName :: Sid -> IO (Maybe ByteString)accountName sid =  withCWString (T.unpack (sidText sid)) $ \cSid -> alloca $ \nameOut -> alloca $ \failedOut -> do    code <- c_nn_account_name cSid nameOut failedOut    found <- peek nameOut    if code /= 0 || found == nullPtr      then pure Nothing      else (Just . TE.encodeUtf8 . T.pack <$> peekCWString found) `finally` localFree found-- | The account this process runs as, its token's user.processAccount :: IO SidprocessAccount = readSid "nn_token_user_sid" c_nn_token_user_sid-- | The SID a call writes as a string, or the failure of the call, thrown.readSid :: String -> (Ptr CWString -> Ptr CString -> IO ErrCode) -> IO SidreadSid shim call =  alloca $ \sidOut -> alloca $ \failedOut -> do    code <- call sidOut failedOut    unless (code == 0) (throwFailure failedOut shim code)    peek sidOut >>= takeSid >>= either (\spelled -> ioError (userError (shim <> " gave " <> show spelled <> ", which is not a SID"))) pure-- | A SID a call wrote as a string for the caller to release, read and-- released, or the text where it is not a SID.takeSid :: CWString -> IO (Either Text Sid)takeSid found = do  spelled <- (T.pack <$> peekCWString found) `finally` localFree found  pure (maybe (Left spelled) Right (sidFromText spelled))-- ----------------------------------------------------------------------------- Failures-- ----------------------------------------------------------------------------- | Win32 errors the pipe's callers tell apart (winerror.h): a pipe that-- already exists, as a first instance finds it, and the other end gone.errorAccessDenied, errorBrokenPipe, errorPipeNotConnected :: ErrCodeerrorAccessDenied = 5errorBrokenPipe = 109errorPipeNotConnected = 233-- | The call a shim names as the one that failed, or the shim's own name-- where it names none.failedCall :: Ptr CString -> String -> IO StringfailedCall failedOut shim = fromMaybe shim <$> (maybePeek peekCString =<< peek failedOut)-- | Throw a Win32 failure as the 'IOError' Win32 raises for one, naming-- the call that failed.throwFailure :: Ptr CString -> String -> ErrCode -> IO athrowFailure failedOut shim code = failedCall failedOut shim >>= \call -> failWith call code-- | A Win32 failure as a message: the call that failed and Windows' words-- for the error.failureMessage :: Ptr CString -> String -> ErrCode -> IO TextfailureMessage failedOut shim code = do  call <- failedCall failedOut shim  described <- bracket (getErrorMessage code) (void . localFree) $ \message ->    if message == nullPtr then pure ("Win32 error " <> show code) else peekTString message  pure (T.pack call <> ": " <> T.strip (T.pack described))-- ----------------------------------------------------------------------------- Foreign calls-- ----------------------------------------------------------------------------- The calls that wait are safe, so they block only the thread-- 'interruptibly' runs them on.foreign import ccall unsafe "nn_winfs.h nn_pipe_create"  c_nn_pipe_create :: CWString -> CInt -> CWString -> Ptr HANDLE -> Ptr CString -> IO ErrCodeforeign import ccall safe "nn_winfs.h nn_pipe_accept"  c_nn_pipe_accept :: HANDLE -> HANDLE -> Ptr CString -> IO ErrCodeforeign import ccall safe "nn_winfs.h nn_pipe_read"  c_nn_pipe_read :: HANDLE -> Ptr () -> CULong -> HANDLE -> Ptr CULong -> Ptr CString -> IO ErrCodeforeign import ccall safe "nn_winfs.h nn_pipe_write"  c_nn_pipe_write :: HANDLE -> Ptr () -> CULong -> HANDLE -> Ptr CString -> IO ErrCodeforeign import ccall unsafe "nn_winfs.h nn_pipe_client"  c_nn_pipe_client :: HANDLE -> Ptr CULong -> Ptr CInt -> Ptr CWString -> Ptr CULong -> Ptr CString -> IO ErrCodeforeign import ccall unsafe "nn_winfs.h nn_pipe_present"  c_nn_pipe_present :: CWString -> CWString -> Ptr CInt -> Ptr CString -> IO ErrCodeforeign import ccall safe "nn_winfs.h nn_pipe_open"  c_nn_pipe_open :: CWString -> CULong -> Ptr HANDLE -> Ptr CString -> IO ErrCodeforeign import ccall unsafe "nn_winfs.h nn_pipe_owner"  c_nn_pipe_owner :: HANDLE -> Ptr CWString -> Ptr CString -> IO ErrCodeforeign import ccall unsafe "nn_winfs.h nn_token_pipe_owner"  c_nn_token_pipe_owner :: HANDLE -> Ptr CWString -> Ptr CString -> IO ErrCodeforeign import ccall unsafe "nn_winfs.h nn_pipe_integrity"  c_nn_pipe_integrity :: HANDLE -> Ptr CULong -> Ptr CString -> IO ErrCodeforeign import ccall safe "nn_winfs.h nn_account_sid"  c_nn_account_sid :: CWString -> CInt -> Ptr CWString -> Ptr CString -> IO ErrCodeforeign import ccall safe "nn_winfs.h nn_account_groups"  c_nn_account_groups :: CWString -> Ptr CWString -> Ptr CULong -> Ptr CString -> IO ErrCodeforeign import ccall safe "nn_winfs.h nn_account_name"  c_nn_account_name :: CWString -> Ptr CWString -> Ptr CString -> IO ErrCodeforeign import ccall unsafe "nn_winfs.h nn_token_user_sid"  c_nn_token_user_sid :: Ptr CWString -> Ptr CString -> IO ErrCodeforeign import ccall unsafe "windows.h CreateEventW"  c_CreateEventW :: Ptr () -> BOOL -> BOOL -> CWString -> IO HANDLEforeign import ccall unsafe "windows.h DisconnectNamedPipe"  c_DisconnectNamedPipe :: HANDLE -> IO BOOL