Exemplo n.º 1
1
/*
 * @implemented
 */
HINSTANCE
WINAPI
LoadLibraryExW(LPCWSTR lpLibFileName,
               HANDLE hFile,
               DWORD dwFlags)
{
    UNICODE_STRING DllName;
    HINSTANCE hInst;
    NTSTATUS Status;
    PWSTR SearchPath;
    ULONG DllCharacteristics = 0;
    BOOL FreeString = FALSE;

    /* Check for any flags LdrLoadDll might be interested in */
    if (dwFlags & DONT_RESOLVE_DLL_REFERENCES)
    {
        /* Tell LDR to treat it as an EXE */
        DllCharacteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
    }

    /* Build up a unicode dll name from null-terminated string */
    RtlInitUnicodeString(&DllName, (LPWSTR)lpLibFileName);

    /* Lazy-initialize BasepExeLdrEntry */
    if (!BasepExeLdrEntry)
        LdrEnumerateLoadedModules(0, BasepLocateExeLdrEntry, NtCurrentPeb()->ImageBaseAddress);

    /* Check if that module is our exe*/
    if (BasepExeLdrEntry && !(dwFlags & LOAD_LIBRARY_AS_DATAFILE) &&
        DllName.Length == BasepExeLdrEntry->FullDllName.Length)
    {
        /* Lengths match and it's not a datafile, so perform name comparison */
        if (RtlEqualUnicodeString(&DllName, &BasepExeLdrEntry->FullDllName, TRUE))
        {
            /* That's us! */
            return BasepExeLdrEntry->DllBase;
        }
    }

    /* Check for trailing spaces and remove them if necessary */
    if (DllName.Buffer[DllName.Length/sizeof(WCHAR) - 1] == L' ')
    {
        RtlCreateUnicodeString(&DllName, (LPWSTR)lpLibFileName);
        while (DllName.Length > sizeof(WCHAR) &&
            DllName.Buffer[DllName.Length/sizeof(WCHAR) - 1] == L' ')
        {
            DllName.Length -= sizeof(WCHAR);
        }
        DllName.Buffer[DllName.Length/sizeof(WCHAR)] = UNICODE_NULL;
        FreeString = TRUE;
    }

    /* Compute the load path */
    SearchPath = BaseComputeProcessDllPath((dwFlags & LOAD_WITH_ALTERED_SEARCH_PATH) ?
                                           DllName.Buffer : NULL,
                                           NULL);
    if (!SearchPath)
    {
        /* Getting DLL path failed, so set last error, free mem and return */
        BaseSetLastNTError(STATUS_NO_MEMORY);
        if (FreeString) RtlFreeUnicodeString(&DllName);
        return NULL;
    }

    _SEH2_TRY
    {
        if (dwFlags & LOAD_LIBRARY_AS_DATAFILE)
        {
            /* If the image is loaded as a datafile, try to get its handle */
            Status = LdrGetDllHandleEx(0, SearchPath, NULL, &DllName, (PVOID*)&hInst);
            if (!NT_SUCCESS(Status))
            {
                /* It's not loaded yet - so load it up */
                Status = BasepLoadLibraryAsDatafile(SearchPath, DllName.Buffer, &hInst);
            }
            _SEH2_YIELD(goto done;)
        }

        /* Call the API Properly */
        Status = LdrLoadDll(SearchPath,
                            &DllCharacteristics,
                            &DllName,
                            (PVOID*)&hInst);
    }
Exemplo n.º 2
0
    FOR_EACH(Entry, RedirectSubDirectory, countof(RedirectSubDirectory))
    {
        CopyMemory(Buffer, ExePath.Buffer, ExePath.Length);
        CopyMemory(PtrAdd(Buffer, ExePath.Length), Entry->Original.Buffer, Entry->Original.Length);
        *PtrAdd(Buffer, ExePath.Length + Entry->Original.Length) = 0;
        RtlCreateUnicodeString(&RedirectEntry->Original, Buffer);

        CopyMemory(PtrAdd(Buffer, ExePath.Length), Entry->Redirected.Buffer, Entry->Redirected.Length);
        *PtrAdd(Buffer, ExePath.Length + Entry->Redirected.Length) = 0;
        RtlCreateUnicodeString(&RedirectEntry->Redirected, Buffer);

        ++RedirectEntry;
    }
Exemplo n.º 3
0
NTSTATUS
NTAPI
UserCreateWinstaDirectory(VOID)
{
    PPEB Peb;
    NTSTATUS Status;
    WCHAR wstrWindowStationsDir[MAX_PATH];
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE hWinstaDir;

    /* Create the WindowStations directory and cache its path for later use */
    Peb = NtCurrentPeb();
    if(Peb->SessionId == 0)
    {
        if (!RtlCreateUnicodeString(&gustrWindowStationsDir, WINSTA_OBJ_DIR))
        {
            return STATUS_INSUFFICIENT_RESOURCES;
        }
    }
    else
    {
        swprintf(wstrWindowStationsDir,
                 L"%ws\\%lu%ws",
                 SESSION_DIR,
                 Peb->SessionId,
                 WINSTA_OBJ_DIR);

        if (!RtlCreateUnicodeString(&gustrWindowStationsDir, wstrWindowStationsDir))
        {
            return STATUS_INSUFFICIENT_RESOURCES;
        }
    }

    InitializeObjectAttributes(&ObjectAttributes,
                               &gustrWindowStationsDir,
                               0,
                               NULL,
                               NULL);
    Status = ZwCreateDirectoryObject(&hWinstaDir, 0, &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        ERR("Could not create %wZ directory (Status 0x%X)\n", &gustrWindowStationsDir,  Status);
        return Status;
    }

    TRACE("Created directory %wZ for session %lu\n", &gustrWindowStationsDir, Peb->SessionId);

    return Status;
}
Exemplo n.º 4
0
/**********************************************************************
 *	PdxCreateDirectory/1					PRIVATE
 *
 * DESCRIPTION
 *	Create a directory in the system name space.
 */
PRIVATE NTSTATUS STDCALL
PdxCreateDirectory (
    IN ULONG ulIndex
)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    NTSTATUS          Status;

    RtlCreateUnicodeString (
        & Server.Directory[ulIndex].usName,
        Server.Directory[ulIndex].wsName
    );
    InitializeObjectAttributes (
        & ObjectAttributes,
        & Server.Directory[ulIndex].usName,
        0,
        NULL,
        NULL
    );
    Status = NtCreateDirectoryObject(
                 & Server.Directory[ulIndex].hObject,
                 DIRECTORY_ALL_ACCESS,
                 & ObjectAttributes
             );
    if (!NT_SUCCESS(Status))
    {
        debug_print(
            L"PSXSS: %s directory creation failed (Status = %08x)",
            Server.Directory[ulIndex].wsName,
            Status
        );

    }
    return Status;
}
Exemplo n.º 5
0
PCATALOG_ENTRY
CreateCatalogEntry(LPWSTR LibraryName)
{
    PCATALOG_ENTRY Provider;

    WS_DbgPrint(MAX_TRACE, ("LibraryName (%S).\n", LibraryName));

    Provider = HeapAlloc(GlobalHeap, 0, sizeof(CATALOG_ENTRY));
    if (!Provider)
        return NULL;

    ZeroMemory(Provider, sizeof(CATALOG_ENTRY));

    if (!RtlCreateUnicodeString(&Provider->LibraryName, LibraryName))
    {
        RtlFreeHeap(GlobalHeap, 0, Provider);
        return NULL;
    }

    Provider->ReferenceCount = 1;

    InitializeCriticalSection(&Provider->Lock);
    Provider->hModule = NULL;

    Provider->Mapping = NULL;

    //EnterCriticalSection(&CatalogLock);

    InsertTailList(&CatalogListHead, &Provider->ListEntry);

    //LeaveCriticalSection(&CatalogLock);

    return Provider;
}
Exemplo n.º 6
0
Arquivo: task.c Projeto: Barrell/wine
/* allocate the win16 TIB for a new 16-bit task */
static WIN16_SUBSYSTEM_TIB *allocate_win16_tib( TDB *pTask )
{
    WCHAR path[MAX_PATH];
    WIN16_SUBSYSTEM_TIB *tib;
    UNICODE_STRING *curdir;
    NE_MODULE *pModule = NE_GetPtr( pTask->hModule );

    if (!(tib = HeapAlloc( GetProcessHeap(), 0, sizeof(*tib) ))) return NULL;
    MultiByteToWideChar( CP_ACP, 0, NE_MODULE_NAME(pModule), -1, path, MAX_PATH );
    GetLongPathNameW( path, path, MAX_PATH );
    if (RtlCreateUnicodeString( &tib->exe_str, path )) tib->exe_name = &tib->exe_str;
    else tib->exe_name = NULL;

    RtlAcquirePebLock();
    if (NtCurrentTeb()->Tib.SubSystemTib)
        curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
    else
        curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
    tib->curdir.DosPath.MaximumLength = sizeof(tib->curdir_buffer);
    tib->curdir.DosPath.Length = min( curdir->Length, tib->curdir.DosPath.MaximumLength-sizeof(WCHAR) );
    tib->curdir.DosPath.Buffer = tib->curdir_buffer;
    tib->curdir.Handle = 0;
    memcpy( tib->curdir_buffer, curdir->Buffer, tib->curdir.DosPath.Length );
    tib->curdir_buffer[tib->curdir.DosPath.Length/sizeof(WCHAR)] = 0;
    RtlReleasePebLock();
    return tib;
}
Exemplo n.º 7
0
BOOL
WINAPI
BaseGetVdmConfigInfo(IN LPCWSTR CommandLineReserved,
                     IN ULONG DosSeqId,
                     IN ULONG BinaryType,
                     IN PUNICODE_STRING CmdLineString,
                     OUT PULONG VdmSize)
{
    WCHAR Buffer[MAX_PATH];
    WCHAR CommandLine[MAX_PATH * 2];
    ULONG Length;

    /* Clear the buffer in case we fail */
    CmdLineString->Buffer = 0;

    /* Always return the same size: 16 Mb */
    *VdmSize = 0x1000000;

    /* Get the system directory */
    Length = GetSystemDirectoryW(Buffer, MAX_PATH);
    if (!(Length) || (Length >= MAX_PATH))
    {
        /* Eliminate no path or path too big */
        SetLastError(ERROR_INVALID_NAME);
        return FALSE;
    }

    /* Check if this is VDM with a DOS Sequence ID */
    if (DosSeqId)
    {
        /*
         * Build the VDM string for it:
         * -i%lx : Gives the DOS Sequence ID;
         * %s%c  : Nothing if DOS VDM, -w if WoW VDM, -ws if separate WoW VDM.
         */
        _snwprintf(CommandLine,
                   sizeof(CommandLine),
                   L"\"%s\\ntvdm.exe\" -i%lx %s%c",
                   Buffer,
                   DosSeqId,
                   (BinaryType == BINARY_TYPE_DOS) ? L" " : L"-w",
                   (BinaryType == BINARY_TYPE_SEPARATE_WOW) ? L's' : L' ');
    }
    else
    {
        /*
         * Build the string for it without the DOS Sequence ID:
         * %s%c  : Nothing if DOS VDM, -w if WoW VDM, -ws if separate WoW VDM.
         */
        _snwprintf(CommandLine,
                   sizeof(CommandLine),
                   L"\"%s\\ntvdm.exe\" %s%c",
                   Buffer,
                   (BinaryType == BINARY_TYPE_DOS) ? L" " : L"-w",
                   (BinaryType == BINARY_TYPE_SEPARATE_WOW) ? L's' : L' ');
    }

    /* Create the actual string */
    return RtlCreateUnicodeString(CmdLineString, CommandLine);
}
Exemplo n.º 8
0
int
wmain(int argc, LPWSTR *argv)
{
  UNICODE_STRING NtPath;
  OBJECT_ATTRIBUTES objattr;
  NTSTATUS stat;

  SetOemPrintFLineLength(GetStdHandle(STD_ERROR_HANDLE));

  if (argc < 2)
    {
      fprintf(stderr, "Usage:\r\n%ws file [...]\r\n", argv[0]);
      return 1;
    }

  while (--argc)
    {
      if ((++argv)[0][0] == '\0')
	continue;

      if (argv[0][0] == L'\\')
	stat = RtlCreateUnicodeString(&NtPath, argv[0]);
      else
	stat = RtlDosPathNameToNtPathName_U(argv[0], &NtPath, NULL, NULL);

      if (!NT_SUCCESS(stat))
	{
	  LPSTR szErrMsg = nt_errmsgA(stat);
	  oem_printf(stderr, "Error: '%1!ws!': %2%%n",
		     argv[0],
		     szErrMsg);
	  LocalFree(szErrMsg);
	  return 1;
	}

      InitializeObjectAttributes(&objattr, &NtPath, OBJ_CASE_INSENSITIVE, NULL,
				 NULL);

      stat = NtDeleteFile(&objattr);

      if (NT_SUCCESS(stat))
	oem_printf(stderr, "Success: '%1!ws!'%%n", argv[0]);
      else
	{
	  LPSTR szErrMsg = nt_errmsgA(stat);
	  oem_printf(stderr, "Error: '%1!ws!': %2%%n",
		     argv[0],
		     szErrMsg);
	  LocalFree(szErrMsg);
	}

      RtlFreeUnicodeString(&NtPath);
    }

  return 0;
}
Exemplo n.º 9
0
Arquivo: pci.c Projeto: killvxk/NT_OS
NTSTATUS
PciCreateInstanceIDString(PUNICODE_STRING InstanceID,
                          PPCI_DEVICE Device)
{
  WCHAR Buffer[3];

  swprintf(Buffer, L"%02X", Device->SlotNumber.u.AsULONG & 0xff);

  return RtlCreateUnicodeString(InstanceID, Buffer) ? STATUS_SUCCESS : STATUS_INSUFFICIENT_RESOURCES;
}
Exemplo n.º 10
0
static
NTSTATUS
SetupCreateSingleDirectory(
    PWCHAR DirectoryName)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    IO_STATUS_BLOCK IoStatusBlock;
    UNICODE_STRING PathName;
    HANDLE DirectoryHandle;
    NTSTATUS Status;

    if(!RtlCreateUnicodeString(&PathName, DirectoryName))
        return STATUS_NO_MEMORY;

    if (PathName.Length > sizeof(WCHAR) &&
        PathName.Buffer[PathName.Length / sizeof(WCHAR) - 2] == L'\\' &&
        PathName.Buffer[PathName.Length / sizeof(WCHAR) - 1] == L'.')
    {
        PathName.Length -= sizeof(WCHAR);
        PathName.Buffer[PathName.Length / sizeof(WCHAR)] = 0;
    }

    if (PathName.Length > sizeof(WCHAR) &&
        PathName.Buffer[PathName.Length / sizeof(WCHAR) - 1] == L'\\')
    {
        PathName.Length -= sizeof(WCHAR);
        PathName.Buffer[PathName.Length / sizeof(WCHAR)] = 0;
    }

    InitializeObjectAttributes(&ObjectAttributes,
                               &PathName,
                               OBJ_CASE_INSENSITIVE | OBJ_INHERIT,
                               NULL,
                               NULL);

    Status = NtCreateFile(&DirectoryHandle,
                          DIRECTORY_ALL_ACCESS,
                          &ObjectAttributes,
                          &IoStatusBlock,
                          NULL,
                          FILE_ATTRIBUTE_DIRECTORY,
                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                          FILE_OPEN_IF,
                          FILE_DIRECTORY_FILE,
                          NULL,
                          0);
    if (NT_SUCCESS(Status))
    {
        NtClose(DirectoryHandle);
    }

    RtlFreeUnicodeString(&PathName);

    return Status;
}
Exemplo n.º 11
0
static
NTSTATUS
PciCreateInstanceIDString(PUNICODE_STRING InstanceID,
                          ULONG PeripheralNumber)
{
    WCHAR Buffer[3];

    swprintf(Buffer, L"%02X", PeripheralNumber & 0xff);

    return RtlCreateUnicodeString(InstanceID, Buffer) ? STATUS_SUCCESS : STATUS_INSUFFICIENT_RESOURCES;
}
Exemplo n.º 12
0
BOOL
WINAPI
BaseGetVdmConfigInfo(IN LPCWSTR Reserved,
                     IN ULONG DosSeqId,
                     IN ULONG BinaryType,
                     IN PUNICODE_STRING CmdLineString,
                     OUT PULONG VdmSize)
{
    WCHAR Buffer[MAX_PATH];
    WCHAR CommandLine[MAX_PATH * 2];
    ULONG Length;

    /* Clear the buffer in case we fail */
    CmdLineString->Buffer = 0;

    /* Always return the same size */
    *VdmSize = 0x1000000;

    /* Get the system directory */
    Length = GetSystemDirectoryW(Buffer, MAX_PATH);
    if (!(Length) || (Length >= MAX_PATH))
    {
        /* Eliminate no path or path too big */
        SetLastError(ERROR_INVALID_NAME);
        return FALSE;
    }

    /* Check if this is VDM with a DOS Sequence ID */
    if (DosSeqId)
    {
        /* Build the VDM string for it */
        _snwprintf(CommandLine,
                   sizeof(CommandLine),
                   L"\"%s\\ntvdm.exe\" -i%lx %s%c",
                   Buffer,
                   DosSeqId,
                   (BinaryType == 0x10) ? L" " : L"-w",
                   (BinaryType == 0x40) ? 's' : ' ');
    }
    else
    {
        /* Non-DOS, build the string for it without the task ID */
        _snwprintf(CommandLine,
                   sizeof(CommandLine),
                   L"\"%s\\ntvdm.exe\"  %s%c",
                   Buffer,
                   (BinaryType == 0x10) ? L" " : L"-w",
                   (BinaryType == 0x40) ? 's' : ' ');
    }

    /* Create the actual string */
    return RtlCreateUnicodeString(CmdLineString, CommandLine);
}
Exemplo n.º 13
0
/* FMIFS.7 */
VOID
NTAPI
FormatEx(
    IN PWCHAR DriveRoot,
    IN FMIFS_MEDIA_FLAG MediaFlag,
    IN PWCHAR Format,
    IN PWCHAR Label,
    IN BOOLEAN QuickFormat,
    IN ULONG ClusterSize,
    IN PFMIFSCALLBACK Callback)
{
    PIFS_PROVIDER Provider;
    UNICODE_STRING usDriveRoot;
    UNICODE_STRING usLabel;
    BOOLEAN Argument = FALSE;
    WCHAR VolumeName[MAX_PATH];
    //CURDIR CurDir;

    Provider = GetProvider(Format);
    if (!Provider)
    {
        /* Unknown file system */
        Callback(DONE, 0, &Argument);
        return;
    }

#if 1
    DPRINT1("Warning: use GetVolumeNameForVolumeMountPointW() instead!\n");
    swprintf(VolumeName, L"\\??\\%c:", towupper(DriveRoot[0]));
    RtlCreateUnicodeString(&usDriveRoot, VolumeName);
    /* Code disabled as long as our storage stack doesn't understand IOCTL_MOUNTDEV_QUERY_DEVICE_NAME */
#else
    if (!GetVolumeNameForVolumeMountPointW(DriveRoot, VolumeName, MAX_PATH) ||
        !RtlDosPathNameToNtPathName_U(VolumeName, &usDriveRoot, NULL, &CurDir))
    {
        /* Report an error. */
        Callback(DONE, 0, &Argument);
        return;
    }
#endif

    RtlInitUnicodeString(&usLabel, Label);

    DPRINT("FormatEx - %S\n", Format);
    Provider->FormatEx(&usDriveRoot,
                       MediaFlag,
                       &usLabel,
                       QuickFormat,
                       ClusterSize,
                       Callback);

    RtlFreeUnicodeString(&usDriveRoot);
}
Exemplo n.º 14
0
VOID MountFloppy(IN ULONG DiskNumber)
{
// FIXME: This should be present in PSDK commdlg.h
//
// FlagsEx Values
#if (_WIN32_WINNT >= 0x0500)
#define  OFN_EX_NOPLACESBAR         0x00000001
#endif // (_WIN32_WINNT >= 0x0500)

    BOOLEAN Success;
    OPENFILENAMEW ofn;
    WCHAR szFile[MAX_PATH] = L"";

    ASSERT(DiskNumber < ARRAYSIZE(GlobalSettings.FloppyDisks));

    RtlZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize  = sizeof(ofn);
    ofn.hwndOwner    = hConsoleWnd;
    ofn.lpstrTitle   = L"Select a virtual floppy image";
    ofn.Flags        = OFN_EXPLORER | OFN_ENABLESIZING | OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
//  ofn.FlagsEx      = OFN_EX_NOPLACESBAR;
    ofn.lpstrFilter  = L"Virtual floppy images (*.vfd;*.img;*.ima;*.dsk)\0*.vfd;*.img;*.ima;*.dsk\0All files (*.*)\0*.*\0\0";
    ofn.lpstrDefExt  = L"vfd";
    ofn.nFilterIndex = 0;
    ofn.lpstrFile    = szFile;
    ofn.nMaxFile     = ARRAYSIZE(szFile);

    if (!GetOpenFileNameW(&ofn))
    {
        DPRINT1("CommDlgExtendedError = %d\n", CommDlgExtendedError());
        return;
    }

    /* Free the old string */
    if (GlobalSettings.FloppyDisks[DiskNumber].Buffer)
        RtlFreeUnicodeString(&GlobalSettings.FloppyDisks[DiskNumber]);

    /* Reinitialize the string */
    Success = RtlCreateUnicodeString(&GlobalSettings.FloppyDisks[DiskNumber], szFile);
    ASSERT(Success);

    /* Mount the disk */
    if (!MountDisk(FLOPPY_DISK, DiskNumber, GlobalSettings.FloppyDisks[DiskNumber].Buffer, !!(ofn.Flags & OFN_READONLY)))
    {
        DisplayMessage(L"An error happened when mounting disk %d", DiskNumber);
        RtlFreeUnicodeString(&GlobalSettings.FloppyDisks[DiskNumber]);
        RtlInitEmptyUnicodeString(&GlobalSettings.FloppyDisks[DiskNumber], NULL, 0);
        return;
    }

    /* Refresh the menu state */
    UpdateVdmMenuDisks();
}
Exemplo n.º 15
0
/* IntAttachMonitor
 *
 * Creates a new MONITOR and appends it to the list of monitors.
 *
 * Arguments
 *
 *   pGdiDevice     Pointer to the PDEVOBJ onto which the monitor was attached
 *   DisplayNumber  Display Number (starting with 0)
 *
 * Return value
 *   Returns a NTSTATUS
 */
