packages feed

nova-nix-0.11.0.0 / cbits / nn_winfs.c

#include "nn_winfs.h"#ifdef _WIN32#include <windows.h>#include <aclapi.h>#include <authz.h>#include <sddl.h>#include <stdlib.h>#include <string.h>#include <winternl.h>/* FileCaseSensitiveInformation and its flag are absent from older SDK and * MinGW headers; both values are fixed ABI, defined locally. */enum { NN_FILE_CASE_SENSITIVE_INFORMATION = 71 };#ifndef FILE_CS_FLAG_CASE_SENSITIVE_DIR#define FILE_CS_FLAG_CASE_SENSITIVE_DIR 0x00000001#endiftypedef struct nn_file_case_sensitive_info {  ULONG flags;} nn_file_case_sensitive_info;typedef NTSTATUS(NTAPI *nn_nt_set_information_file)(HANDLE, PIO_STATUS_BLOCK,                                                    PVOID, ULONG, ULONG);int nn_dir_set_case_sensitive(const wchar_t *path) {  HMODULE ntdll;  nn_nt_set_information_file set_information_file;  HANDLE dir;  nn_file_case_sensitive_info info;  IO_STATUS_BLOCK iosb;  NTSTATUS status;  /* NtSetInformationFile is the documented route to the per-directory   * flag (fsutil and WSL use it); resolved dynamically because it lives   * in ntdll, which is always loaded but not in the link line. */  ntdll = GetModuleHandleW(L"ntdll.dll");  if (ntdll == NULL) {    return 0;  }  set_information_file =      (nn_nt_set_information_file)GetProcAddress(ntdll, "NtSetInformationFile");  if (set_information_file == NULL) {    return 0;  }  dir = CreateFileW(path, FILE_WRITE_ATTRIBUTES,                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,                    NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);  if (dir == INVALID_HANDLE_VALUE) {    return 0;  }  info.flags = FILE_CS_FLAG_CASE_SENSITIVE_DIR;  status = set_information_file(dir, &iosb, &info, sizeof info,                                NN_FILE_CASE_SENSITIVE_INFORMATION);  CloseHandle(dir);  return status >= 0 ? 1 : 0;}/* The user of the token, in the string form ConvertSidToStringSidW * writes, written to *sid for the caller to release with LocalFree. */static DWORD token_user_sid(HANDLE token, wchar_t **sid,                            const char **failed) {  /* A TOKEN_USER is followed in the buffer by the SID it points at, which   * is at most SECURITY_MAX_SID_SIZE bytes, so one call fills it.  The   * union aligns the buffer for the structure. */  union {    TOKEN_USER user;    BYTE bytes[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE];  } buffer;  DWORD size;  if (!GetTokenInformation(token, TokenUser, &buffer, sizeof buffer, &size)) {    *failed = "GetTokenInformation";    return GetLastError();  }  if (!ConvertSidToStringSidW(buffer.user.User.Sid, sid)) {    *failed = "ConvertSidToStringSidW";    *sid = NULL;    return GetLastError();  }  return ERROR_SUCCESS;}unsigned long nn_token_user_sid(wchar_t **sid, const char **failed) {  HANDLE token;  DWORD error;  *sid = NULL;  *failed = NULL;  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {    *failed = "OpenProcessToken";    return GetLastError();  }  error = token_user_sid(token, sid, failed);  CloseHandle(token);  return error;}unsigned long nn_dir_create_sddl(const wchar_t *path, const wchar_t *sddl) {  PSECURITY_DESCRIPTOR descriptor = NULL;  SECURITY_ATTRIBUTES attributes;  DWORD error = ERROR_SUCCESS;  if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(          sddl, SDDL_REVISION_1, &descriptor, NULL)) {    return GetLastError();  }  attributes.nLength = sizeof attributes;  attributes.lpSecurityDescriptor = descriptor;  attributes.bInheritHandle = FALSE;  if (!CreateDirectoryW(path, &attributes)) {    error = GetLastError();  }  LocalFree(descriptor);  return error;}unsigned long nn_entry_security(const wchar_t *path, void **descriptor,                                unsigned long *length, const char **failed) {  HANDLE entry;  PSECURITY_DESCRIPTOR read = NULL;  DWORD error;  *descriptor = NULL;  *length = 0;  *failed = NULL;  /* READ_CONTROL is the one right reading an owner and a DACL takes.   * FILE_FLAG_BACKUP_SEMANTICS lets a directory be opened at all, and   * FILE_FLAG_OPEN_REPARSE_POINT opens a link itself, not what it leads   * to. */  entry = CreateFileW(path, READ_CONTROL,                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,                      NULL, OPEN_EXISTING,                      FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,                      NULL);  if (entry == INVALID_HANDLE_VALUE) {    *failed = "CreateFileW";    return GetLastError();  }  error =      GetSecurityInfo(entry, SE_FILE_OBJECT,                      OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,                      NULL, NULL, NULL, NULL, &read);  CloseHandle(entry);  if (error != ERROR_SUCCESS) {    *failed = "GetSecurityInfo";    return error;  }  *descriptor = read;  *length = GetSecurityDescriptorLength(read);  return ERROR_SUCCESS;}/* Whether this process's token is granted access by the owner and DACL of * a descriptor, as AccessCheck decides.  AccessCheck takes an impersonation * token, so the process's is duplicated as one.  *granted is set only when * the check is made. */static unsigned long descriptor_grants(PSECURITY_DESCRIPTOR descriptor,                                       DWORD access, int *granted,                                       const char **failed) {  HANDLE process_token = NULL;  HANDLE token = NULL;  GENERIC_MAPPING mapping;  PRIVILEGE_SET privileges;  DWORD privileges_length = sizeof privileges;  DWORD granted_access = 0;  BOOL allowed = FALSE;  DWORD error = ERROR_SUCCESS;  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE,                        &process_token)) {    *failed = "OpenProcessToken";    return GetLastError();  }  if (!DuplicateToken(process_token, SecurityImpersonation, &token)) {    *failed = "DuplicateToken";    error = GetLastError();    CloseHandle(process_token);    return error;  }  CloseHandle(process_token);  mapping.GenericRead = FILE_GENERIC_READ;  mapping.GenericWrite = FILE_GENERIC_WRITE;  mapping.GenericExecute = FILE_GENERIC_EXECUTE;  mapping.GenericAll = FILE_ALL_ACCESS;  if (AccessCheck(descriptor, token, access, &mapping, &privileges,                  &privileges_length, &granted_access, &allowed)) {    *granted = allowed ? 1 : 0;  } else {    *failed = "AccessCheck";    error = GetLastError();  }  CloseHandle(token);  return error;}unsigned long nn_dir_access(const wchar_t *path, unsigned long access,                            int *granted, const char **failed) {  HANDLE directory;  PSECURITY_DESCRIPTOR descriptor = NULL;  DWORD error;  *granted = 0;  *failed = NULL;  /* READ_CONTROL is the one right reading the owner, group and DACL takes,   * and AccessCheck wants the owner and the group both.   * FILE_FLAG_BACKUP_SEMANTICS lets a directory be opened at all. */  directory = CreateFileW(path, READ_CONTROL,                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,                          NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);  if (directory == INVALID_HANDLE_VALUE) {    *failed = "CreateFileW";    return GetLastError();  }  error = GetSecurityInfo(directory, SE_FILE_OBJECT,                          OWNER_SECURITY_INFORMATION |                              GROUP_SECURITY_INFORMATION |                              DACL_SECURITY_INFORMATION,                          NULL, NULL, NULL, NULL, &descriptor);  CloseHandle(directory);  if (error != ERROR_SUCCESS) {    *failed = "GetSecurityInfo";    return error;  }  error = descriptor_grants(descriptor, access, granted, failed);  LocalFree(descriptor);  return error;}/* A local account's name, qualified by the computer's NetBIOS name so * the lookup searches this machine's accounts alone and never a domain's, * fits in this many characters with room to spare: a NetBIOS name is at * most 15 and a local account's name at most 256. */enum { NN_QUALIFIED_NAME_CHARS = 300 };/* Write name qualified by the computer's name (COMPUTER\name) to * qualified, which holds NN_QUALIFIED_NAME_CHARS characters.  Returns * ERROR_INSUFFICIENT_BUFFER, leaving *failed alone, where the qualified * name is longer than any account's, which so names none. */static DWORD qualified_local_name(const wchar_t *name, wchar_t *qualified,                                  const char **failed) {  DWORD computerChars = MAX_COMPUTERNAME_LENGTH + 1;  size_t nameChars = wcslen(name);  if (!GetComputerNameW(qualified, &computerChars)) {    *failed = "GetComputerNameW";    return GetLastError();  }  if (computerChars + 1 + nameChars + 1 > NN_QUALIFIED_NAME_CHARS) {    return ERROR_INSUFFICIENT_BUFFER;  }  qualified[computerChars] = L'\\';  wmemcpy(qualified + computerChars + 1, name, nameChars + 1);  return ERROR_SUCCESS;}unsigned long nn_local_group_sid(const wchar_t *name, wchar_t **sid,                                 const char **failed) {  wchar_t qualified[NN_QUALIFIED_NAME_CHARS];  union {    SID sid;    BYTE bytes[SECURITY_MAX_SID_SIZE];  } found;  DWORD sidSize = sizeof found;  wchar_t domain[MAX_COMPUTERNAME_LENGTH + 1];  DWORD domainChars = MAX_COMPUTERNAME_LENGTH + 1;  SID_NAME_USE use;  DWORD error;  *sid = NULL;  *failed = NULL;  error = qualified_local_name(name, qualified, failed);  if (error == ERROR_INSUFFICIENT_BUFFER) {    *failed = "nn_local_group_sid";    return ERROR_INVALID_PARAMETER;  }  if (error != ERROR_SUCCESS) {    return error;  }  if (!LookupAccountNameW(NULL, qualified, &found.sid, &sidSize, domain,                          &domainChars, &use)) {    error = GetLastError();    if (error == ERROR_NONE_MAPPED) {      return ERROR_SUCCESS;    }    *failed = "LookupAccountNameW";    return error;  }  if (use != SidTypeAlias) {    return ERROR_SUCCESS;  }  if (!ConvertSidToStringSidW(&found.sid, sid)) {    *failed = "ConvertSidToStringSidW";    *sid = NULL;    return GetLastError();  }  return ERROR_SUCCESS;}unsigned long nn_descriptor_from_sddl(const wchar_t *sddl, void **descriptor) {  PSECURITY_DESCRIPTOR made = NULL;  *descriptor = NULL;  if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(          sddl, SDDL_REVISION_1, &made, NULL)) {    return GetLastError();  }  *descriptor = made;  return ERROR_SUCCESS;}unsigned long nn_entry_set_owner_dacl(const wchar_t *path, void *descriptor,                                      const char **failed) {  PSID owner = NULL;  PACL dacl = NULL;  BOOL present = FALSE;  BOOL defaulted = FALSE;  HANDLE entry;  DWORD error;  *failed = NULL;  if (!GetSecurityDescriptorOwner(descriptor, &owner, &defaulted)) {    *failed = "GetSecurityDescriptorOwner";    return GetLastError();  }  if (!GetSecurityDescriptorDacl(descriptor, &present, &dacl, &defaulted)) {    *failed = "GetSecurityDescriptorDacl";    return GetLastError();  }  /* WRITE_OWNER and WRITE_DAC are the rights the two writes take, and   * READ_CONTROL lets the write read what it keeps.  The flags open a   * directory, and a link itself rather than what it leads to. */  entry = CreateFileW(path, READ_CONTROL | WRITE_DAC | WRITE_OWNER,                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,                      NULL, OPEN_EXISTING,                      FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,                      NULL);  if (entry == INVALID_HANDLE_VALUE) {    *failed = "CreateFileW";    return GetLastError();  }  error = SetSecurityInfo(entry, SE_FILE_OBJECT,                          OWNER_SECURITY_INFORMATION |                              DACL_SECURITY_INFORMATION |                              PROTECTED_DACL_SECURITY_INFORMATION,                          owner, NULL, dacl, NULL);  CloseHandle(entry);  if (error != ERROR_SUCCESS) {    *failed = "SetSecurityInfo";  }  return error;}unsigned long nn_job_die_on_unhandled_exception(void *job, const char **failed) {  JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits;  *failed = NULL;  /* The limits are set as a whole, so the job's own, the process   * library's KILL_ON_JOB_CLOSE among them, are read first and kept. */  if (!QueryInformationJobObject(job, JobObjectExtendedLimitInformation,                                 &limits, sizeof limits, NULL)) {    *failed = "QueryInformationJobObject";    return GetLastError();  }  limits.BasicLimitInformation.LimitFlags |=      JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;  if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation,                               &limits, sizeof limits)) {    *failed = "SetInformationJobObject";    return GetLastError();  }  return ERROR_SUCCESS;}/* What each direction of a pipe instance holds before a write waits for * the reader. */enum { NN_PIPE_BUFFER_BYTES = 65536 };/* How long, in milliseconds, a client waits for an instance of the pipe * while every one is busy, and how many such waits it makes before it * gives up.  The daemon makes its next instance as soon as a client * connects to the last, so a client finds none free only in that moment, * and a wait runs out only where the daemon has stopped making them.  A * client can be sent back to wait by another that takes the instance that * freed, so it waits again, but not for ever. */enum { NN_PIPE_BUSY_WAIT_MS = 5000, NN_PIPE_OPEN_ATTEMPTS = 4 };/* An account's or a domain's name fits in this many characters with its * NUL: a user's or a group's name is at most 256 (UNLEN, GNLEN), and a * domain's DNS name at most 255. */enum { NN_ACCOUNT_CHARS = 257 };/* Begin an overlapped operation's record, with the manual-reset event the * system sets as the operation ends. */static DWORD overlapped_begin(OVERLAPPED *overlapped, const char **failed) {  memset(overlapped, 0, sizeof *overlapped);  overlapped->hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);  if (overlapped->hEvent == NULL) {    *failed = "CreateEventW";    return GetLastError();  }  return ERROR_SUCCESS;}/* Wait for the overlapped operation begun on handle to end, or for stop to * be set, which cancels it.  The operation is waited for to its end * either way, since the system writes its record until then; one that * ended before the cancel keeps its result.  *transferred gets the bytes * it moved.  An operation that failed leaves *failed as the caller set it, * naming the operation. */static DWORD overlapped_finish(HANDLE handle, OVERLAPPED *overlapped,                               HANDLE stop, DWORD *transferred,                               const char **failed) {  HANDLE events[2];  DWORD woken;  DWORD waitError = ERROR_SUCCESS;  events[0] = overlapped->hEvent;  events[1] = stop;  woken = WaitForMultipleObjects(2, events, FALSE, INFINITE);  if (woken == WAIT_FAILED) {    waitError = GetLastError();  }  if (woken != WAIT_OBJECT_0) {    (void)CancelIoEx(handle, overlapped);  }  if (!GetOverlappedResult(handle, overlapped, transferred, TRUE)) {    if (waitError != ERROR_SUCCESS) {      *failed = "WaitForMultipleObjects";      return waitError;    }    return GetLastError();  }  return ERROR_SUCCESS;}unsigned long nn_pipe_create(const wchar_t *name, int first,                             const wchar_t *sddl, void **pipe,                             const char **failed) {  PSECURITY_DESCRIPTOR descriptor = NULL;  SECURITY_ATTRIBUTES attributes;  DWORD openMode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED;  HANDLE made;  DWORD error = ERROR_SUCCESS;  *pipe = NULL;  *failed = NULL;  if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(          sddl, SDDL_REVISION_1, &descriptor, NULL)) {    *failed = "ConvertStringSecurityDescriptorToSecurityDescriptorW";    return GetLastError();  }  /* Not inheritable, so no process the daemon starts, a builder among   * them, holds a client's connection open. */  attributes.nLength = sizeof attributes;  attributes.lpSecurityDescriptor = descriptor;  attributes.bInheritHandle = FALSE;  if (first) {    openMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;  }  made = CreateNamedPipeW(      name, openMode,      PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT |          PIPE_REJECT_REMOTE_CLIENTS,      PIPE_UNLIMITED_INSTANCES, NN_PIPE_BUFFER_BYTES, NN_PIPE_BUFFER_BYTES,      NN_PIPE_BUSY_WAIT_MS, &attributes);  if (made == INVALID_HANDLE_VALUE) {    *failed = "CreateNamedPipeW";    error = GetLastError();  } else {    *pipe = made;  }  LocalFree(descriptor);  return error;}unsigned long nn_pipe_accept(void *pipe, void *stop, const char **failed) {  OVERLAPPED overlapped;  DWORD unused;  DWORD error;  *failed = NULL;  error = overlapped_begin(&overlapped, failed);  if (error != ERROR_SUCCESS) {    return error;  }  for (;;) {    *failed = "ConnectNamedPipe";    (void)ResetEvent(overlapped.hEvent);    if (ConnectNamedPipe(pipe, &overlapped)) {      error = ERROR_SUCCESS;    } else {      error = GetLastError();      if (error == ERROR_IO_PENDING) {        error = overlapped_finish(pipe, &overlapped, stop, &unused, failed);      } else if (error == ERROR_PIPE_CONNECTED) {        /* The client connected between the instance's making and this         * call. */        error = ERROR_SUCCESS;      }    }    if (error != ERROR_NO_DATA) {      break;    }    /* The client closed its end before the instance waited for it, and     * the instance takes no other client until it is disconnected. */    if (!DisconnectNamedPipe(pipe)) {      *failed = "DisconnectNamedPipe";      error = GetLastError();      break;    }  }  CloseHandle(overlapped.hEvent);  if (error == ERROR_SUCCESS) {    *failed = NULL;  }  return error;}unsigned long nn_pipe_read(void *pipe, void *buffer, unsigned long size,                           void *stop, unsigned long *got,                           const char **failed) {  OVERLAPPED overlapped;  DWORD read = 0;  DWORD error;  *got = 0;  *failed = NULL;  error = overlapped_begin(&overlapped, failed);  if (error != ERROR_SUCCESS) {    return error;  }  *failed = "ReadFile";  /* A read that ends at once and one that is pending alike leave their   * result in the record, which overlapped_finish reads. */  if (ReadFile(pipe, buffer, size, NULL, &overlapped) ||      (error = GetLastError()) == ERROR_IO_PENDING) {    error = overlapped_finish(pipe, &overlapped, stop, &read, failed);  }  CloseHandle(overlapped.hEvent);  *got = read;  if (error == ERROR_SUCCESS) {    *failed = NULL;  }  return error;}unsigned long nn_pipe_write(void *pipe, const void *buffer,                            unsigned long size, void *stop,                            const char **failed) {  OVERLAPPED overlapped;  const char *rest = buffer;  DWORD left = size;  DWORD written;  DWORD error;  *failed = NULL;  error = overlapped_begin(&overlapped, failed);  if (error != ERROR_SUCCESS) {    return error;  }  while (error == ERROR_SUCCESS && left > 0) {    written = 0;    *failed = "WriteFile";    if (WriteFile(pipe, rest, left, NULL, &overlapped) ||        (error = GetLastError()) == ERROR_IO_PENDING) {      error = overlapped_finish(pipe, &overlapped, stop, &written, failed);    }    /* A write that takes nothing would leave the loop running forever. */    if (error == ERROR_SUCCESS && written == 0) {      error = ERROR_WRITE_FAULT;    }    rest += written;    left -= written;  }  CloseHandle(overlapped.hEvent);  if (error == ERROR_SUCCESS) {    *failed = NULL;  }  return error;}/* Whether a token's group is one an access check grants by: enabled, and * not held for deny only, as a filtered administrator's token holds * Administrators. */static int group_grants(DWORD attributes) {  return (attributes & SE_GROUP_ENABLED) != 0 &&         (attributes & SE_GROUP_USE_FOR_DENY_ONLY) == 0;}/* Every group, for a list of groups that is kept whole. */static int group_any(DWORD attributes) {  (void)attributes;  return 1;}/* Put the string form of sid, NUL included, at out + *at, within the * capacity characters out holds, or with out NULL only count it; either * way *at moves past it. */static DWORD sid_put(PSID sid, wchar_t *out, DWORD capacity, DWORD *at,                     const char **failed) {  wchar_t *text;  DWORD length;  if (!ConvertSidToStringSidW(sid, &text)) {    *failed = "ConvertSidToStringSidW";    return GetLastError();  }  length = (DWORD)wcslen(text) + 1;  if (out != NULL) {    if (length > capacity - *at) {      LocalFree(text);      *failed = "nn_pipe_client";      return ERROR_INSUFFICIENT_BUFFER;    }    wmemcpy(out + *at, text, length);  }  *at += length;  LocalFree(text);  return ERROR_SUCCESS;}/* Each of the token's groups the test keeps, through sid_put. */static DWORD groups_put(const TOKEN_GROUPS *groups, int (*keep)(DWORD),                        wchar_t *out, DWORD capacity, DWORD *at,                        const char **failed) {  DWORD index;  DWORD error = ERROR_SUCCESS;  for (index = 0; error == ERROR_SUCCESS && index < groups->GroupCount;       index++) {    if (keep(groups->Groups[index].Attributes)) {      error = sid_put(groups->Groups[index].Sid, out, capacity, at, failed);    }  }  return error;}/* The token's user and each of its groups group_grants keeps, through * sid_put. */static DWORD sids_put(const TOKEN_USER *user, const TOKEN_GROUPS *groups,                      wchar_t *out, DWORD capacity, DWORD *at,                      const char **failed) {  DWORD error = sid_put(user->User.Sid, out, capacity, at, failed);  if (error == ERROR_SUCCESS) {    error = groups_put(groups, group_grants, out, capacity, at, failed);  }  return error;}/* The token's groups, in a buffer for the caller to release with * LocalFree. */static DWORD token_groups(HANDLE token, TOKEN_GROUPS **groups,                          const char **failed) {  DWORD size = 0;  DWORD error;  *groups = NULL;  /* The groups take as much room as the token has groups, which the   * first call asks. */  if (!GetTokenInformation(token, TokenGroups, NULL, 0, &size)) {    error = GetLastError();    if (error != ERROR_INSUFFICIENT_BUFFER) {      *failed = "GetTokenInformation";      return error;    }  }  *groups = LocalAlloc(LMEM_FIXED, size);  if (*groups == NULL) {    *failed = "LocalAlloc";    return GetLastError();  }  if (!GetTokenInformation(token, TokenGroups, *groups, size, &size)) {    *failed = "GetTokenInformation";    error = GetLastError();    LocalFree(*groups);    *groups = NULL;    return error;  }  return ERROR_SUCCESS;}/* The SIDs a token names its holder by, as nn_pipe_client writes them, * and whether the token is restricted. */static DWORD token_sids(HANDLE token, int *restricted, wchar_t **sids,                        unsigned long *chars, const char **failed) {  /* A TOKEN_USER is followed in the buffer by the SID it points at, as in   * token_user_sid. */  union {    TOKEN_USER user;    BYTE bytes[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE];  } user;  TOKEN_GROUPS *groups;  wchar_t *out;  DWORD size = 0;  DWORD total = 0;  DWORD written = 0;  DWORD error;  if (!GetTokenInformation(token, TokenUser, &user, sizeof user, &size)) {    *failed = "GetTokenInformation";    return GetLastError();  }  *restricted = IsTokenRestricted(token) ||                (user.user.User.Attributes & SE_GROUP_USE_FOR_DENY_ONLY) != 0;  error = token_groups(token, &groups, failed);  if (error != ERROR_SUCCESS) {    return error;  }  error = sids_put(&user.user, groups, NULL, 0, &total, failed);  if (error == ERROR_SUCCESS) {    out = LocalAlloc(LMEM_FIXED, total * sizeof(wchar_t));    if (out == NULL) {      *failed = "LocalAlloc";      error = GetLastError();    } else {      error = sids_put(&user.user, groups, out, total, &written, failed);      if (error == ERROR_SUCCESS) {        *sids = out;        *chars = written;      } else {        LocalFree(out);      }    }  }  LocalFree(groups);  return error;}unsigned long nn_pipe_client(void *pipe, unsigned long *process,                             int *restricted, wchar_t **sids,                             unsigned long *chars, const char **failed) {  ULONG client;  HANDLE token = NULL;  DWORD error = ERROR_SUCCESS;  *process = 0;  *restricted = 0;  *sids = NULL;  *chars = 0;  *failed = NULL;  if (!GetNamedPipeClientProcessId(pipe, &client)) {    *failed = "GetNamedPipeClientProcessId";    return GetLastError();  }  if (!ImpersonateNamedPipeClient(pipe)) {    *failed = "ImpersonateNamedPipeClient";    return GetLastError();  }  /* Opened as the process rather than as the client, whose token a client   * that lets itself be identified but not impersonated cannot open. */  if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token)) {    *failed = "OpenThreadToken";    error = GetLastError();  }  /* The thread goes on to run the caller's code, none of which may run as   * the client, and Windows' guidance for a thread that cannot stop   * impersonating is to end the process. */  if (!RevertToSelf()) {    abort();  }  if (error != ERROR_SUCCESS) {    return error;  }  error = token_sids(token, restricted, sids, chars, failed);  CloseHandle(token);  if (error == ERROR_SUCCESS) {    *process = client;  }  return error;}unsigned long nn_pipe_open(const wchar_t *name, unsigned long access,                           void **pipe, const char **failed) {  HANDLE opened;  DWORD error;  int attempt;  *pipe = NULL;  *failed = NULL;  for (attempt = 1;; attempt++) {    /* SECURITY_IDENTIFICATION lets the daemon read who the client is, and     * not act as it. */    opened = CreateFileW(name, access, 0, NULL, OPEN_EXISTING,                         FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT |                             SECURITY_IDENTIFICATION,                         NULL);    if (opened != INVALID_HANDLE_VALUE) {      *pipe = opened;      return ERROR_SUCCESS;    }    error = GetLastError();    if (error != ERROR_PIPE_BUSY || attempt == NN_PIPE_OPEN_ATTEMPTS) {      *failed = "CreateFileW";      return error;    }    /* Another client may take the instance that frees before this one     * opens it, which only sends this one back to wait.  A wait that runs     * out says that every instance stayed busy, which is the open's     * failure. */    if (!WaitNamedPipeW(name, NMPWAIT_USE_DEFAULT_WAIT)) {      error = GetLastError();      if (error == ERROR_SEM_TIMEOUT) {        *failed = "CreateFileW";        return ERROR_PIPE_BUSY;      }      *failed = "WaitNamedPipeW";      return error;    }  }}unsigned long nn_pipe_owner(void *pipe, wchar_t **sid, const char **failed) {  PSID owner = NULL;  PSECURITY_DESCRIPTOR descriptor = NULL;  DWORD error;  *sid = NULL;  *failed = NULL;  /* The owner the pipe's creator gave it. */  error = GetSecurityInfo(pipe, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION,                          &owner, NULL, NULL, NULL, &descriptor);  if (error != ERROR_SUCCESS) {    *failed = "GetSecurityInfo";    return error;  }  if (owner != NULL && !ConvertSidToStringSidW(owner, sid)) {    *failed = "ConvertSidToStringSidW";    *sid = NULL;    error = GetLastError();  }  LocalFree(descriptor);  return error;}unsigned long nn_pipe_integrity(void *pipe, unsigned long *level,                                const char **failed) {  PACL sacl = NULL;  PSECURITY_DESCRIPTOR descriptor = NULL;  DWORD index;  DWORD error;  *level = SECURITY_MANDATORY_MEDIUM_RID;  *failed = NULL;  error = GetSecurityInfo(pipe, SE_KERNEL_OBJECT, LABEL_SECURITY_INFORMATION,                          NULL, NULL, NULL, &sacl, &descriptor);  if (error != ERROR_SUCCESS) {    *failed = "GetSecurityInfo";    return error;  }  /* The label is an entry of the SACL whose SID's last subauthority is the   * level; the SACL read for the label alone holds no other kind. */  for (index = 0; sacl != NULL && index < sacl->AceCount; index++) {    void *entry;    SYSTEM_MANDATORY_LABEL_ACE *label;    PSID sid;    if (!GetAce(sacl, index, &entry)) {      *failed = "GetAce";      error = GetLastError();      break;    }    label = entry;    if (label->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE) {      sid = (PSID)&label->SidStart;      *level = *GetSidSubAuthority(          sid, (DWORD)(*GetSidSubAuthorityCount(sid) - 1));      break;    }  }  LocalFree(descriptor);  return error;}/* Whether the token holds the group enabled, not for deny only, and with * the right to own objects as it: the way an elevated administrator's * token holds Administrators, and a filtered one, which holds the group * for deny only, does not. */static int token_owns_as_group(const TOKEN_GROUPS *groups, PSID group) {  DWORD index;  DWORD attributes;  for (index = 0; index < groups->GroupCount; index++) {    if (EqualSid(groups->Groups[index].Sid, group)) {      attributes = groups->Groups[index].Attributes;      return (attributes & SE_GROUP_ENABLED) != 0 &&             (attributes & SE_GROUP_OWNER) != 0 &&             (attributes & SE_GROUP_USE_FOR_DENY_ONLY) == 0;    }  }  return 0;}unsigned long nn_token_pipe_owner(void *token, wchar_t **sid,                                  const char **failed) {  HANDLE opened = NULL;  union {    SID sid;    BYTE bytes[SECURITY_MAX_SID_SIZE];  } administrators;  DWORD administratorsSize = sizeof administrators;  TOKEN_GROUPS *groups = NULL;  DWORD error;  *sid = NULL;  *failed = NULL;  if (token == NULL) {    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &opened)) {      *failed = "OpenProcessToken";      return GetLastError();    }    token = opened;  }  if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL,                          &administrators.sid, &administratorsSize)) {    *failed = "CreateWellKnownSid";    error = GetLastError();  } else {    error = token_groups(token, &groups, failed);  }  if (error == ERROR_SUCCESS) {    if (!token_owns_as_group(groups, &administrators.sid)) {      error = token_user_sid(token, sid, failed);    } else if (!ConvertSidToStringSidW(&administrators.sid, sid)) {      *failed = "ConvertSidToStringSidW";      *sid = NULL;      error = GetLastError();    }    LocalFree(groups);  }  if (opened != NULL) {    CloseHandle(opened);  }  return error;}unsigned long nn_pipe_present(const wchar_t *path, const wchar_t *name,                              int *present, const char **failed) {  WIN32_FIND_DATAW found;  HANDLE search;  DWORD error = ERROR_SUCCESS;  *present = 0;  *failed = NULL;  /* A search of the pipes' namespace lists the pipes whose names match;   * opening the pipe or asking its attributes would connect to an   * instance.  A name holding a wildcard matches others, so each found   * name is compared with the one asked for. */  search = FindFirstFileW(path, &found);  if (search == INVALID_HANDLE_VALUE) {    /* The pipes' namespace answers a search that matches nothing with     * ERROR_NO_MORE_FILES, where a directory on disk answers     * ERROR_FILE_NOT_FOUND. */    error = GetLastError();    if (error == ERROR_FILE_NOT_FOUND || error == ERROR_NO_MORE_FILES) {      return ERROR_SUCCESS;    }    *failed = "FindFirstFileW";    return error;  }  do {    if (CompareStringOrdinal(found.cFileName, -1, name, -1, TRUE) ==        CSTR_EQUAL) {      *present = 1;    }  } while (!*present && FindNextFileW(search, &found));  if (!*present) {    error = GetLastError();    if (error == ERROR_NO_MORE_FILES) {      error = ERROR_SUCCESS;    } else {      *failed = "FindNextFileW";    }  }  FindClose(search);  return error;}/* Whether an account whose name resolved to this type is of the kind * asked for.  SYSTEM, LOCAL SERVICE and a service's virtual account are * filed as well-known groups yet are the users processes run as, so a user * may be one. */static int use_fits(SID_NAME_USE use, int kind) {  if (kind == NN_ACCOUNT_USER) {    return use == SidTypeUser || use == SidTypeWellKnownGroup;  }  return use == SidTypeGroup || use == SidTypeAlias ||         use == SidTypeWellKnownGroup;}unsigned long nn_account_sid(const wchar_t *name, int kind, wchar_t **sid,                             const char **failed) {  wchar_t qualified[NN_QUALIFIED_NAME_CHARS];  const wchar_t *searched = name;  union {    SID sid;    BYTE bytes[SECURITY_MAX_SID_SIZE];  } found;  DWORD sidSize = sizeof found;  wchar_t domain[NN_ACCOUNT_CHARS];  DWORD domainChars = NN_ACCOUNT_CHARS;  SID_NAME_USE use;  DWORD error;  *sid = NULL;  *failed = NULL;  /* A name that names no domain is searched for among this machine's   * accounts alone: handed to LookupAccountNameW bare, it falls through to   * the domain the machine belongs to. */  if (wcspbrk(name, L"\\@") == NULL) {    error = qualified_local_name(name, qualified, failed);    if (error == ERROR_INSUFFICIENT_BUFFER) {      return ERROR_SUCCESS;    }    if (error != ERROR_SUCCESS) {      return error;    }    searched = qualified;  }  if (!LookupAccountNameW(NULL, searched, &found.sid, &sidSize, domain,                          &domainChars, &use)) {    error = GetLastError();    if (error == ERROR_NONE_MAPPED) {      return ERROR_SUCCESS;    }    *failed = "LookupAccountNameW";    return error;  }  if (!use_fits(use, kind)) {    return ERROR_SUCCESS;  }  if (!ConvertSidToStringSidW(&found.sid, sid)) {    error = GetLastError();    *failed = "ConvertSidToStringSidW";    *sid = NULL;    return error;  }  return ERROR_SUCCESS;}/* The groups of the account whose SID is given, from the access check's * own source for them, in a buffer for the caller to release with * LocalFree. */static DWORD account_context_groups(PSID user, TOKEN_GROUPS **groups,                                    const char **failed) {  AUTHZ_RESOURCE_MANAGER_HANDLE manager = NULL;  AUTHZ_CLIENT_CONTEXT_HANDLE context = NULL;  LUID identifier = {0, 0};  DWORD size = 0;  DWORD error = ERROR_SUCCESS;  *groups = NULL;  /* No audit event is made for a context that only reads groups. */  if (!AuthzInitializeResourceManager(AUTHZ_RM_FLAG_NO_AUDIT, NULL, NULL, NULL,                                      NULL, &manager)) {    *failed = "AuthzInitializeResourceManager";    return GetLastError();  }  if (!AuthzInitializeContextFromSid(0, user, manager, NULL, identifier, NULL,                                     &context)) {    *failed = "AuthzInitializeContextFromSid";    error = GetLastError();  } else {    /* The first call asks how much room the groups take. */    (void)AuthzGetInformationFromContext(context, AuthzContextInfoGroupsSids,                                         0, &size, NULL);    *groups = LocalAlloc(LMEM_FIXED, size);    if (*groups == NULL) {      *failed = "LocalAlloc";      error = GetLastError();    } else if (!AuthzGetInformationFromContext(                   context, AuthzContextInfoGroupsSids, size, &size,                   *groups)) {      *failed = "AuthzGetInformationFromContext";      error = GetLastError();      LocalFree(*groups);      *groups = NULL;    }    AuthzFreeContext(context);  }  AuthzFreeResourceManager(manager);  return error;}unsigned long nn_account_groups(const wchar_t *sid, wchar_t **sids,                                unsigned long *chars, const char **failed) {  PSID user = NULL;  TOKEN_GROUPS *groups = NULL;  wchar_t *out;  DWORD total = 0;  DWORD written = 0;  DWORD error;  *sids = NULL;  *chars = 0;  *failed = NULL;  if (!ConvertStringSidToSidW(sid, &user)) {    *failed = "ConvertStringSidToSidW";    return GetLastError();  }  error = account_context_groups(user, &groups, failed);  LocalFree(user);  if (error != ERROR_SUCCESS) {    return error;  }  error = groups_put(groups, group_any, NULL, 0, &total, failed);  if (error == ERROR_SUCCESS) {    /* One more than the groups' text, so an account in no group still gets     * a buffer to release. */    out = LocalAlloc(LMEM_FIXED, ((size_t)total + 1) * sizeof(wchar_t));    if (out == NULL) {      *failed = "LocalAlloc";      error = GetLastError();    } else {      error = groups_put(groups, group_any, out, total, &written, failed);      if (error == ERROR_SUCCESS) {        *sids = out;        *chars = written;      } else {        LocalFree(out);      }    }  }  LocalFree(groups);  return error;}unsigned long nn_account_name(const wchar_t *sid, wchar_t **name,                              const char **failed) {  PSID binary = NULL;  wchar_t account[NN_ACCOUNT_CHARS];  DWORD accountChars = NN_ACCOUNT_CHARS;  wchar_t domain[NN_ACCOUNT_CHARS];  DWORD domainChars = NN_ACCOUNT_CHARS;  SID_NAME_USE use;  size_t accountLength;  size_t domainLength;  size_t prefix;  wchar_t *joined;  DWORD error;  *name = NULL;  *failed = NULL;  if (!ConvertStringSidToSidW(sid, &binary)) {    *failed = "ConvertStringSidToSidW";    return GetLastError();  }  if (!LookupAccountSidW(NULL, binary, account, &accountChars, domain,                         &domainChars, &use)) {    error = GetLastError();    LocalFree(binary);    if (error == ERROR_NONE_MAPPED) {      return ERROR_SUCCESS;    }    *failed = "LookupAccountSidW";    return error;  }  LocalFree(binary);  accountLength = wcslen(account);  domainLength = wcslen(domain);  prefix = domainLength > 0 ? domainLength + 1 : 0;  joined = LocalAlloc(LMEM_FIXED,                      (prefix + accountLength + 1) * sizeof(wchar_t));  if (joined == NULL) {    *failed = "LocalAlloc";    return GetLastError();  }  if (domainLength > 0) {    wmemcpy(joined, domain, domainLength);    joined[domainLength] = L'\\';  }  wmemcpy(joined + prefix, account, accountLength + 1);  *name = joined;  return ERROR_SUCCESS;}#else /* !_WIN32 *//* Per-directory case sensitivity is an NTFS feature; APFS decides at * volume creation and Linux filesystems are case-sensitive by nature. */int nn_dir_set_case_sensitive(const wchar_t *path) {  (void)path;  return 0;}#endif