NTSTATUS
IntAttachMonitor(IN PDEVOBJ *pGdiDevice,
                 IN ULONG DisplayNumber)
{
    PMONITOR Monitor;
    WCHAR Buffer[CCHDEVICENAME];

    TRACE("Attaching monitor...\n");

    /* create new monitor object */
    Monitor = IntCreateMonitorObject();
    if (Monitor == NULL)
    {
        TRACE("Couldnt create monitor object\n");
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    _snwprintf(Buffer, CCHDEVICENAME, L"\\\\.\\DISPLAY%d", DisplayNumber + 1);
    if (!RtlCreateUnicodeString(&Monitor->DeviceName, Buffer))
    {
        TRACE("Couldn't duplicate monitor name!\n");
        UserDereferenceObject(Monitor);
        UserDeleteObject(UserHMGetHandle(Monitor), otMonitor);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    Monitor->GdiDevice = pGdiDevice;
    Monitor->cWndStack = 0;

    if (gMonitorList == NULL)
    {
        TRACE("Primary monitor is beeing attached\n");
        Monitor->IsPrimary = TRUE;
        gMonitorList = Monitor;
    }
    else
    {
        PMONITOR p;
        TRACE("Additional monitor is beeing attached\n");
        for (p = gMonitorList; p->Next != NULL; p = p->Next)
        {
            p->Next = Monitor;
        }
        Monitor->Prev = p;
    }

    IntUpdateMonitorSize(pGdiDevice);

    return STATUS_SUCCESS;
}
Exemplo n.º 16
0
Arquivo: pci.c Projeto: killvxk/NT_OS
NTSTATUS
PciCreateDeviceLocationString(PUNICODE_STRING DeviceLocation,
                              PPCI_DEVICE Device)
{
  WCHAR Buffer[256];

  swprintf(Buffer,
           L"PCI-Bus %lu, Device %u, Function %u",
           Device->BusNumber,
           Device->SlotNumber.u.bits.DeviceNumber,
           Device->SlotNumber.u.bits.FunctionNumber);

  return RtlCreateUnicodeString(DeviceLocation, Buffer) ? STATUS_SUCCESS : STATUS_INSUFFICIENT_RESOURCES;
}
Exemplo n.º 17
0
Arquivo: pci.c Projeto: killvxk/NT_OS
NTSTATUS
PciCreateDeviceIDString(PUNICODE_STRING DeviceID,
                        PPCI_DEVICE Device)
{
  WCHAR Buffer[256];

  swprintf(Buffer,
           L"PCI\\VEN_%04X&DEV_%04X&SUBSYS_%08X&REV_%02X",
           Device->PciConfig.VendorID,
           Device->PciConfig.DeviceID,
           (Device->PciConfig.u.type0.SubSystemID << 16) +
           Device->PciConfig.u.type0.SubVendorID,
           Device->PciConfig.RevisionID);

  return RtlCreateUnicodeString(DeviceID, Buffer) ? STATUS_SUCCESS : STATUS_INSUFFICIENT_RESOURCES;
}
NTSTATUS GetLangFile(PUNICODE_STRING LangFile, ULONG LangIndex, PCWSTR SubKey)
{
    BOOL        Success;
    WCHAR       LangIndexBuffer[16];
    NTSTATUS    Status;
    PKEY_VALUE_PARTIAL_INFORMATION FileName;

    swprintf(LangIndexBuffer, L"%04x", LangIndex);

    Status = GetKeyValue(REGKEY_ROOT, SubKey, LangIndexBuffer, &FileName);
    FAIL_RETURN(Status);

    Success = RtlCreateUnicodeString(LangFile, (PWSTR)FileName->Data);
    FreeMemoryP(FileName);

    return Success ? STATUS_SUCCESS : STATUS_NO_MEMORY;
}
Exemplo n.º 19
0
BOOL
NTAPI
RtlLargeStringToUnicodeString( PUNICODE_STRING DestinationString,
                               PLARGE_STRING SourceString)
{
  ANSI_STRING AnsiString;

  RtlInitUnicodeString(DestinationString, NULL);
  if (DestinationString && SourceString && SourceString->bAnsi)
  {
     RtlInitAnsiString(&AnsiString, (LPSTR)SourceString->Buffer);
     return NT_SUCCESS(RtlAnsiStringToUnicodeString(DestinationString, &AnsiString, TRUE));
  }
  else if (DestinationString && SourceString)
  {
     return RtlCreateUnicodeString(DestinationString, SourceString->Buffer);
  }
  else
     return FALSE;
}
Exemplo n.º 20
0
/*
 * @implemented
 */
BOOL
WINAPI
WaitNamedPipeW(LPCWSTR lpNamedPipeName,
               DWORD nTimeOut)
{
    UNICODE_STRING NamedPipeName, NewName, DevicePath, PipePrefix;
    ULONG NameLength;
    ULONG i;
    PWCHAR p;
    ULONG Type;
    OBJECT_ATTRIBUTES ObjectAttributes;
    NTSTATUS Status;
    HANDLE FileHandle;
    IO_STATUS_BLOCK IoStatusBlock;
    ULONG WaitPipeInfoSize;
    PFILE_PIPE_WAIT_FOR_BUFFER WaitPipeInfo;

    /* Start by making a unicode string of the name */
    TRACE("Sent path: %S\n", lpNamedPipeName);
    RtlCreateUnicodeString(&NamedPipeName, lpNamedPipeName);
    NameLength = NamedPipeName.Length / sizeof(WCHAR);

    /* All slashes must become backslashes */
    for (i = 0; i < NameLength; i++)
    {
        /* Check and convert */
        if (NamedPipeName.Buffer[i] == L'/') NamedPipeName.Buffer[i] = L'\\';
    }

    /* Find the path type of the name we were given */
    NewName = NamedPipeName;
    Type = RtlDetermineDosPathNameType_U(lpNamedPipeName);

    /* Check if this was a device path, ie : "\\.\pipe\name" */
    if (Type == RtlPathTypeLocalDevice)
    {
        /* Make sure it's a valid prefix */
        RtlInitUnicodeString(&PipePrefix, L"\\\\.\\pipe\\");
        RtlPrefixString((PANSI_STRING)&PipePrefix, (PANSI_STRING)&NewName, TRUE);

        /* Move past it */
        NewName.Buffer += 9;
        NewName.Length -= 9 * sizeof(WCHAR);

        /* Initialize the Dos Devices name */
        TRACE("NewName: %wZ\n", &NewName);
        RtlInitUnicodeString(&DevicePath, L"\\DosDevices\\pipe\\");
    }
    else if (Type == RtlPathTypeRootLocalDevice)
    {
        /* The path is \\server\\pipe\name; find the pipename itself */
        p = &NewName.Buffer[2];

        /* First loop to get past the server name */
        do
        {
            /* Check if this is a backslash */
            if (*p == L'\\') break;

            /* Check next */
            p++;
        } while (*p);

        /* Now make sure the full name contains "pipe\" */
        if ((*p) && !(_wcsnicmp(p + 1, L"pipe\\", sizeof("pipe\\"))))
        {
            /* Get to the pipe name itself now */
            p += sizeof("pipe\\") - 1;
        }
        else
        {
            /* The name is invalid */
            WARN("Invalid name!\n");
            BaseSetLastNTError(STATUS_OBJECT_PATH_SYNTAX_BAD);
            return FALSE;
        }

        /* FIXME: Open \DosDevices\Unc\Server\Pipe\Name */
    }
    else
    {
        WARN("Invalid path type\n");
        BaseSetLastNTError(STATUS_OBJECT_PATH_SYNTAX_BAD);
        return FALSE;
    }

    /* Now calculate the total length of the structure and allocate it */
    WaitPipeInfoSize = FIELD_OFFSET(FILE_PIPE_WAIT_FOR_BUFFER, Name[0]) +
                       NewName.Length;
    WaitPipeInfo = RtlAllocateHeap(RtlGetProcessHeap(), 0, WaitPipeInfoSize);
    if (WaitPipeInfo == NULL)
    {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        return FALSE;
    }

    /* Initialize the object attributes */
    TRACE("Opening: %wZ\n", &DevicePath);
    InitializeObjectAttributes(&ObjectAttributes,
                               &DevicePath,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    /* Open the path */
    Status = NtOpenFile(&FileHandle,
                        FILE_READ_ATTRIBUTES | SYNCHRONIZE,
                        &ObjectAttributes,
                        &IoStatusBlock,
                        FILE_SHARE_READ | FILE_SHARE_WRITE,
                        FILE_SYNCHRONOUS_IO_NONALERT);
    if (!NT_SUCCESS(Status))
    {
        /* Fail; couldn't open */
        WARN("Status: %lx\n", Status);
        BaseSetLastNTError(Status);
        RtlFreeUnicodeString(&NamedPipeName);
        RtlFreeHeap(RtlGetProcessHeap(), 0, WaitPipeInfo);
        return FALSE;
    }

    /* Check what timeout we got */
    if (nTimeOut == NMPWAIT_USE_DEFAULT_WAIT)
    {
        /* Don't use a timeout */
        WaitPipeInfo->TimeoutSpecified = FALSE;
    }
    else
    {
        /* Check if we should wait forever */
        if (nTimeOut == NMPWAIT_WAIT_FOREVER)
        {
            /* Set the max */
            WaitPipeInfo->Timeout.LowPart = 0;
            WaitPipeInfo->Timeout.HighPart = 0x80000000;
        }
        else
        {
            /* Convert to NT format */
            WaitPipeInfo->Timeout.QuadPart = UInt32x32To64(-10000, nTimeOut);
        }

        /* In both cases, we do have a timeout */
        WaitPipeInfo->TimeoutSpecified = TRUE;
    }

    /* Set the length and copy the name */
    WaitPipeInfo->NameLength = NewName.Length;
    RtlCopyMemory(WaitPipeInfo->Name, NewName.Buffer, NewName.Length);

    /* Get rid of the full name */
    RtlFreeUnicodeString(&NamedPipeName);

    /* Let NPFS know of our request */
    Status = NtFsControlFile(FileHandle,
                             NULL,
                             NULL,
                             NULL,
                             &IoStatusBlock,
                             FSCTL_PIPE_WAIT,
                             WaitPipeInfo,
                             WaitPipeInfoSize,
                             NULL,
                             0);

    /* Free our pipe info data and close the handle */
    RtlFreeHeap(RtlGetProcessHeap(), 0, WaitPipeInfo);
    NtClose(FileHandle);

    /* Check the status */
    if (!NT_SUCCESS(Status))
    {
        /* Failure to wait on the pipe */
        WARN("Status: %lx\n", Status);
        BaseSetLastNTError (Status);
        return FALSE;
     }

    /* Success */
    return TRUE;
}
Exemplo n.º 21
0
/*
 * @implemented
 */
NTSTATUS NTAPI
RtlConvertSidToUnicodeString(PUNICODE_STRING String,
                             PSID Sid_,
                             BOOLEAN AllocateBuffer)
{
   WCHAR Buffer[256];
   PWSTR wcs;
   ULONG Length;
   ULONG i;
   PISID Sid =  Sid_;

   PAGED_CODE_RTL();

   if (RtlValidSid (Sid) == FALSE)
      return STATUS_INVALID_SID;

   wcs = Buffer;
   wcs += swprintf (wcs, L"S-%u-", Sid->Revision);
   if (Sid->IdentifierAuthority.Value[0] == 0 &&
       Sid->IdentifierAuthority.Value[1] == 0)
   {
      wcs += swprintf (wcs,
                       L"%lu",
                       (ULONG)Sid->IdentifierAuthority.Value[2] << 24 |
                       (ULONG)Sid->IdentifierAuthority.Value[3] << 16 |
                       (ULONG)Sid->IdentifierAuthority.Value[4] << 8 |
                       (ULONG)Sid->IdentifierAuthority.Value[5]);
   }
   else
   {
      wcs += swprintf (wcs,
                       L"0x%02hx%02hx%02hx%02hx%02hx%02hx",
                       Sid->IdentifierAuthority.Value[0],
                       Sid->IdentifierAuthority.Value[1],
                       Sid->IdentifierAuthority.Value[2],
                       Sid->IdentifierAuthority.Value[3],
                       Sid->IdentifierAuthority.Value[4],
                       Sid->IdentifierAuthority.Value[5]);
   }

   for (i = 0; i < Sid->SubAuthorityCount; i++)
   {
      wcs += swprintf (wcs,
                       L"-%u",
                       Sid->SubAuthority[i]);
   }

   if (AllocateBuffer)
   {
      if (!RtlCreateUnicodeString(String,
                                  Buffer))
      {
         return STATUS_NO_MEMORY;
      }
   }
   else
   {
      Length = (wcs - Buffer) * sizeof(WCHAR);

      if (Length > String->MaximumLength)
         return STATUS_BUFFER_TOO_SMALL;

      String->Length = Length;
      RtlCopyMemory (String->Buffer,
                     Buffer,
                     Length);
      if (Length < String->MaximumLength)
         String->Buffer[Length / sizeof(WCHAR)] = 0;
   }

   return STATUS_SUCCESS;
}
Exemplo n.º 22
0
NTSTATUS
IopSetupConfigurationTree(
     IN PCONFIGURATION_COMPONENT_DATA CurrentEntry,
     IN HANDLE Handle,
     IN PUNICODE_STRING WorkName,
     IN INTERFACE_TYPE InterfaceType,
     IN BUS_DATA_TYPE BusDataType,
     IN ULONG BusNumber
     )
/*++

Routine Description:

    This routine traverses loader configuration tree and register
    desired hardware information to System\Enuk\Root registry data base.

Arguments:

    CurrentEntry - Supplies a pointer to a loader configuration
        tree or subtree.

    Handle - Supplies the handle to the registry where we can create new key.

    WorkName - Supplies a pointer to a unicode string to specify the
        parent key name of current entry.

    InterfaceType - Specify the Interface type of the bus that the
        CurrentEntry component resides.

    BusDataType - Specify the data/configuration type of the bus that the
        CurrentEntry component resides.

    BusNumber - Specify the Bus Number of the bus that the CurrentEntry
        component resides.  If Bus number is -1, it means InterfaceType
        and BusNumber are meaningless for this component.

Returns:

    NTSTATUS

--*/
{
    NTSTATUS status;
    PCONFIGURATION_COMPONENT component;
    UNICODE_STRING keyName;
    UNICODE_STRING unicodeName;
    static ULONG peripheralCount = 0, controllerCount = 0;
    BOOLEAN freeKeyName = FALSE, nameMapped;
    // BUGBUG (shielint): initialize pnpId for now to avoid compiler warning.
    PWSTR pnpId = NULL;
    STRING stringName;
    USHORT namePosition;

    //
    // Process current entry first
    //

    if (CurrentEntry) {
        component = &CurrentEntry->ComponentEntry;
        nameMapped = FALSE;
#if 0
        switch (component->Type) {
        case DiskController:
             pnpId = L"DiskController";
             break;
        case TapeController:
             pnpId = L"PNP0100";
             break;
        case CdromController:
             pnpId = L"PNP0200";
             break;
        case WormController:
             pnpId = L"PNP0300";
             break;
        case SerialController:
             pnpId = L"PNP0400";
             break;
        case NetworkController:
             pnpId = L"PNP0500";
             break;
        case DisplayController:
             pnpId = L"PNP0600";
             break;
        case ParallelController:
             pnpId = L"PNP0700";
             break;
        case PointerController:
             pnpId = L"PNP0800";
             break;
        case KeyboardController:
             pnpId = L"PNP0900";
             break;
        case AudioController:
             pnpId = L"PNP1000";
             break;
        case OtherController:
             pnpId = L"PNP1100";
             break;
        case DiskPeripheral:
             pnpId = L"PNP1200";
             break;
        case FloppyDiskPeripheral:
             pnpId = L"PNP1300";
             break;
        case TapePeripheral:
             pnpId = L"PNP1400";
             break;
        case ModemPeripheral:
             pnpId = L"PNP1500";
             break;
        case MonitorPeripheral:
             pnpId = L"PNP1600";
             break;
        case PrinterPeripheral:
             pnpId = L"PNP1700";
             break;
        case PointerPeripheral:
             pnpId = L"PNP1800";
             break;
        case KeyboardPeripheral:
             pnpId = L"PNP1900";
             break;
        case TerminalPeripheral:
             pnpId = L"PNP2000";
             break;
        case OtherPeripheral:
             pnpId = L"PNP2100";
             break;
        case LinePeripheral:
             pnpId = L"PNP2200";
             break;
        case NetworkPeripheral:
             pnpId = L"PNP2300";
             break;
        }
#endif
        //
        // if we did NOT successfully mapped a PNP id for the component, we
        // will create a special key name and the key will be processed by
        // user mode inf file later.
        //

        if (nameMapped) {
            RtlCreateUnicodeString(&keyName, pnpId);
        } else {
            RtlInitUnicodeString(&unicodeName, L"Arc");
            IopConcatenateUnicodeStrings(&keyName,
                                         &unicodeName,
                                         &CmTypeName[component->Type]);
            freeKeyName = TRUE;
        }

        //
        // Initialize and copy current component to Enum\Root if it is
        // the one we're insterested in.
        //

        namePosition = WorkName->Length;
        status = IopInitializeRegistryNode(
                         CurrentEntry,
                         Handle,
                         WorkName,
                         &keyName,
                         IopPeripheralCount[component->Type]++,
                         InterfaceType,
                         BusDataType,
                         BusNumber
                         );

        if (freeKeyName) {
            RtlFreeUnicodeString(&keyName);
        }
        if (!NT_SUCCESS(status)) {
            return status;
        }

        //
        // Process the child entry of current entry
        //

        status = IopSetupConfigurationTree(CurrentEntry->Child,
                                           Handle,
                                           WorkName,
                                           InterfaceType,
                                           BusDataType,
                                           BusNumber
                                           );

        WorkName->Length = namePosition;

        if (!NT_SUCCESS(status)) {
            return status;
        }

        //
        // Process all the Siblings of current entry
        //

        status = IopSetupConfigurationTree(CurrentEntry->Sibling,
                                           Handle,
                                           WorkName,
                                           InterfaceType,
                                           BusDataType,
                                           BusNumber
                                           );

        return(status);
    } else {
        return(STATUS_SUCCESS);
    }
}
Exemplo n.º 23
0
NTSTATUS
GetSourcePaths(
    PUNICODE_STRING SourcePath,
    PUNICODE_STRING SourceRootPath,
    PUNICODE_STRING SourceRootDir)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING LinkName;
    UNICODE_STRING SourceName;
    WCHAR SourceBuffer[MAX_PATH] = {L'\0'};
    HANDLE Handle;
    NTSTATUS Status;
    ULONG Length;
    PWCHAR Ptr;

    RtlInitUnicodeString(&LinkName,
                         L"\\SystemRoot");

    InitializeObjectAttributes(&ObjectAttributes,
                               &LinkName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    Status = NtOpenSymbolicLinkObject(&Handle,
                                      SYMBOLIC_LINK_ALL_ACCESS,
                                      &ObjectAttributes);
    if (!NT_SUCCESS(Status))
        return Status;

    SourceName.Length = 0;
    SourceName.MaximumLength = MAX_PATH * sizeof(WCHAR);
    SourceName.Buffer = SourceBuffer;

    Status = NtQuerySymbolicLinkObject(Handle,
                                       &SourceName,
                                       &Length);
    NtClose(Handle);

    if (NT_SUCCESS(Status))
    {
        RtlCreateUnicodeString(SourcePath,
                               SourceName.Buffer);

        /* strip trailing directory */
        Ptr = wcsrchr(SourceName.Buffer, L'\\');
        if (Ptr)
        {
            RtlCreateUnicodeString(SourceRootDir, Ptr);
            *Ptr = 0;
        }
        else
            RtlCreateUnicodeString(SourceRootDir, L"");

        RtlCreateUnicodeString(SourceRootPath,
                               SourceName.Buffer);
    }

    NtClose(Handle);

    return STATUS_SUCCESS;
}
Exemplo n.º 24
0
static NTSTATUS
ReadRegistryEntries(
	IN PUNICODE_STRING RegistryPath,
	IN PCLASS_DRIVER_EXTENSION DriverExtension)
{
	UNICODE_STRING ParametersRegistryKey;
	RTL_QUERY_REGISTRY_TABLE Parameters[4];
	NTSTATUS Status;

	ULONG DefaultConnectMultiplePorts = 1;
	ULONG DefaultDataQueueSize = 0x64;
	PCWSTR DefaultDeviceBaseName = L"PointerClass";

	ParametersRegistryKey.Length = 0;
	ParametersRegistryKey.MaximumLength = RegistryPath->Length + sizeof(L"\\Parameters") + sizeof(UNICODE_NULL);
	ParametersRegistryKey.Buffer = ExAllocatePoolWithTag(PagedPool, ParametersRegistryKey.MaximumLength, CLASS_TAG);
	if (!ParametersRegistryKey.Buffer)
	{
		WARN_(CLASS_NAME, "ExAllocatePoolWithTag() failed\n");
		return STATUS_NO_MEMORY;
	}
	RtlCopyUnicodeString(&ParametersRegistryKey, RegistryPath);
	RtlAppendUnicodeToString(&ParametersRegistryKey, L"\\Parameters");
	ParametersRegistryKey.Buffer[ParametersRegistryKey.Length / sizeof(WCHAR)] = UNICODE_NULL;

	RtlZeroMemory(Parameters, sizeof(Parameters));

	Parameters[0].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[0].Name = L"ConnectMultiplePorts";
	Parameters[0].EntryContext = &DriverExtension->ConnectMultiplePorts;
	Parameters[0].DefaultType = REG_DWORD;
	Parameters[0].DefaultData = &DefaultConnectMultiplePorts;
	Parameters[0].DefaultLength = sizeof(ULONG);

	Parameters[1].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[1].Name = L"MouseDataQueueSize";
	Parameters[1].EntryContext = &DriverExtension->DataQueueSize;
	Parameters[1].DefaultType = REG_DWORD;
	Parameters[1].DefaultData = &DefaultDataQueueSize;
	Parameters[1].DefaultLength = sizeof(ULONG);

	Parameters[2].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[2].Name = L"PointerDeviceBaseName";
	Parameters[2].EntryContext = &DriverExtension->DeviceBaseName;
	Parameters[2].DefaultType = REG_SZ;
	Parameters[2].DefaultData = (PVOID)DefaultDeviceBaseName;
	Parameters[2].DefaultLength = 0;

	Status = RtlQueryRegistryValues(
		RTL_REGISTRY_ABSOLUTE,
		ParametersRegistryKey.Buffer,
		Parameters,
		NULL,
		NULL);

	if (NT_SUCCESS(Status))
	{
		/* Check values */
		if (DriverExtension->ConnectMultiplePorts != 0
			&& DriverExtension->ConnectMultiplePorts != 1)
		{
			DriverExtension->ConnectMultiplePorts = DefaultConnectMultiplePorts;
		}
		if (DriverExtension->DataQueueSize == 0)
		{
			DriverExtension->DataQueueSize = DefaultDataQueueSize;
		}
	}
	else if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
	{
		/* Registry path doesn't exist. Set defaults */
		DriverExtension->ConnectMultiplePorts = DefaultConnectMultiplePorts;
		DriverExtension->DataQueueSize = DefaultDataQueueSize;
		if (RtlCreateUnicodeString(&DriverExtension->DeviceBaseName, DefaultDeviceBaseName))
			Status = STATUS_SUCCESS;
		else
			Status = STATUS_NO_MEMORY;
	}

	ExFreePoolWithTag(ParametersRegistryKey.Buffer, CLASS_TAG);
	return Status;
}
Exemplo n.º 25
0
NTSTATUS
ObpCreateDosDevicesDirectory( VOID )
{
    NTSTATUS Status;
    UNICODE_STRING NameString;
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE Handle;
    SECURITY_DESCRIPTOR DosDevicesSD;

    //
    // Create the root directory object for the \DosDevices directory.
    //

    Status = ObpGetDosDevicesProtection( &DosDevicesSD );
    if (NT_SUCCESS( Status )) {
        RtlInitUnicodeString( &NameString, L"\\??" );
        InitializeObjectAttributes( &ObjectAttributes,
                                    &NameString,
                                    OBJ_PERMANENT,
                                    (HANDLE) NULL,
                                    &DosDevicesSD
                                  );

        Status = NtCreateDirectoryObject( &Handle,
                                          DIRECTORY_ALL_ACCESS,
                                          &ObjectAttributes
                                        );
        if (NT_SUCCESS( Status )) {
            Status = ObReferenceObjectByHandle( Handle,
                                                0,
                                                ObpDirectoryObjectType,
                                                KernelMode,
                                                (PVOID *)&ObpDosDevicesDirectoryObject,
                                                NULL
                                              );
            if (!NT_SUCCESS( Status )) {
                return( Status );
                }
            NtClose( Handle );

            ObpDosDevicesShortName.Buffer = (PWSTR)&ObpDosDevicesShortNamePrefix;
            ObpDosDevicesShortName.Length = 0;
            ObpDosDevicesShortName.MaximumLength = sizeof( ObpDosDevicesShortNamePrefix );
            RtlCopyUnicodeString( &ObpDosDevicesShortName, &NameString );
            ObpDosDevicesShortName.Buffer[ 3 ] = UNICODE_NULL;

            RtlCreateUnicodeString( &NameString, L"\\DosDevices" );
            InitializeObjectAttributes( &ObjectAttributes,
                                        &NameString,
                                        OBJ_PERMANENT,
                                        (HANDLE) NULL,
                                        &DosDevicesSD
                                      );
            Status = NtCreateSymbolicLinkObject( &Handle,
                                                 SYMBOLIC_LINK_ALL_ACCESS,
                                                 &ObjectAttributes,
                                                 &ObpDosDevicesShortName
                                               );
            if (NT_SUCCESS( Status )) {
                NtClose( Handle );
                }

            ObpDosDevicesShortName.Buffer[ 3 ] = OBJ_NAME_PATH_SEPARATOR;
            ObpDosDevicesShortName.Length += sizeof( OBJ_NAME_PATH_SEPARATOR );
            }

        ObpFreeDosDevicesProtection( &DosDevicesSD );
        }

    return Status;
}
Exemplo n.º 26
0
NTSTATUS
ReadRegistryEntries(
	IN PUNICODE_STRING RegistryPath,
	OUT PI8042_SETTINGS Settings)
{
	RTL_QUERY_REGISTRY_TABLE Parameters[17];
	NTSTATUS Status;

	ULONG DefaultKeyboardDataQueueSize = 0x64;
	PCWSTR DefaultKeyboardDeviceBaseName = L"KeyboardPort";
	ULONG DefaultMouseDataQueueSize = 0x64;
	ULONG DefaultMouseResolution = 3;
	ULONG DefaultMouseSynchIn100ns = 20000000;
	ULONG DefaultNumberOfButtons = 2;
	PCWSTR DefaultPointerDeviceBaseName = L"PointerPort";
	ULONG DefaultPollStatusIterations = 1;
	ULONG DefaultOverrideKeyboardType = 4;
	ULONG DefaultOverrideKeyboardSubtype = 0;
	ULONG DefaultPollingIterations = 12000;
	ULONG DefaultPollingIterationsMaximum = 12000;
	ULONG DefaultResendIterations = 0x3;
	ULONG DefaultSampleRate = 60;
	ULONG DefaultCrashOnCtrlScroll;

	/* Default value for CrashOnCtrlScroll depends if we're
	 * running a debug build or a normal build.
	 */
#if DBG
	DefaultCrashOnCtrlScroll = 1;
#else
	DefaultCrashOnCtrlScroll = 0;
#endif

	RtlZeroMemory(Parameters, sizeof(Parameters));

	Parameters[0].Flags = RTL_QUERY_REGISTRY_SUBKEY;
	Parameters[0].Name = L"Parameters";

	Parameters[1].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[1].Name = L"KeyboardDataQueueSize";
	Parameters[1].EntryContext = &Settings->KeyboardDataQueueSize;
	Parameters[1].DefaultType = REG_DWORD;
	Parameters[1].DefaultData = &DefaultKeyboardDataQueueSize;
	Parameters[1].DefaultLength = sizeof(ULONG);

	Parameters[2].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[2].Name = L"KeyboardDeviceBaseName";
	Parameters[2].EntryContext = &Settings->KeyboardDeviceBaseName;
	Parameters[2].DefaultType = REG_SZ;
	Parameters[2].DefaultData = (PVOID)DefaultKeyboardDeviceBaseName;
	Parameters[2].DefaultLength = 0;

	Parameters[3].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[3].Name = L"MouseDataQueueSize";
	Parameters[3].EntryContext = &Settings->MouseDataQueueSize;
	Parameters[3].DefaultType = REG_DWORD;
	Parameters[3].DefaultData = &DefaultMouseDataQueueSize;
	Parameters[3].DefaultLength = sizeof(ULONG);

	Parameters[4].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[4].Name = L"MouseResolution";
	Parameters[4].EntryContext = &Settings->MouseResolution;
	Parameters[4].DefaultType = REG_DWORD;
	Parameters[4].DefaultData = &DefaultMouseResolution;
	Parameters[4].DefaultLength = sizeof(ULONG);

	Parameters[5].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[5].Name = L"MouseSynchIn100ns";
	Parameters[5].EntryContext = &Settings->MouseSynchIn100ns;
	Parameters[5].DefaultType = REG_DWORD;
	Parameters[5].DefaultData = &DefaultMouseSynchIn100ns;
	Parameters[5].DefaultLength = sizeof(ULONG);

	Parameters[6].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[6].Name = L"NumberOfButtons";
	Parameters[6].EntryContext = &Settings->NumberOfButtons;
	Parameters[6].DefaultType = REG_DWORD;
	Parameters[6].DefaultData = &DefaultNumberOfButtons;
	Parameters[6].DefaultLength = sizeof(ULONG);

	Parameters[7].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[7].Name = L"PointerDeviceBaseName";
	Parameters[7].EntryContext = &Settings->PointerDeviceBaseName;
	Parameters[7].DefaultType = REG_SZ;
	Parameters[7].DefaultData = (PVOID)DefaultPointerDeviceBaseName;
	Parameters[7].DefaultLength = 0;

	Parameters[8].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[8].Name = L"PollStatusIterations";
	Parameters[8].EntryContext = &Settings->PollStatusIterations;
	Parameters[8].DefaultType = REG_DWORD;
	Parameters[8].DefaultData = &DefaultPollStatusIterations;
	Parameters[8].DefaultLength = sizeof(ULONG);

	Parameters[9].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[9].Name = L"OverrideKeyboardType";
	Parameters[9].EntryContext = &Settings->OverrideKeyboardType;
	Parameters[9].DefaultType = REG_DWORD;
	Parameters[9].DefaultData = &DefaultOverrideKeyboardType;
	Parameters[9].DefaultLength = sizeof(ULONG);

	Parameters[10].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[10].Name = L"OverrideKeyboardSubtype";
	Parameters[10].EntryContext = &Settings->OverrideKeyboardSubtype;
	Parameters[10].DefaultType = REG_DWORD;
	Parameters[10].DefaultData = &DefaultOverrideKeyboardSubtype;
	Parameters[10].DefaultLength = sizeof(ULONG);

	Parameters[11].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[11].Name = L"PollingIterations";
	Parameters[11].EntryContext = &Settings->PollingIterations;
	Parameters[11].DefaultType = REG_DWORD;
	Parameters[11].DefaultData = &DefaultPollingIterations;
	Parameters[11].DefaultLength = sizeof(ULONG);

	Parameters[12].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[12].Name = L"PollingIterationsMaximum";
	Parameters[12].EntryContext = &Settings->PollingIterationsMaximum;
	Parameters[12].DefaultType = REG_DWORD;
	Parameters[12].DefaultData = &DefaultPollingIterationsMaximum;
	Parameters[12].DefaultLength = sizeof(ULONG);

	Parameters[13].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[13].Name = L"ResendIterations";
	Parameters[13].EntryContext = &Settings->ResendIterations;
	Parameters[13].DefaultType = REG_DWORD;
	Parameters[13].DefaultData = &DefaultResendIterations;
	Parameters[13].DefaultLength = sizeof(ULONG);

	Parameters[14].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[14].Name = L"SampleRate";
	Parameters[14].EntryContext = &Settings->SampleRate;
	Parameters[14].DefaultType = REG_DWORD;
	Parameters[14].DefaultData = &DefaultSampleRate;
	Parameters[14].DefaultLength = sizeof(ULONG);

	Parameters[15].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[15].Name = L"CrashOnCtrlScroll";
	Parameters[15].EntryContext = &Settings->CrashOnCtrlScroll;
	Parameters[15].DefaultType = REG_DWORD;
	Parameters[15].DefaultData = &DefaultCrashOnCtrlScroll;
	Parameters[15].DefaultLength = sizeof(ULONG);

	Status = RtlQueryRegistryValues(
		RTL_REGISTRY_ABSOLUTE,
		RegistryPath->Buffer,
		Parameters,
		NULL,
		NULL);

	if (NT_SUCCESS(Status))
	{
		/* Check values */
		if (Settings->KeyboardDataQueueSize < 1)
			Settings->KeyboardDataQueueSize = DefaultKeyboardDataQueueSize;
		if (Settings->MouseDataQueueSize < 1)
			Settings->MouseDataQueueSize = DefaultMouseDataQueueSize;
		if (Settings->NumberOfButtons < 1)
			Settings->NumberOfButtons = DefaultNumberOfButtons;
		if (Settings->PollingIterations < 0x400)
			Settings->PollingIterations = DefaultPollingIterations;
		if (Settings->PollingIterationsMaximum < 0x400)
			Settings->PollingIterationsMaximum = DefaultPollingIterationsMaximum;
		if (Settings->ResendIterations < 1)
			Settings->ResendIterations = DefaultResendIterations;
	}
	else if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
	{
		/* Registry path doesn't exist. Set defaults */
		Settings->KeyboardDataQueueSize = DefaultKeyboardDataQueueSize;
		Settings->MouseDataQueueSize = DefaultMouseDataQueueSize;
		Settings->MouseResolution = DefaultMouseResolution;
		Settings->MouseSynchIn100ns = DefaultMouseSynchIn100ns;
		Settings->NumberOfButtons = DefaultNumberOfButtons;
		Settings->PollStatusIterations = DefaultPollStatusIterations;
		Settings->OverrideKeyboardType = DefaultOverrideKeyboardType;
		Settings->OverrideKeyboardSubtype = DefaultOverrideKeyboardSubtype;
		Settings->PollingIterations = DefaultPollingIterations;
		Settings->PollingIterationsMaximum = DefaultPollingIterationsMaximum;
		Settings->ResendIterations = DefaultResendIterations;
		Settings->SampleRate = DefaultSampleRate;
		Settings->CrashOnCtrlScroll = DefaultCrashOnCtrlScroll;
		if (!RtlCreateUnicodeString(&Settings->KeyboardDeviceBaseName, DefaultKeyboardDeviceBaseName)
		 || !RtlCreateUnicodeString(&Settings->PointerDeviceBaseName, DefaultPointerDeviceBaseName))
		{
			WARN_(I8042PRT, "RtlCreateUnicodeString() failed\n");
			Status = STATUS_NO_MEMORY;
		}
		else
		{
			Status = STATUS_SUCCESS;
		}
	}

	if (NT_SUCCESS(Status))
	{
		INFO_(I8042PRT, "KeyboardDataQueueSize : 0x%lx\n", Settings->KeyboardDataQueueSize);
		INFO_(I8042PRT, "KeyboardDeviceBaseName : %wZ\n", &Settings->KeyboardDeviceBaseName);
		INFO_(I8042PRT, "MouseDataQueueSize : 0x%lx\n", Settings->MouseDataQueueSize);
		INFO_(I8042PRT, "MouseResolution : 0x%lx\n", Settings->MouseResolution);
		INFO_(I8042PRT, "MouseSynchIn100ns : %lu\n", Settings->MouseSynchIn100ns);
		INFO_(I8042PRT, "NumberOfButtons : 0x%lx\n", Settings->NumberOfButtons);
		INFO_(I8042PRT, "PointerDeviceBaseName : %wZ\n", &Settings->PointerDeviceBaseName);
		INFO_(I8042PRT, "PollStatusIterations : 0x%lx\n", Settings->PollStatusIterations);
		INFO_(I8042PRT, "OverrideKeyboardType : 0x%lx\n", Settings->OverrideKeyboardType);
		INFO_(I8042PRT, "OverrideKeyboardSubtype : 0x%lx\n", Settings->OverrideKeyboardSubtype);
		INFO_(I8042PRT, "PollingIterations : 0x%lx\n", Settings->PollingIterations);
		INFO_(I8042PRT, "PollingIterationsMaximum : %lu\n", Settings->PollingIterationsMaximum);
		INFO_(I8042PRT, "ResendIterations : 0x%lx\n", Settings->ResendIterations);
		INFO_(I8042PRT, "SampleRate : %lu\n", Settings->SampleRate);
	}

	return Status;
}
Exemplo n.º 27
0
NTSTATUS
SmpHandleConnectionRequest(
    IN HANDLE ConnectionPort,
    IN PSBAPIMSG Message
    )

/*++

Routine Description:

    This routine handles connection requests from either known subsystems,
    or other clients. Other clients are admin processes.

    The protocol for connection from a known subsystem is:

        capture the name of the sub systems Sb API port

        Accept the connection

        Connect to the subsystems Sb API port

        Store the communication port handle in the known subsystem database

        signal the event associated with the known subsystem

    The protocol for others is to simply validate and accept the connection
    request.

Arguments:

Return Value:

    None.

--*/

{
    NTSTATUS st;
    HANDLE CommunicationPort;
    REMOTE_PORT_VIEW ClientView;
    PSBCONNECTINFO ConnectInfo;
    ULONG ConnectInfoLength;
    PSMPKNOWNSUBSYS KnownSubSys;
    BOOLEAN Accept;
    UNICODE_STRING SubSystemPort;
    SECURITY_QUALITY_OF_SERVICE DynamicQos;
    PSMP_CLIENT_CONTEXT ClientContext;

    //
    // Set up the security quality of service parameters to use over the
    // sb API port.  Use the most efficient (least overhead) - which is dynamic
    // rather than static tracking.
    //

    DynamicQos.ImpersonationLevel = SecurityIdentification;
    DynamicQos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
    DynamicQos.EffectiveOnly = TRUE;


    ConnectInfo = &Message->ConnectionRequest;
    KnownSubSys = SmpLocateKnownSubSysByCid(&Message->h.ClientId);

    if ( KnownSubSys ) {

        if ( SmpLocateKnownSubSysByType(ConnectInfo->SubsystemImageType) ==
             KnownSubSys ) {
            Accept = FALSE;
            KdPrint(("SMSS: Connection from SubSystem rejected\n"));
            KdPrint(("SMSS: Image type already being served\n"));
        } else {
            Accept = TRUE;
            KnownSubSys->ImageType = ConnectInfo->SubsystemImageType;
        }
    } else {

        //
        // Authenticate the SOB
        //

        Accept = TRUE;

    }

    if (Accept) {
        ClientContext = RtlAllocateHeap(SmpHeap, MAKE_TAG( SM_TAG ), sizeof(SMP_CLIENT_CONTEXT));
        ClientContext->KnownSubSys = KnownSubSys;
    }

    ClientView.Length = sizeof(ClientView);
    st = NtAcceptConnectPort(
            &CommunicationPort,
            ClientContext,
            (PPORT_MESSAGE)Message,
            Accept,
            NULL,
            &ClientView
            );
    ASSERT( NT_SUCCESS(st) );

    if ( Accept ) {

        if ( KnownSubSys ) {
            KnownSubSys->SmApiCommunicationPort = CommunicationPort;
        }

        st = NtCompleteConnectPort(CommunicationPort);
        ASSERT( NT_SUCCESS(st) );

        //
        // Connect Back to subsystem
        //

        if ( KnownSubSys ) {
            RtlCreateUnicodeString( &SubSystemPort,
                                    ConnectInfo->EmulationSubSystemPortName
                                  );
            ConnectInfoLength = sizeof( *ConnectInfo );

            st = NtConnectPort(
                    &KnownSubSys->SbApiCommunicationPort,
                    &SubSystemPort,
                    &DynamicQos,
                    NULL,
                    NULL,
                    NULL,
                    NULL,
                    NULL
                    );
            if ( !NT_SUCCESS(st) ) {
                KdPrint(("SMSS: Connect back to Sb %wZ failed %lx\n",&SubSystemPort,st));
            }

            RtlFreeUnicodeString( &SubSystemPort );
            NtSetEvent(KnownSubSys->Active,NULL);
        }
    }

    return st;
}
Exemplo n.º 28
0
NTSTATUS
NTAPI
INIT_FUNCTION
IopInitializePlugPlayServices(VOID)
{
    NTSTATUS Status;
    ULONG Disposition;
    HANDLE KeyHandle, EnumHandle, ParentHandle, TreeHandle, ControlHandle;
    UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\\REGISTRY\\MACHINE\\SYSTEM\\CURRENTCONTROLSET");
    UNICODE_STRING PnpManagerDriverName = RTL_CONSTANT_STRING(DRIVER_ROOT_NAME L"PnpManager");
    PDEVICE_OBJECT Pdo;

    /* Initialize locks and such */
    KeInitializeSpinLock(&IopDeviceTreeLock);
    KeInitializeSpinLock(&IopDeviceRelationsSpinLock);
    InitializeListHead(&IopDeviceRelationsRequestList);

    /* Get the default interface */
    PnpDefaultInterfaceType = IopDetermineDefaultInterfaceType();

    /* Initialize arbiters */
    Status = IopInitializeArbiters();
    if (!NT_SUCCESS(Status)) return Status;

    /* Setup the group cache */
    Status = PiInitCacheGroupInformation();
    if (!NT_SUCCESS(Status)) return Status;

    /* Open the current control set */
    Status = IopOpenRegistryKeyEx(&KeyHandle,
                                  NULL,
                                  &KeyName,
                                  KEY_ALL_ACCESS);
    if (!NT_SUCCESS(Status)) return Status;

    /* Create the control key */
    RtlInitUnicodeString(&KeyName, L"Control");
    Status = IopCreateRegistryKeyEx(&ControlHandle,
                                    KeyHandle,
                                    &KeyName,
                                    KEY_ALL_ACCESS,
                                    REG_OPTION_NON_VOLATILE,
                                    &Disposition);
    if (!NT_SUCCESS(Status)) return Status;

    /* Check if it's a new key */
    if (Disposition == REG_CREATED_NEW_KEY)
    {
        HANDLE DeviceClassesHandle;

        /* Create the device classes key */
        RtlInitUnicodeString(&KeyName, L"DeviceClasses");
        Status = IopCreateRegistryKeyEx(&DeviceClassesHandle,
                                        ControlHandle,
                                        &KeyName,
                                        KEY_ALL_ACCESS,
                                        REG_OPTION_NON_VOLATILE,
                                        &Disposition);
        if (!NT_SUCCESS(Status)) return Status;

        ZwClose(DeviceClassesHandle);
    }

    ZwClose(ControlHandle);

    /* Create the enum key */
    RtlInitUnicodeString(&KeyName, REGSTR_KEY_ENUM);
    Status = IopCreateRegistryKeyEx(&EnumHandle,
                                    KeyHandle,
                                    &KeyName,
                                    KEY_ALL_ACCESS,
                                    REG_OPTION_NON_VOLATILE,
                                    &Disposition);
    if (!NT_SUCCESS(Status)) return Status;

    /* Check if it's a new key */
    if (Disposition == REG_CREATED_NEW_KEY)
    {
        /* FIXME: DACLs */
        DPRINT1("Need to build DACL\n");
    }

    /* Create the root key */
    ParentHandle = EnumHandle;
    RtlInitUnicodeString(&KeyName, REGSTR_KEY_ROOTENUM);
    Status = IopCreateRegistryKeyEx(&EnumHandle,
                                    ParentHandle,
                                    &KeyName,
                                    KEY_ALL_ACCESS,
                                    REG_OPTION_NON_VOLATILE,
                                    &Disposition);
    NtClose(ParentHandle);
    if (!NT_SUCCESS(Status)) return Status;
    NtClose(EnumHandle);

    /* Open the root key now */
    RtlInitUnicodeString(&KeyName, L"\\REGISTRY\\MACHINE\\SYSTEM\\CURRENTCONTROLSET\\ENUM");
    Status = IopOpenRegistryKeyEx(&EnumHandle,
                                  NULL,
                                  &KeyName,
                                  KEY_ALL_ACCESS);
    if (NT_SUCCESS(Status))
    {
        /* Create the root dev node */
        RtlInitUnicodeString(&KeyName, REGSTR_VAL_ROOT_DEVNODE);
        Status = IopCreateRegistryKeyEx(&TreeHandle,
                                        EnumHandle,
                                        &KeyName,
                                        KEY_ALL_ACCESS,
                                        REG_OPTION_NON_VOLATILE,
                                        NULL);
        NtClose(EnumHandle);
        if (NT_SUCCESS(Status)) NtClose(TreeHandle);
    }

    /* Create the root driver */
    Status = IoCreateDriver(&PnpManagerDriverName, PnpRootDriverEntry);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("IoCreateDriverObject() failed\n");
        KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
    }

    /* Create the root PDO */
    Status = IoCreateDevice(IopRootDriverObject,
                            sizeof(IOPNP_DEVICE_EXTENSION),
                            NULL,
                            FILE_DEVICE_CONTROLLER,
                            0,
                            FALSE,
                            &Pdo);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("IoCreateDevice() failed\n");
        KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
    }

    /* This is a bus enumerated device */
    Pdo->Flags |= DO_BUS_ENUMERATED_DEVICE;

    /* Create the root device node */
    IopRootDeviceNode = PipAllocateDeviceNode(Pdo);

    /* Set flags */
    IopRootDeviceNode->Flags |= DNF_STARTED + DNF_PROCESSED + DNF_ENUMERATED +
                                DNF_MADEUP + DNF_NO_RESOURCE_REQUIRED +
                                DNF_ADDED;

    /* Create instance path */
    RtlCreateUnicodeString(&IopRootDeviceNode->InstancePath,
                           REGSTR_VAL_ROOT_DEVNODE);

    /* Call the add device routine */
    IopRootDriverObject->DriverExtension->AddDevice(IopRootDriverObject,
                                                    IopRootDeviceNode->PhysicalDeviceObject);

    /* Initialize PnP-Event notification support */
    Status = IopInitPlugPlayEvents();
    if (!NT_SUCCESS(Status)) return Status;

    /* Report the device to the user-mode pnp manager */
    IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
                              &IopRootDeviceNode->InstancePath);

    /* Initialize the Bus Type GUID List */
    PnpBusTypeGuidList = ExAllocatePool(PagedPool, sizeof(IO_BUS_TYPE_GUID_LIST));
    RtlZeroMemory(PnpBusTypeGuidList, sizeof(IO_BUS_TYPE_GUID_LIST));
    ExInitializeFastMutex(&PnpBusTypeGuidList->Lock);

    /* Launch the firmware mapper */
    Status = IopUpdateRootKey();
    if (!NT_SUCCESS(Status)) return Status;

    /* Close the handle to the control set */
    NtClose(KeyHandle);

    /* We made it */
    return STATUS_SUCCESS;
}
Exemplo n.º 29
0
/**********************************************************************
 *	StartServiceCtrlDispatcherW
 *
 * @implemented
 */
BOOL WINAPI
StartServiceCtrlDispatcherW(const SERVICE_TABLE_ENTRYW *lpServiceStartTable)
{
    ULONG i;
    HANDLE hPipe;
    DWORD dwError;
    PSCM_CONTROL_PACKET ControlPacket;
    DWORD dwBufSize;
    BOOL bRet = TRUE;

    TRACE("StartServiceCtrlDispatcherW() called\n");

    i = 0;
    while (lpServiceStartTable[i].lpServiceProc != NULL)
    {
        i++;
    }

    dwActiveServiceCount = i;
    lpActiveServices = RtlAllocateHeap(RtlGetProcessHeap(),
                                       HEAP_ZERO_MEMORY,
                                       dwActiveServiceCount * sizeof(ACTIVE_SERVICE));
    if (lpActiveServices == NULL)
    {
        return FALSE;
    }

    /* Copy service names and start procedure */
    for (i = 0; i < dwActiveServiceCount; i++)
    {
        RtlCreateUnicodeString(&lpActiveServices[i].ServiceName,
                               lpServiceStartTable[i].lpServiceName);
        lpActiveServices[i].ThreadParams.W.lpServiceMain = lpServiceStartTable[i].lpServiceProc;
        lpActiveServices[i].hServiceStatus = 0;
        lpActiveServices[i].bUnicode = TRUE;
        lpActiveServices[i].bOwnProcess = FALSE;
    }

    dwError = ScConnectControlPipe(&hPipe);
    if (dwError != ERROR_SUCCESS)
    {
        bRet = FALSE;
        goto done;
    }

    dwBufSize = sizeof(SCM_CONTROL_PACKET) +
                (MAX_SERVICE_NAME_LENGTH + 1) * sizeof(WCHAR);

    ControlPacket = RtlAllocateHeap(RtlGetProcessHeap(),
                                    HEAP_ZERO_MEMORY,
                                    dwBufSize);
    if (ControlPacket == NULL)
    {
        bRet = FALSE;
        goto done;
    }

    ScCreateStatusBinding();

    ScServiceDispatcher(hPipe, ControlPacket, dwBufSize);

    ScDestroyStatusBinding();

    CloseHandle(hPipe);

    /* Free the control packet */
    RtlFreeHeap(RtlGetProcessHeap(), 0, ControlPacket);

done:
    /* Free the service table */
    for (i = 0; i < dwActiveServiceCount; i++)
    {
        RtlFreeUnicodeString(&lpActiveServices[i].ServiceName);
    }
    RtlFreeHeap(RtlGetProcessHeap(), 0, lpActiveServices);
    lpActiveServices = NULL;
    dwActiveServiceCount = 0;

    return bRet;
}
Exemplo n.º 30
0
NTSTATUS
NTAPI
SmpHandleConnectionRequest(IN HANDLE SmApiPort,
                           IN PSB_API_MSG SbApiMsg)
{
    BOOLEAN Accept = TRUE;
    HANDLE PortHandle, ProcessHandle;
    ULONG SessionId;
    UNICODE_STRING SubsystemPort;
    SMP_CLIENT_CONTEXT *ClientContext;
    NTSTATUS Status;
    OBJECT_ATTRIBUTES ObjectAttributes;
    REMOTE_PORT_VIEW PortView;
    SECURITY_QUALITY_OF_SERVICE SecurityQos;
    PSMP_SUBSYSTEM CidSubsystem, TypeSubsystem;

    /* Initialize QoS data */
    SecurityQos.ImpersonationLevel = SecurityIdentification;
    SecurityQos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
    SecurityQos.EffectiveOnly = TRUE;

    /* Check if this is SM connecting to itself */
    if (SbApiMsg->h.ClientId.UniqueProcess == SmUniqueProcessId)
    {
        /* No need to get any handle -- assume session 0 */
        ProcessHandle = NULL;
        SessionId = 0;
    }
    else
    {
        /* Reference the foreign process */
        InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL);
        Status = NtOpenProcess(&ProcessHandle,
                               PROCESS_QUERY_INFORMATION,
                               &ObjectAttributes,
                               &SbApiMsg->h.ClientId);
        if (!NT_SUCCESS(Status)) Accept = FALSE;

        /* Get its session ID */
        SmpGetProcessMuSessionId(ProcessHandle, &SessionId);
    }

    /* See if we already know about the caller's subystem */
    CidSubsystem = SmpLocateKnownSubSysByCid(&SbApiMsg->h.ClientId);
    if ((CidSubsystem) && (Accept))
    {
        /* Check if we already have a subsystem for this kind of image */
        TypeSubsystem = SmpLocateKnownSubSysByType(SessionId,
                                                   SbApiMsg->ConnectionInfo.SubsystemType);
        if (TypeSubsystem == CidSubsystem)
        {
            /* Someone is trying to take control of an existing subsystem, fail */
            Accept = FALSE;
            DPRINT1("SMSS: Connection from SubSystem rejected\n");
            DPRINT1("SMSS: Image type already being served\n");
        }
        else
        {
            /* Set this image type as the type for this subsystem */
            CidSubsystem->ImageType = SbApiMsg->ConnectionInfo.SubsystemType;
        }

        /* Drop the reference we had acquired */
        if (TypeSubsystem) SmpDereferenceSubsystem(TypeSubsystem);
    }

    /* Check if we'll be accepting the connection */
    if (Accept)
    {
        /* We will, so create a client context for it */
        ClientContext = RtlAllocateHeap(SmpHeap, 0, sizeof(SMP_CLIENT_CONTEXT));
        if (ClientContext)
        {
            ClientContext->ProcessHandle = ProcessHandle;
            ClientContext->Subsystem = CidSubsystem;
            ClientContext->dword10 = 0;
            ClientContext->PortHandle = NULL;
        }
        else
        {
            /* Failed to allocate a client context, so reject the connection */
            DPRINT1("Rejecting connectiond due to lack of memory\n");
            Accept = FALSE;
        }
    }
    else
    {
        /* Use a bogus context since we're going to reject the message */
        ClientContext = (PSMP_CLIENT_CONTEXT)SbApiMsg;
    }

    /* Now send the actual accept reply (which could be a rejection) */
    PortView.Length = sizeof(PortView);
    Status = NtAcceptConnectPort(&PortHandle,
                                 ClientContext,
                                 &SbApiMsg->h,
                                 Accept,
                                 NULL,
                                 &PortView);
    if (!(Accept) || !(NT_SUCCESS(Status)))
    {
        /* Close the process handle, reference the subsystem, and exit */
        DPRINT1("Accept failed or rejected: %lx\n", Status);
        if (ClientContext != (PVOID)SbApiMsg) RtlFreeHeap(SmpHeap, 0, ClientContext);
        if (ProcessHandle) NtClose(ProcessHandle);
        if (CidSubsystem) SmpDereferenceSubsystem(CidSubsystem);
        return Status;
    }

    /* Save the port handle now that we've accepted it */
    if (ClientContext) ClientContext->PortHandle = PortHandle;
    if (CidSubsystem) CidSubsystem->PortHandle = PortHandle;

    /* Complete the port connection */
    Status = NtCompleteConnectPort(PortHandle);
    if ((NT_SUCCESS(Status)) && (CidSubsystem))
    {
        /* This was an actual subsystem, so connect back to it */
        SbApiMsg->ConnectionInfo.SbApiPortName[119] = UNICODE_NULL;
        RtlCreateUnicodeString(&SubsystemPort,
                               SbApiMsg->ConnectionInfo.SbApiPortName);
        Status = NtConnectPort(&CidSubsystem->SbApiPort,
                               &SubsystemPort,
                               &SecurityQos,
                               NULL,
                               NULL,
                               NULL,
                               NULL,
                               NULL);
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("SMSS: Connect back to Sb %wZ failed %lx\n", &SubsystemPort, Status);
        }
        RtlFreeUnicodeString(&SubsystemPort);

        /* Now that we're connected, signal the event handle */
        NtSetEvent(CidSubsystem->Event, NULL);
    }
    else if (CidSubsystem)
    {
        /* We failed to complete the connection, so clear the port handle */
        DPRINT1("Completing the connection failed: %lx\n", Status);
        CidSubsystem->PortHandle = NULL;
    }

    /* Dereference the subsystem and return the result */
    if (CidSubsystem) SmpDereferenceSubsystem(CidSubsystem);
    return Status;
}