Пример #1
0
/*
 * @implemented
 */
BOOL
WINAPI
CheckNameLegalDOS8Dot3A(
    LPCSTR lpName,
    LPSTR lpOemName OPTIONAL,
    DWORD OemNameSize OPTIONAL,
    PBOOL pbNameContainsSpaces OPTIONAL,
    PBOOL pbNameLegal
    )
{
    UNICODE_STRING Name;
    ANSI_STRING AnsiName, AnsiInputName;
    NTSTATUS Status;
    BOOLEAN NameContainsSpaces;

    if(lpName == NULL ||
       (lpOemName == NULL && OemNameSize != 0) ||
       pbNameLegal == NULL)
    {
      SetLastError(ERROR_INVALID_PARAMETER);
      return FALSE;
    }

    if(lpOemName != NULL)
    {
      AnsiName.Buffer = lpOemName;
      AnsiName.MaximumLength = (USHORT)OemNameSize * sizeof(CHAR);
      AnsiName.Length = 0;
    }

    RtlInitAnsiString(&AnsiInputName, (LPSTR)lpName);
    if(bIsFileApiAnsi)
      Status = RtlAnsiStringToUnicodeString(&Name, &AnsiInputName, TRUE);
    else
      Status = RtlOemStringToUnicodeString(&Name, &AnsiInputName, TRUE);

    if(!NT_SUCCESS(Status))
    {
      BaseSetLastNTError(Status);
      return FALSE;
    }

    *pbNameLegal = RtlIsNameLegalDOS8Dot3(&Name,
                                          (lpOemName ? &AnsiName : NULL),
                                          &NameContainsSpaces);
    if (*pbNameLegal && pbNameContainsSpaces)
        *pbNameContainsSpaces = NameContainsSpaces;

    RtlFreeUnicodeString(&Name);

    return TRUE;
}
Пример #2
0
BOOLEAN
OpenMailslot(
    PSZ Name,
    PHANDLE Handle
    )
{
    STRING ansiString;
    UNICODE_STRING nameString;
    NTSTATUS status;
    OBJECT_ATTRIBUTES objectAttributes;
    IO_STATUS_BLOCK ioStatusBlock;

    RtlInitString(&ansiString, Name );
    RtlOemStringToUnicodeString(&nameString, &ansiString, TRUE);

    //
    //  Open the mailslot
    //

    InitializeObjectAttributes(
        &objectAttributes,
        &nameString,
        OBJ_CASE_INSENSITIVE,
        NULL,
        NULL
        );

    printf( "Attempting to open mailslot \"%wZ\"\n", &nameString );

    status = NtOpenFile (
                Handle,
                FILE_WRITE_DATA | SYNCHRONIZE,
                &objectAttributes,
                &ioStatusBlock,
                FILE_SHARE_WRITE | FILE_SHARE_READ,
                0L
                );

    printf( "Status = %x\n", status );

    RtlFreeUnicodeString(&nameString);
    return ( (BOOLEAN) NT_SUCCESS( status ) );
}
Пример #3
0
STATIC DWORD
MsgDisplayThread(
    LPVOID  parm
    )

/*++

Routine Description:


Arguments:


Return Value:


Note:

    This worker thread expects that the critical section guarding the
    global queue data is already initialized.


--*/
{
    LPQUEUE_ENTRY   pQueueEntry;
    INT             displayStatus;
    DWORD           msgrState;
    UNICODE_STRING  unicodeString;
    OEM_STRING      oemString;
    NTSTATUS        ntStatus;
    BOOL            unicodeFlag;
    USHORT          unicodeLength;
    LPSTR           pHead;      // pointer to header portion of message
    LPSTR           pTime;      // pointer to time portion of message
    LPSTR           pBody;      // pointer to body of message (just after time)
    DWORD           BigTime;
    BOOL            MsgToRead=TRUE;  // tells us whether or not to sleep.


    UNREFERENCED_PARAMETER(parm);

    pHead = NULL;
    pQueueEntry = NULL;

    do {

        //
        // If we are not currently working on displaying a message,
        // then get a new message from the queue.
        //
        if (pHead == NULL) {

            //  ***************************
            //  **** LOCK QUEUE ACCESS ****
            //  ***************************
            EnterCriticalSection(&MsgDisplayCriticalSection);

            if (!MsgDisplayQueueRead(&pQueueEntry)) {

                //
                // No display entries in the queue.  We can leave.
                //
                MsgToRead = FALSE;

                CloseHandle(GlobalDisplayThread);
                GlobalDisplayThread = NULL;

                if (hGlobalDisplayEvent != NULL) {
                    CloseHandle(hGlobalDisplayEvent);
                    hGlobalDisplayEvent = NULL;
                }

                //  *****************************
                //  **** UNLOCK QUEUE ACCESS ****
                //  *****************************
                LeaveCriticalSection(&MsgDisplayCriticalSection);
                //
                // From this point on, we can't access any global
                // variables.
                //
            }
            else {
                //  *****************************
                //  **** UNLOCK QUEUE ACCESS ****
                //  *****************************
                LeaveCriticalSection(&MsgDisplayCriticalSection);

                //
                // Process the entry.
                //
                BigTime = pQueueEntry->BigTime;
                //
                // Here we trash the pQueueEntry structure by pointing to the
                // beginning and copying the message data starting at the
                // first address.  This is because MsgMakeNewFormattedMsg
                // expects the message to begin at a address that can be
                // released with LocalFree();
                //
                pHead = (LPSTR)pQueueEntry;
                strcpy(pHead, pQueueEntry->Message);

                pTime = strstr(pHead, GlobalTimePlaceHolder);
                pBody = pTime+strlen(GlobalTimePlaceHolder);
                if (pTime == NULL) {
                    pTime=pBody;
                }
            }
        }
        if (pHead != NULL) {
            MsgMakeNewFormattedMsg(&pHead,&pTime,&pBody,BigTime);

            unicodeFlag = TRUE;
            //
            // Convert the data from the OEM character set to the
            // Unicode character set.
            //
            //
            // Translate the oem string in the name table to a unicode name
            //
            RtlInitAnsiString( &oemString, pHead);

            unicodeLength = oemString.Length * sizeof(WCHAR);

            unicodeString.Buffer = (WCHAR *)LocalAlloc(
                LMEM_ZEROINIT,
                unicodeLength + sizeof(WCHAR));

            if (unicodeString.Buffer == NULL) {

                //
                // Couldn't allocate for unicode buffer.  Therefore we will
                // display the message with the Ansi version of the
                // message box API.
                //
                unicodeFlag = FALSE;
            }
            else {

                unicodeString.Length = unicodeLength;
                unicodeString.MaximumLength = unicodeLength + sizeof(WCHAR);

                ntStatus = RtlOemStringToUnicodeString(
                            &unicodeString,      // Destination
                            &oemString,          // Source
                            FALSE);              // Don't allocate the destination.

                if (!NT_SUCCESS(ntStatus)) {
                    MSG_LOG(ERROR,
                        "MsgDisplayThread:RtlOemStringToUnicodeString Failed rc=%X\n",
                        ntStatus);
                    //
                    // Attempt to display with ANSI MessageBox
                    //
                    LocalFree(unicodeString.Buffer);
                    unicodeString.Buffer = NULL;
                    unicodeFlag = FALSE;
                }
            }

            if (unicodeFlag) {

                //
                // Display the data in the QueueEntry as Unicode
                //
                MSG_LOG(TRACE,"Calling MessageBox (Unicode) Function\n",0);

                displayStatus = MessageBoxW(
                                NULL,
                                unicodeString.Buffer,
                                GlobalMessageBoxTitle,
                                MB_OK | MB_SYSTEMMODAL | MB_SERVICE_NOTIFICATION |
                                MB_SETFOREGROUND | MB_DEFAULT_DESKTOP_ONLY);

                if (displayStatus == 0) {
                    MSG_LOG1(TRACE,"MessageBox (unicode) Call failed %d\n",GetLastError());
                    WaitForSingleObject( hGlobalDisplayEvent, INFINITE );
                }
                else {
                    //
                    // Free up the data in the QueueEntry
                    //
                    LocalFree(pHead);
                    pHead = NULL;
                }
                LocalFree(unicodeString.Buffer);
                unicodeString.Buffer = NULL;
                unicodeFlag = FALSE;
            }
            else {
                //
                // Display the data in the QueueEntry as Ansi
                //
                MSG_LOG(TRACE,"Calling MessageBox (Ansi) Function\n",0);

                displayStatus = MessageBoxA(
                                NULL,
                                pHead,
                                "Messenger Service",
                                MB_OK | MB_SYSTEMMODAL | MB_SERVICE_NOTIFICATION |
                                MB_SETFOREGROUND | MB_DEFAULT_DESKTOP_ONLY);

                if (displayStatus == 0) {
                    MSG_LOG0(ERROR,"MessageBox (Ansi) Call failed\n");

                    WaitForSingleObject( hGlobalDisplayEvent, INFINITE );
                }
                else {
                    //
                    // Free up the data in the QueueEntry
                    // We only want to free this if the message was
                    // displayed.
                    //
                    LocalFree(pHead);
                    pHead = NULL;
                }
            }
        }
        msgrState = GetMsgrState();
    }
    while(MsgToRead && (msgrState != STOPPING) && (msgrState != STOPPED));

    return(0);
}
Пример #4
0
static INT_PTR CALLBACK NetworkOutputDlgProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
    )
{
    PNETWORK_OUTPUT_CONTEXT context;

    if (uMsg == WM_INITDIALOG)
    {
        context = (PNETWORK_OUTPUT_CONTEXT)lParam;
        SetProp(hwndDlg, L"Context", (HANDLE)context);
    }
    else
    {
        context = (PNETWORK_OUTPUT_CONTEXT)GetProp(hwndDlg, L"Context");

        if (uMsg == WM_DESTROY)
        {
            PhSaveWindowPlacementToSetting(SETTING_NAME_TRACERT_WINDOW_POSITION, SETTING_NAME_TRACERT_WINDOW_SIZE, hwndDlg);
            PhDeleteLayoutManager(&context->LayoutManager);

            if (context->ProcessHandle)
            {
                // Terminate the child process.
                PhTerminateProcess(context->ProcessHandle, STATUS_SUCCESS);

                // Close the child process handle.
                NtClose(context->ProcessHandle);
            }

            // Close the pipe handle.
            if (context->PipeReadHandle)
                NtClose(context->PipeReadHandle);

            RemoveProp(hwndDlg, L"Context");
            PhFree(context);
        }
    }

    if (!context)
        return FALSE;

    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            PH_RECTANGLE windowRectangle;

            context->WindowHandle = hwndDlg;
            context->OutputHandle = GetDlgItem(hwndDlg, IDC_NETOUTPUTEDIT);

            PhInitializeLayoutManager(&context->LayoutManager, hwndDlg);
            PhAddLayoutItem(&context->LayoutManager, context->OutputHandle, NULL, PH_ANCHOR_ALL);
            PhAddLayoutItem(&context->LayoutManager, GetDlgItem(hwndDlg, IDC_MORE_INFO), NULL, PH_ANCHOR_BOTTOM | PH_ANCHOR_LEFT);
            PhAddLayoutItem(&context->LayoutManager, GetDlgItem(hwndDlg, IDOK), NULL, PH_ANCHOR_BOTTOM | PH_ANCHOR_RIGHT);

            windowRectangle.Position = PhGetIntegerPairSetting(SETTING_NAME_TRACERT_WINDOW_POSITION);
            windowRectangle.Size = PhGetIntegerPairSetting(SETTING_NAME_TRACERT_WINDOW_SIZE);

            if (MinimumSize.left == -1)
            {
                RECT rect;

                rect.left = 0;
                rect.top = 0;
                rect.right = 190;
                rect.bottom = 120;
                MapDialogRect(hwndDlg, &rect);
                MinimumSize = rect;
                MinimumSize.left = 0;
            }

            // Check for first-run default position.
            if (windowRectangle.Position.X == 0 || windowRectangle.Position.Y == 0)
            {
                PhCenterWindow(hwndDlg, GetParent(hwndDlg));
            }
            else
            {
                PhLoadWindowPlacementFromSetting(SETTING_NAME_TRACERT_WINDOW_POSITION, SETTING_NAME_TRACERT_WINDOW_SIZE, hwndDlg);
            }

            if (context->IpAddress.Type == PH_IPV4_NETWORK_TYPE)
            {
                RtlIpv4AddressToString(&context->IpAddress.InAddr, context->IpAddressString);
            }
            else
            {
                RtlIpv6AddressToString(&context->IpAddress.In6Addr, context->IpAddressString);
            }

            switch (context->Action)
            {
            case NETWORK_ACTION_TRACEROUTE:
                {
                    HANDLE dialogThread = INVALID_HANDLE_VALUE;

                    Static_SetText(context->WindowHandle,
                        PhaFormatString(L"Tracing route to %s...", context->IpAddressString)->Buffer
                        );

                    if (dialogThread = PhCreateThread(0, NetworkTracertThreadStart, (PVOID)context))
                        NtClose(dialogThread);
                }
                break;
            case NETWORK_ACTION_WHOIS:
                {
                    HANDLE dialogThread = INVALID_HANDLE_VALUE;

                    Static_SetText(context->WindowHandle,
                        PhaFormatString(L"Whois %s...", context->IpAddressString)->Buffer
                        );

                    ShowWindow(GetDlgItem(hwndDlg, IDC_MORE_INFO), SW_SHOW);

                    if (dialogThread = PhCreateThread(0, NetworkWhoisThreadStart, (PVOID)context))
                        NtClose(dialogThread);
                }
                break;
            }
        }
        break;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDCANCEL:
            case IDOK:
                PostQuitMessage(0);
                break;
            }
        }
        break;
    case WM_SIZE:
        PhLayoutManagerLayout(&context->LayoutManager);
        break;
    case WM_SIZING:
        PhResizingMinimumSize((PRECT)lParam, wParam, MinimumSize.right, MinimumSize.bottom);
        break;
    case WM_CTLCOLORDLG:
    case WM_CTLCOLORSTATIC:
        {
            HDC hDC = (HDC)wParam;
            HWND hwndChild = (HWND)lParam;

            // Check if old graph colors are enabled.
            if (!PhGetIntegerSetting(L"GraphColorMode"))
                break;

            // Set a transparent background for the control backcolor.
            SetBkMode(hDC, TRANSPARENT);

            // Check for our edit control and change the color.
            if (hwndChild == context->OutputHandle)
            {
                // Set text color as the Green PH graph text color.
                SetTextColor(hDC, RGB(124, 252, 0));

                // Set a black control backcolor.
                return (INT_PTR)GetStockBrush(BLACK_BRUSH);
            }
        }
        break;
    case WM_NOTIFY:
        {
            switch (((LPNMHDR)lParam)->code)
            {
            case NM_CLICK:
            case NM_RETURN:
                {
                    PNMLINK syslink = (PNMLINK)lParam;

                    if (syslink->hdr.idFrom == IDC_MORE_INFO)
                    {
                        PhShellExecute(
                            PhMainWndHandle,
                            PhaConcatStrings2(L"http://wq.apnic.net/apnic-bin/whois.pl?searchtext=", context->IpAddressString)->Buffer,
                            NULL
                            );
                    }
                }
                break;
            }
        }
        break;
    case NTM_RECEIVEDTRACE:
        {
            OEM_STRING inputString;
            UNICODE_STRING convertedString;
            PH_STRING_BUILDER receivedString;

            if (wParam != 0)
            {
                inputString.Buffer = (PCHAR)lParam;
                inputString.Length = (USHORT)wParam;

                if (NT_SUCCESS(RtlOemStringToUnicodeString(&convertedString, &inputString, TRUE)))
                {
                    PPH_STRING windowText = NULL;

                    PhInitializeStringBuilder(&receivedString, PAGE_SIZE);

                    // Get the current output text.
                    windowText = PhGetWindowText(context->OutputHandle);

                    // Append the current output text to the New string.
                    if (!PhIsNullOrEmptyString(windowText))
                        PhAppendStringBuilder(&receivedString, &windowText->sr);

                    PhAppendFormatStringBuilder(&receivedString, L"%s", convertedString.Buffer);

                    // Remove leading newlines.
                    if (receivedString.String->Length >= 2 * 2 &&
                        receivedString.String->Buffer[0] == '\r' &&
                        receivedString.String->Buffer[1] == '\n')
                    {
                        PhRemoveStringBuilder(&receivedString, 0, 2);
                    }

                    SetWindowText(context->OutputHandle, receivedString.String->Buffer);
                    SendMessage(
                        context->OutputHandle,
                        EM_SETSEL,
                        receivedString.String->Length / 2 - 1,
                        receivedString.String->Length / 2 - 1
                        );
                    SendMessage(context->OutputHandle, WM_VSCROLL, SB_BOTTOM, 0);

                    PhDereferenceObject(windowText);
                    PhDeleteStringBuilder(&receivedString);
                    RtlFreeUnicodeString(&convertedString);
                }
            }
        }
        break;
    case NTM_RECEIVEDWHOIS:
        {
            OEM_STRING inputString;
            UNICODE_STRING convertedString;
            PH_STRING_BUILDER receivedString;

            if (lParam != 0)
            {
                inputString.Buffer = (PCHAR)lParam;
                inputString.Length = (USHORT)wParam;

                if (NT_SUCCESS(RtlOemStringToUnicodeString(&convertedString, &inputString, TRUE)))
                {
                    USHORT i;

                    PhInitializeStringBuilder(&receivedString, PAGE_SIZE);

                    // Convert carriage returns.
                    for (i = 0; i < convertedString.Length; i++)
                    {
                        if (convertedString.Buffer[i] == '\n')
                        {
                            PhAppendStringBuilder2(&receivedString, L"\r\n");
                        }
                        else
                        {
                            PhAppendCharStringBuilder(&receivedString, convertedString.Buffer[i]);
                        }
                    }

                    // Remove leading newlines.
                    if (receivedString.String->Length >= 2 * 2 &&
                        receivedString.String->Buffer[0] == '\r' &&
                        receivedString.String->Buffer[1] == '\n')
                    {
                        PhRemoveStringBuilder(&receivedString, 0, 2);
                    }

                    SetWindowText(context->OutputHandle, receivedString.String->Buffer);
                    SendMessage(
                        context->OutputHandle,
                        EM_SETSEL,
                        receivedString.String->Length / 2 - 1,
                        receivedString.String->Length / 2 - 1
                        );
                    SendMessage(context->OutputHandle, WM_VSCROLL, SB_TOP, 0);

                    PhDeleteStringBuilder(&receivedString);
                    RtlFreeUnicodeString(&convertedString);
                }

                PhFree((PVOID)lParam);
            }
        }
        break;
    case NTM_RECEIVEDFINISH:
        {
            PPH_STRING windowText = PhGetWindowText(context->WindowHandle);

            if (windowText)
            {
                Static_SetText(
                    context->WindowHandle,
                    PhaFormatString(L"%s Finished.", windowText->Buffer)->Buffer
                    );
                PhDereferenceObject(windowText);
            }
        }
        break;
    }

    return FALSE;
}
Пример #5
0
NET_API_STATUS NET_API_FUNCTION
NetrConnectionEnum (
    IN LPTSTR ServerName,
    IN LPTSTR Qualifier,
    IN LPCONNECT_ENUM_STRUCT InfoStruct,
    IN DWORD PreferredMaximumLength,
    OUT LPDWORD TotalEntries,
    IN OUT LPDWORD ResumeHandle OPTIONAL
    )

/*++

Routine Description:

    This routine communicates with the server FSD to implement the
    NetConnectionEnum function.

Arguments:

    None.

Return Value:

    NET_API_STATUS - NO_ERROR or reason for failure.

--*/

{
    NET_API_STATUS error;
    PSERVER_REQUEST_PACKET srp;

    ServerName;

    //
    // Make sure that the level is valid.  Since it is an unsigned
    // value, it can never be less than 0.
    //

    if ( InfoStruct->Level > 1 ) {
        return ERROR_INVALID_LEVEL;
    }

    //
    // The qualifier cannot be null or can it be a null string
    //

    if ( Qualifier == NULL || *Qualifier == L'\0' ) {
        return ERROR_INVALID_PARAMETER;
    }

    //
    // Make sure that the caller is allowed to get connection
    // information in the server.
    //

    error = SsCheckAccess(
                &SsConnectionSecurityObject,
                SRVSVC_CONNECTION_INFO_GET
                );

    if ( error != NO_ERROR ) {
        return ERROR_ACCESS_DENIED;
    }

    //
    // Set up the input parameters in the request buffer.
    //

    srp = SsAllocateSrp( );
    if ( srp == NULL ) {
        return ERROR_NOT_ENOUGH_MEMORY;
    }
    srp->Level = InfoStruct->Level;

#ifdef UNICODE
    RtlInitUnicodeString( &srp->Name1, Qualifier );
#else
    {
        OEM_STRING ansiString;
        NTSTATUS status;
        NetpInitOemString( &ansiString, Qualifier );
        status = RtlOemStringToUnicodeString( &srp->Name1, &ansiString, TRUE );
        SS_ASSERT( NT_SUCCESS(status) );
    }
#endif

    if ( ARGUMENT_PRESENT( ResumeHandle ) ) {
        srp->Parameters.Get.ResumeHandle = *ResumeHandle;
    } else {
        srp->Parameters.Get.ResumeHandle = 0;
    }

    //
    // Get the data from the server.  This routine will allocate the
    // return buffer and handle the case where PreferredMaximumLength ==
    // -1.
    //

    error = SsServerFsControlGetInfo(
                FSCTL_SRV_NET_CONNECTION_ENUM,
                srp,
                (PVOID *)&InfoStruct->ConnectInfo.Level1->Buffer,
                PreferredMaximumLength
                );

    //
    // Set up return information.
    //

    InfoStruct->ConnectInfo.Level1->EntriesRead =
        srp->Parameters.Get.EntriesRead;
    *TotalEntries = srp->Parameters.Get.TotalEntries;

    if ( srp->Parameters.Get.EntriesRead > 0 &&
             ARGUMENT_PRESENT( ResumeHandle ) ) {
        *ResumeHandle = srp->Parameters.Get.ResumeHandle;
    }

#ifndef UNICODE
    RtlFreeUnicodeString( &srp->Name1 );
#endif

    SsFreeSrp( srp );

    return error;

} // NetrConnectionEnum
Пример #6
0
VOID cmdCreateProcess ( VOID )
{

    VDMINFO VDMInfoForCount;
    STARTUPINFO StartupInfo;
    PROCESS_INFORMATION ProcessInformation;
    HANDLE hStd16In,hStd16Out,hStd16Err;
    CHAR CurDirVar [] = "=?:";
    CHAR Buffer [MAX_DIR];
    CHAR *CurDir = Buffer;
    DWORD dwRet;
    BOOL  Status;
    NTSTATUS NtStatus;
    UNICODE_STRING Unicode;
    OEM_STRING	   OemString;
    LPVOID lpNewEnv=NULL;
    PSTD_HANDLES pStdHandles;
    ANSI_STRING Env_A;

    // we have one more 32 executable active
    Exe32ActiveCount++;

    // Increment the Re-enterancy count for the VDM
    VDMInfoForCount.VDMState = INCREMENT_REENTER_COUNT;
    GetNextVDMCommand (&VDMInfoForCount);

    RtlZeroMemory((PVOID)&StartupInfo,sizeof(STARTUPINFO));
    StartupInfo.cb = sizeof(STARTUPINFO);

    CurDirVar [1] = chDefaultDrive;

    dwRet = GetEnvironmentVariable (CurDirVar,Buffer,MAX_DIR);

    if (dwRet == 0 || dwRet == MAX_DIR)
	CurDir = NULL;

    pStdHandles = (PSTD_HANDLES) GetVDMAddr (getSS(), getBP());
    if ((hStd16In = (HANDLE) FETCHDWORD(pStdHandles->hStdIn)) != (HANDLE)-1)
        SetStdHandle (STD_INPUT_HANDLE, hStd16In);

    if ((hStd16Out = (HANDLE) FETCHDWORD(pStdHandles->hStdOut)) != (HANDLE)-1)
        SetStdHandle (STD_OUTPUT_HANDLE, hStd16Out);

    if ((hStd16Err = (HANDLE) FETCHDWORD(pStdHandles->hStdErr)) != (HANDLE)-1)
        SetStdHandle (STD_ERROR_HANDLE, hStd16Err);

    /*
     *  Warning, pEnv32 currently points to an ansi environment.
     *  The DOS is using an ANSI env which isn't quite correct.
     *  If the DOS is changed to use an OEM env then we will
     *  have to convert the env back to ansi before spawning
     *  non-dos exes ?!?
     *  16-Jan-1993 Jonle
     */

    Env_A.Buffer = NULL;

    RtlInitString((PSTRING)&OemString, pCommand32);
    NtStatus = RtlOemStringToUnicodeString(&Unicode,&OemString,TRUE);
    if (NT_SUCCESS(NtStatus)) {
        NtStatus = RtlUnicodeStringToAnsiString((PANSI_STRING)&OemString, &Unicode, FALSE);
        RtlFreeUnicodeString( &Unicode );
        }
    if (!NT_SUCCESS(NtStatus)) {
        SetLastError(RtlNtStatusToDosError(NtStatus));
        Status = FALSE;
        }
    else {
	if (pEnv32 != NULL && !cmdXformEnvironment (pEnv32, &Env_A)) {
	    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
	    Status = FALSE;
	}
	else {

	    Status = CreateProcess (
                           NULL,
                           (LPTSTR)pCommand32,
                           NULL,
                           NULL,
                           TRUE,
                           CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
			   Env_A.Buffer,
                           (LPTSTR)CurDir,
                           &StartupInfo,
			   &ProcessInformation);
	}
    }

    if (Status == FALSE)
        dwExitCode32 = GetLastError ();

    if (hStd16In != (HANDLE)-1)
        SetStdHandle (STD_INPUT_HANDLE, SCS_hStdIn);

    if (hStd16Out != (HANDLE)-1)
        SetStdHandle (STD_OUTPUT_HANDLE, SCS_hStdOut);

    if (hStd16Err != (HANDLE)-1)
        SetStdHandle (STD_ERROR_HANDLE, SCS_hStdErr);

    if (Status) {
	ResumeThread (ProcessInformation.hThread);
        WaitForSingleObject(ProcessInformation.hProcess, (DWORD)-1);
        GetExitCodeProcess (ProcessInformation.hProcess, &dwExitCode32);
        CloseHandle (ProcessInformation.hProcess);
        CloseHandle (ProcessInformation.hThread);
    }

    if (Env_A.Buffer)
	RtlFreeAnsiString(&Env_A);

    // Decrement the Re-enterancy count for the VDM
    VDMInfoForCount.VDMState = DECREMENT_REENTER_COUNT;
    GetNextVDMCommand (&VDMInfoForCount);

    // one less 32 executable active
    Exe32ActiveCount--;

    // Kill this thread
    ExitThread (0);
}
Пример #7
0
VOID cmdCheckBinary (VOID)
{

    LPSTR  lpAppName;
    ULONG  BinaryType;
    PPARAMBLOCK lpParamBlock;
    PCHAR  lpCommandTail,lpTemp;
    ULONG  AppNameLen,CommandTailLen = 0;
    USHORT CommandTailOff,CommandTailSeg,usTemp;
    NTSTATUS       Status;
    UNICODE_STRING Unicode;
    OEM_STRING     OemString;
    ANSI_STRING    AnsiString;


    if(DontCheckDosBinaryType){
        setCF(0);
        return;         // DOS Exe
    }

    lpAppName = (LPSTR) GetVDMAddr (getDS(),getDX());

    Unicode.Buffer = NULL;
    AnsiString.Buffer = NULL;
    RtlInitString((PSTRING)&OemString, lpAppName);
    Status = RtlOemStringToUnicodeString(&Unicode,&OemString,TRUE);
    if ( NT_SUCCESS(Status) ) {
        Status = RtlUnicodeStringToAnsiString(&AnsiString, &Unicode, TRUE);
        }
    if ( !NT_SUCCESS(Status) ) {
        Status = RtlNtStatusToDosError(Status);
        }
    else if (GetBinaryType (AnsiString.Buffer,(LPLONG)&BinaryType) == FALSE)
       {
        Status =  GetLastError();
        }

    if (Unicode.Buffer != NULL) {
        RtlFreeUnicodeString( &Unicode );
        }
    if (AnsiString.Buffer != NULL) {
        RtlFreeAnsiString( &AnsiString);
        }

    if (Status){
        setCF(1);
        setAX((USHORT)Status);
        return;         // Invalid path
    }


    if (BinaryType == SCS_DOS_BINARY) {
        setCF(0);
        return;         // DOS Exe
    }
                        // Prevent certain WOW apps from being spawned by DOS exe's
                        // This is for win31 compatibility
    else if (BinaryType == SCS_WOW_BINARY) {
        if (!IsWowAppRunnable(lpAppName)) {
            setCF(0);
            return;     // Run as DOS Exe
        }
    }


    if (VDMForWOW && BinaryType == SCS_WOW_BINARY && IsFirstWOWCheckBinary) {
        IsFirstWOWCheckBinary = FALSE;
        setCF(0);
        return;         // Special Hack for krnl286.exe
    }

    // dont allow running 32bit binaries from autoexec.nt. Reason is that
    // running non-dos binary requires that we should have read the actual
    // command from GetNextVDMCommand. Otherwise the whole design gets into
    // synchronization problems.

    if (IsFirstCall) {
        setCF(1);
        setAX((USHORT)ERROR_FILE_NOT_FOUND);
        return;
    }

    // Its a 32bit exe, replace the command with "command.com /z" and add the
    // original binary name to command tail.

    AppNameLen = strlen (lpAppName);

    lpParamBlock = (PPARAMBLOCK) GetVDMAddr (getES(),getBX());

    if (lpParamBlock) {
        CommandTailOff = FETCHWORD(lpParamBlock->OffCmdTail);
        CommandTailSeg = FETCHWORD(lpParamBlock->SegCmdTail);

        lpCommandTail = (PCHAR) GetVDMAddr (CommandTailSeg,CommandTailOff);

        if (lpCommandTail){
            CommandTailLen = *(PCHAR)lpCommandTail;
            lpCommandTail++;        // point to the actual command tail
            if (CommandTailLen)
                CommandTailLen++;   // For CR
        }

        // We are adding 3 below for "/z<space>" and anothre space between
        // AppName and CommandTail.

        if ((3 + AppNameLen + CommandTailLen ) > 128){
            setCF(1);
            setAX((USHORT)ERROR_NOT_ENOUGH_MEMORY);
            return;
        }
    }

    // copy the stub command.com name
    strcpy ((PCHAR)&pSCSInfo->SCS_ComSpec,lpszComSpec+8);
    lpTemp = (PCHAR) &pSCSInfo->SCS_ComSpec;
    lpTemp = (PCHAR)((ULONG)lpTemp - (ULONG)GetVDMAddr(0,0));
    usTemp = (USHORT)((ULONG)lpTemp >> 4);
    setDS(usTemp);
    usTemp = (USHORT)((ULONG)lpTemp & 0x0f);
    setDX((usTemp));

    // Form the command tail, first "3" is for "/z "
    pSCSInfo->SCS_CmdTail [0] = (UCHAR)(3 +
                                        AppNameLen +
                                        CommandTailLen);
    RtlCopyMemory ((PCHAR)&pSCSInfo->SCS_CmdTail[1],"/z ",3);
    strcpy ((PCHAR)&pSCSInfo->SCS_CmdTail[4],lpAppName);
    if (CommandTailLen) {
        pSCSInfo->SCS_CmdTail[4+AppNameLen] = ' ';
        RtlCopyMemory ((PCHAR)((ULONG)&pSCSInfo->SCS_CmdTail[4]+AppNameLen+1),
                lpCommandTail,
                CommandTailLen);
    }
    else {
        pSCSInfo->SCS_CmdTail[4+AppNameLen] = 0xd;
    }

    // Set the parameter Block
    if (lpParamBlock) {
        STOREWORD(pSCSInfo->SCS_ParamBlock.SegEnv,lpParamBlock->SegEnv);
        STOREDWORD(pSCSInfo->SCS_ParamBlock.pFCB1,lpParamBlock->pFCB1);
        STOREDWORD(pSCSInfo->SCS_ParamBlock.pFCB2,lpParamBlock->pFCB2);
    }
    else {
        STOREWORD(pSCSInfo->SCS_ParamBlock.SegEnv,0);
        STOREDWORD(pSCSInfo->SCS_ParamBlock.pFCB1,0);
        STOREDWORD(pSCSInfo->SCS_ParamBlock.pFCB2,0);
    }

    lpTemp = (PCHAR) &pSCSInfo->SCS_CmdTail;
    lpTemp = (PCHAR)((ULONG)lpTemp - (ULONG)GetVDMAddr(0,0));
    usTemp = (USHORT)((ULONG)lpTemp & 0x0f);
    STOREWORD(pSCSInfo->SCS_ParamBlock.OffCmdTail,usTemp);
    usTemp = (USHORT)((ULONG)lpTemp >> 4);
    STOREWORD(pSCSInfo->SCS_ParamBlock.SegCmdTail,usTemp);

    lpTemp = (PCHAR) &pSCSInfo->SCS_ParamBlock;
    lpTemp = (PCHAR)((ULONG)lpTemp - (ULONG)GetVDMAddr(0,0));
    usTemp = (USHORT)((ULONG)lpTemp >> 4);
    setES (usTemp);
    usTemp = (USHORT)((ULONG)lpTemp & 0x0f);
    setBX (usTemp);

    setCF(0);
    return;
}
Пример #8
0
INT_PTR CALLBACK NetworkOutputDlgProc(
    __in HWND hwndDlg,
    __in UINT uMsg,
    __in WPARAM wParam,
    __in LPARAM lParam
    )
{
    PNETWORK_OUTPUT_CONTEXT context;

    if (uMsg == WM_INITDIALOG)
    {
        context = (PNETWORK_OUTPUT_CONTEXT)lParam;
        SetProp(hwndDlg, L"Context", (HANDLE)context);
    }
    else
    {
        context = (PNETWORK_OUTPUT_CONTEXT)GetProp(hwndDlg, L"Context");

        if (uMsg == WM_DESTROY)
            RemoveProp(hwndDlg, L"Context");
    }

    if (!context)
        return FALSE;

    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            WCHAR addressString[65];
            HANDLE pipeWriteHandle;

            PhCenterWindow(hwndDlg, GetParent(hwndDlg));
            context->WindowHandle = hwndDlg;

            PhInitializeLayoutManager(&context->LayoutManager, hwndDlg);

            PhAddLayoutItem(&context->LayoutManager, GetDlgItem(hwndDlg, IDC_TEXT), NULL, PH_ANCHOR_ALL);
            PhAddLayoutItem(&context->LayoutManager, GetDlgItem(hwndDlg, IDOK), NULL, PH_ANCHOR_BOTTOM | PH_ANCHOR_RIGHT);

            if (context->Address.Type == PH_IPV4_NETWORK_TYPE)
                RtlIpv4AddressToString(&context->Address.InAddr, addressString);
            else
                RtlIpv6AddressToString(&context->Address.In6Addr, addressString);

            switch (context->Action)
            {
            case NETWORK_ACTION_PING:
            case NETWORK_ACTION_TRACEROUTE:
                if (context->Action == NETWORK_ACTION_PING)
                {
                    SetWindowText(hwndDlg,
                        PhaFormatString(L"Pinging %s...", addressString)->Buffer);
                }
                else
                {
                    SetWindowText(hwndDlg,
                        PhaFormatString(L"Tracing route to %s...", addressString)->Buffer);
                }

                // Doing this properly would be too complex, so we'll just
                // execute ping.exe/traceroute.exe and display its output.

                if (CreatePipe(&context->PipeReadHandle, &pipeWriteHandle, NULL, 0))
                {
                    STARTUPINFO startupInfo = { sizeof(startupInfo) };
                    PPH_STRING command;
                    OBJECT_HANDLE_FLAG_INFORMATION flagInfo;

                    startupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
                    startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
                    startupInfo.hStdOutput = pipeWriteHandle;
                    startupInfo.hStdError = pipeWriteHandle;
                    startupInfo.wShowWindow = SW_HIDE;

                    if (context->Action == NETWORK_ACTION_PING)
                    {
                        command = PhaFormatString(
                            L"%s\\system32\\ping.exe %s",
                            USER_SHARED_DATA->NtSystemRoot,
                            addressString
                            );
                    }
                    else
                    {
                        command = PhaFormatString(
                            L"%s\\system32\\tracert.exe %s",
                            USER_SHARED_DATA->NtSystemRoot,
                            addressString
                            );
                    }

                    // Allow the write handle to be inherited.

                    flagInfo.Inherit = TRUE;
                    flagInfo.ProtectFromClose = FALSE;

                    NtSetInformationObject(
                        pipeWriteHandle,
                        ObjectHandleFlagInformation,
                        &flagInfo,
                        sizeof(OBJECT_HANDLE_FLAG_INFORMATION)
                        );

                    PhCreateProcessWin32Ex(
                        NULL,
                        command->Buffer,
                        NULL,
                        NULL,
                        &startupInfo,
                        PH_CREATE_PROCESS_INHERIT_HANDLES,
                        NULL,
                        NULL,
                        &context->ProcessHandle,
                        NULL
                        );

                    // Essential; when the process exits, the last instance of the pipe
                    // will be disconnected and our thread will exit.
                    NtClose(pipeWriteHandle);

                    // Create a thread which will wait for output and display it.
                    context->ThreadHandle = PhCreateThread(0, NetworkWorkerThreadStart, context);
                }

                break;
            }
        }
        break;
    case WM_DESTROY:
        {
            PhAcquireQueuedLockExclusive(&context->WindowHandleLock);
            context->WindowHandle = NULL;
            PhReleaseQueuedLockExclusive(&context->WindowHandleLock);

            if (context->ProcessHandle)
            {
                NtTerminateProcess(context->ProcessHandle, STATUS_SUCCESS);
                NtClose(context->ProcessHandle);
            }
        }
        break;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDCANCEL:
            case IDOK:
                EndDialog(hwndDlg, IDOK);
                break;
            }
        }
        break;
    case WM_SIZE:
        PhLayoutManagerLayout(&context->LayoutManager);
        break;
    case NTM_DONE:
        {
            PPH_STRING windowText = PhGetWindowText(hwndDlg);

            if (windowText)
            {
                SetWindowText(hwndDlg, PhaFormatString(L"%s Finished.", windowText->Buffer)->Buffer);

                PhDereferenceObject(windowText);
            }
        }
        break;
    case NTM_RECEIVED:
        {
            OEM_STRING inputString;
            UNICODE_STRING convertedString;

            if (wParam != 0)
            {
                inputString.Buffer = (PCHAR)lParam;
                inputString.Length = (USHORT)wParam;

                if (NT_SUCCESS(RtlOemStringToUnicodeString(&convertedString, &inputString, TRUE)))
                {
                    PhAppendStringBuilderEx(&context->ReceivedString, convertedString.Buffer, convertedString.Length);
                    RtlFreeUnicodeString(&convertedString);

                    // Remove leading newlines.
                    if (
                        context->ReceivedString.String->Length >= 2 * 2 &&
                        context->ReceivedString.String->Buffer[0] == '\r' && context->ReceivedString.String->Buffer[1] == '\n'
                        )
                    {
                        PhRemoveStringBuilder(&context->ReceivedString, 0, 2);
                    }

                    SetDlgItemText(hwndDlg, IDC_TEXT, context->ReceivedString.String->Buffer);
                    SendMessage(
                        GetDlgItem(hwndDlg, IDC_TEXT),
                        EM_SETSEL,
                        context->ReceivedString.String->Length / 2 - 1,
                        context->ReceivedString.String->Length / 2 - 1
                        );
                    SendMessage(GetDlgItem(hwndDlg, IDC_TEXT), WM_VSCROLL, SB_BOTTOM, 0);
                }
            }
        }
        break;
    }

    return FALSE;
}
Пример #9
0
NET_API_STATUS
NetpRdrFsControlTree(
    IN LPTSTR TreeName,
    IN LPTSTR TransportName OPTIONAL,
    IN DWORD ConnectionType,
    IN DWORD FsControlCode,
    IN LPVOID SecurityDescriptor OPTIONAL,
    IN LPVOID InputBuffer OPTIONAL,
    IN DWORD InputBufferSize,
    OUT LPVOID OutputBuffer OPTIONAL,
    IN DWORD OutputBufferSize,
    IN BOOL NoPermissionRequired
    )

/*++

Routine Description:

    NetpRdrFsControlTree performs a given FSCTL (file system control)
    on a given tree connection name.

Arguments:

    TreeName - Remote name to do fsctl to (in \\server\share format).

    FsControlCode - function code to pass to the redirector.  These are
        defined in <ntddnfs.h>.

    SecurityDescriptor - optionally points to a security descriptor to be
        used when creating the tree connection.

    InputBuffer - optionally points to a structure to be passed to the
        redirector.

    InputBufferSize - size of InputBuffer in bytes; must be zero if
        InputBuffer is a NULL pointer.

    OutputBuffer - optionally points to a structure to be filled in by the
        redirector.

    OutputBufferSize - size of OutputBuffer in bytes; must be zero if
        OutputBuffer is a NULL pointer.

    NoPermissionRequired - TRUE if this is a no permission required API.  (I.e.
        TRUE if the null session may be used.)

Return Value:

    NET_API_STATUS

--*/

{
    NET_API_STATUS ApiStatus;
    IO_STATUS_BLOCK iosb;
    NTSTATUS ntstatus;                      // Status from NT operations.
    OBJECT_ATTRIBUTES objattrTreeConn;      // Attrs for tree conn.
    LPTSTR pszTreeConn;                      // See strTreeConn below.
#ifndef UNICODE
    STRING strTreeConn;                     // \Device\LanManRedir\server\share
#endif
    UNICODE_STRING ucTreeConn;
    HANDLE TreeConnHandle;

    PFILE_FULL_EA_INFORMATION EaBuffer = NULL;
    PFILE_FULL_EA_INFORMATION Ea;
    USHORT TransportNameSize = 0;
    ULONG EaBufferSize = 0;
    PWSTR UnicodeTransportName = NULL;

    UCHAR EaNameDomainNameSize = (UCHAR) (ROUND_UP_COUNT(
                                             strlen(EA_NAME_DOMAIN) + sizeof(CHAR),
                                             ALIGN_WCHAR
                                             ) - sizeof(CHAR));

    UCHAR EaNamePasswordSize = (UCHAR) (ROUND_UP_COUNT(
                                             strlen(EA_NAME_PASSWORD) + sizeof(CHAR),
                                             ALIGN_WCHAR
                                             ) - sizeof(CHAR));

    UCHAR EaNameTransportNameSize = (UCHAR) (ROUND_UP_COUNT(
                                             strlen(EA_NAME_TRANSPORT) + sizeof(CHAR),
                                             ALIGN_WCHAR
                                             ) - sizeof(CHAR));

    UCHAR EaNameTypeSize = (UCHAR) (ROUND_UP_COUNT(
                                        strlen(EA_NAME_TYPE) + sizeof(CHAR),
                                        ALIGN_DWORD
                                        ) - sizeof(CHAR));

    UCHAR EaNameUserNameSize = (UCHAR) (ROUND_UP_COUNT(
                                             strlen(EA_NAME_USERNAME) + sizeof(CHAR),
                                             ALIGN_WCHAR
                                             ) - sizeof(CHAR));

    USHORT TypeSize = sizeof(ULONG);




    IF_DEBUG(RDRFSCTL) {
        NetpKdPrint(( PREFIX_NETLIB
                "NetpRdrFsControlTree: entered, TreeName='"
                FORMAT_LPTSTR "', " FORMAT_LPTSTR " session.\n",
                TreeName,
                NoPermissionRequired ? TEXT("null") : TEXT("non-null") ));
    }

    if ((TreeName == NULL) || (TreeName[0] == 0)) {
        return (ERROR_INVALID_PARAMETER);
    }

    if (! NetpIsRemoteNameValid(TreeName)) {
        return (ERROR_INVALID_PARAMETER);
    }

    //
    // Build NT-style name for what we're connecting to.  Note that there is
    // NOT a pair of backslashes anywhere in this name.
    //

    {
        DWORD NameSize =

            // /Device/LanManRedirector      /    server/share     \0
#ifdef UNICODE
            ( ( STRLEN((LPTSTR)DD_NFS_DEVICE_NAME_U) + 1 + STRLEN(TreeName) + 1 ) )
#else
            ( ( STRLEN((LPTSTR)DD_NFS_DEVICE_NAME) + 1 + STRLEN(TreeName) + 1 ) )
#endif
            * sizeof(TCHAR);

        pszTreeConn = (LPTSTR)NetpMemoryAllocate( NameSize );
    }

    if (pszTreeConn == NULL) {
        return (ERROR_NOT_ENOUGH_MEMORY);
    }

    //
    // Build the tree connect name.
    //

#ifdef UNICODE
    (void) STRCPY(pszTreeConn, (LPTSTR) DD_NFS_DEVICE_NAME_U);
#else
    (void) STRCPY(pszTreeConn, (LPTSTR) DD_NFS_DEVICE_NAME);
#endif

    //
    // NOTE: We add 1, (not sizeof(TCHAR)) because pointer arithmetic is done
    // in terms of multiples of sizeof(*pointer), not bytes
    //

    (void) STRCAT(pszTreeConn, TreeName+1); // \server\share

#ifdef UNICODE
    RtlInitUnicodeString(&ucTreeConn, pszTreeConn);
#else
    RtlInitString( & strTreeConn, pszTreeConn);
    (void) RtlOemStringToUnicodeString(&ucTreeConn, &strTreeConn, TRUE);
#endif

    IF_DEBUG(RDRFSCTL) {
        NetpKdPrint(( PREFIX_NETLIB
                "NetpRdrFsControlTree: UNICODE name is " FORMAT_LPWSTR
                ".\n", ucTreeConn.Buffer ));
    }



    //
    // Calculate the number of bytes needed for the EA buffer.
    // This may have the transport name.  For regular sessions, the user
    // name, password, and domain name are implicit.  For null sessions, we
    // must give 0-len user name, 0-len password, and 0-len domain name.
    //

    if (ARGUMENT_PRESENT(TransportName)) {
        ASSERT(ConnectionType == USE_IPC);

#ifdef UNICODE
        UnicodeTransportName = TransportName;
#else
        UnicodeTransportName = NetpAllocWStrFromStr(TransportName);

        if (UnicodeTransportName == NULL) {

            NetpMemoryFree(pszTreeConn);

            return ERROR_NOT_ENOUGH_MEMORY;
        }
#endif
        TransportNameSize = (USHORT) (wcslen(UnicodeTransportName) * sizeof(WCHAR));

        EaBufferSize += ROUND_UP_COUNT(
                            FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                            EaNameTransportNameSize + sizeof(CHAR) +
                            TransportNameSize,
                            ALIGN_DWORD
                            );
    }

    if (NoPermissionRequired) {

        // Domain name (0-len).
        EaBufferSize += ROUND_UP_COUNT(
                            FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                            EaNameDomainNameSize + sizeof(CHAR),
                            ALIGN_DWORD
                            );

        // Password (0-len).
        EaBufferSize += ROUND_UP_COUNT(
                            FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                            EaNamePasswordSize + sizeof(CHAR),
                            ALIGN_DWORD
                            );

        // User name (0-len).
        EaBufferSize += ROUND_UP_COUNT(
                            FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                            EaNameUserNameSize + sizeof(CHAR),
                            ALIGN_DWORD
                            );
    }

    EaBufferSize += ((ULONG)FIELD_OFFSET( FILE_FULL_EA_INFORMATION, EaName[0]))+
                    EaNameTypeSize + sizeof(CHAR) +
                    TypeSize;


    //
    // Allocate the EA buffer
    //

    if ((EaBuffer = NetpMemoryAllocate( EaBufferSize )) == NULL) {

        NetpMemoryFree(pszTreeConn);

#ifndef UNICODE
        if (UnicodeTransportName != NULL) {
            NetpMemoryFree(UnicodeTransportName);
        }
#endif

        return ERROR_NOT_ENOUGH_MEMORY;
    }

    //
    // Fill-in the EA buffer.
    //

    RtlZeroMemory(EaBuffer, EaBufferSize);

    Ea = EaBuffer;

    if (ARGUMENT_PRESENT(TransportName)) {

        //
        // Copy the EA name into EA buffer.  EA name length does not
        // include the zero terminator.
        //
        strcpy(Ea->EaName, EA_NAME_TRANSPORT);
        Ea->EaNameLength = EaNameTransportNameSize;

        //
        // Copy the EA value into EA buffer.  EA value length does not
        // include the zero terminator.
        //
        (VOID) wcscpy(
            (LPWSTR) &(Ea->EaName[EaNameTransportNameSize + sizeof(CHAR)]),
            UnicodeTransportName
            );

        Ea->EaValueLength = TransportNameSize;

        Ea->NextEntryOffset = ROUND_UP_COUNT(
                                  FIELD_OFFSET( FILE_FULL_EA_INFORMATION, EaName[0]) +
                                  EaNameTransportNameSize + sizeof(CHAR) +
                                  TransportNameSize,
                                  ALIGN_DWORD
                                  );
        Ea->Flags = 0;

        (ULONG) Ea += Ea->NextEntryOffset;
    }

    if (NoPermissionRequired) {

        //
        // *** DOMAIN NAME ***
        // Copy the EA name into EA buffer.  EA name length does not
        // include the zero terminator.
        //
        (VOID) strcpy(Ea->EaName, EA_NAME_DOMAIN);
        Ea->EaNameLength = EaNameDomainNameSize;

        Ea->EaValueLength = 0;  // There is no EA value for this.

        Ea->NextEntryOffset = ROUND_UP_COUNT(
                                  FIELD_OFFSET( FILE_FULL_EA_INFORMATION, EaName[0]) +
                                  EaNameDomainNameSize + sizeof(CHAR),
                                  ALIGN_DWORD
                                  );
        Ea->Flags = 0;

        (ULONG) Ea += Ea->NextEntryOffset;

        //
        // *** PASSWORD ***
        // Copy the EA name into EA buffer.  EA name length does not
        // include the zero terminator.
        //
        (VOID) strcpy(Ea->EaName, EA_NAME_PASSWORD);
        Ea->EaNameLength = EaNamePasswordSize;

        Ea->EaValueLength = 0;  // There is no EA value for this.

        Ea->NextEntryOffset = ROUND_UP_COUNT(
                                  FIELD_OFFSET( FILE_FULL_EA_INFORMATION, EaName[0]) +
                                  EaNamePasswordSize + sizeof(CHAR),
                                  ALIGN_DWORD
                                  );
        Ea->Flags = 0;

        (ULONG) Ea += Ea->NextEntryOffset;

        //
        // *** USER NAME ***
        // Copy the EA name into EA buffer.  EA name length does not
        // include the zero terminator.
        //
        (VOID) strcpy(Ea->EaName, EA_NAME_USERNAME);
        Ea->EaNameLength = EaNameUserNameSize;

        Ea->EaValueLength = 0;  // There is no EA value for this.

        Ea->NextEntryOffset = ROUND_UP_COUNT(
                                  FIELD_OFFSET( FILE_FULL_EA_INFORMATION, EaName[0]) +
                                  EaNameUserNameSize + sizeof(CHAR),
                                  ALIGN_DWORD
                                  );
        Ea->Flags = 0;

        (ULONG) Ea += Ea->NextEntryOffset;
    }

    //
    // Copy the EA for the connection type name into EA buffer.  EA name length
    // does not include the zero terminator.
    //
    strcpy(Ea->EaName, EA_NAME_TYPE);
    Ea->EaNameLength = EaNameTypeSize;

    *((PULONG) &(Ea->EaName[EaNameTypeSize + sizeof(CHAR)])) = ConnectionType;

    Ea->EaValueLength = TypeSize;

    Ea->NextEntryOffset = 0;
    Ea->Flags = 0;

    // Set object attributes for the tree conn.
    InitializeObjectAttributes(
                & objattrTreeConn,                       // obj attr to init
                (LPVOID) & ucTreeConn,                   // string to use
                OBJ_CASE_INSENSITIVE,                    // Attributes
                NULL,                                    // Root directory
                SecurityDescriptor);                     // Security Descriptor

    //
    // Open a tree connection to the remote server.
    //

    IF_DEBUG(RDRFSCTL) {
        NetpKdPrint(( PREFIX_NETLIB
                "NetpRdrFsControlTree: opening " FORMAT_LPTSTR ".\n",
                pszTreeConn ));
    }
    ntstatus = NtCreateFile(
                & TreeConnHandle,                        // ptr to handle
                SYNCHRONIZE                              // desired...
                | GENERIC_READ | GENERIC_WRITE,          // ...access
                & objattrTreeConn,                       // name & attributes
                & iosb,                                  // I/O status block.
                NULL,                                    // alloc size.
                FILE_ATTRIBUTE_NORMAL,                   // (ignored)
                FILE_SHARE_READ | FILE_SHARE_WRITE,      // ...access
                FILE_OPEN_IF,                            // create disposition
                FILE_CREATE_TREE_CONNECTION              // create...
                | FILE_SYNCHRONOUS_IO_NONALERT,          // ...options
                EaBuffer,                                // EA buffer
                EaBufferSize );                          // Ea buffer size

#ifndef UNICODE
    RtlFreeUnicodeString( &ucTreeConn );
#endif

    if (! NT_SUCCESS(ntstatus)) {

#ifndef UNICODE
        if (UnicodeTransportName != NULL) {
            NetpMemoryFree(UnicodeTransportName);

        }
#endif

        if (EaBuffer != NULL) {
            NetpMemoryFree(EaBuffer);
        }

        NetpMemoryFree(pszTreeConn);
        ApiStatus = NetpNtStatusToApiStatus(ntstatus);
        if (ApiStatus == ERROR_BAD_NET_NAME) {
            ApiStatus = NERR_BadTransactConfig;  // Special meaning if no IPC$
        }

        if (ApiStatus != ERROR_BAD_NETPATH) {
            NetpKdPrint(( PREFIX_NETLIB
                    "NetpRdrFsControlTree: unexpected create error,\n"
                    "  tree name='" FORMAT_LPTSTR "', "
                    "ntstatus=" FORMAT_NTSTATUS ",\n"
                    "  iosb.Status=" FORMAT_NTSTATUS ", "
                    "iosb.Info=" FORMAT_HEX_ULONG ", "
                    "  returning " FORMAT_API_STATUS ".\n",
                    TreeName, ntstatus,
                    iosb.Status, iosb.Information, ApiStatus ));
        }

        return (ApiStatus);
    }

    // Do the FSCTL.
    IF_DEBUG(RDRFSCTL) {
        NetpKdPrint(( PREFIX_NETLIB
                "NetpRdrFsControlTree: doing fsctl...\n" ));
    }
    ntstatus = NtFsControlFile(
                        TreeConnHandle,                  // handle
                        NULL,                            // no event
                        NULL,                            // no APC routine
                        NULL,                            // no APC context
                        & iosb,                          // I/O stat blk (set)
                        FsControlCode,                   // func code
                        InputBuffer,
                        InputBufferSize,
                        OutputBuffer,
                        OutputBufferSize);

    if (! NT_SUCCESS(ntstatus)) {
       NTSTATUS Status;

       Status = NtClose(TreeConnHandle);
#if DBG
       if (!NT_SUCCESS(Status)) {
           NetpKdPrint(( PREFIX_NETLIB
                   "NetpRdrFsControlTree: "
                   "Unexpected error closing tree connect handle: "
                   FORMAT_NTSTATUS "\n",
                   Status ));
       }
#endif

       NetpMemoryFree(pszTreeConn);

#ifndef UNICODE
        if (UnicodeTransportName != NULL) {
            NetpMemoryFree(UnicodeTransportName);

        }
#endif

        if (EaBuffer != NULL) {
            NetpMemoryFree(EaBuffer);
        }
        ApiStatus = NetpNtStatusToApiStatus(ntstatus);

        NetpKdPrint(( PREFIX_NETLIB
                "NetpRdrFsControlTree: unexpected FSCTL error,\n"
                "  tree name='" FORMAT_LPTSTR "', "
                "ntstatus=" FORMAT_NTSTATUS ".\n"
                "  ApiStatus=" FORMAT_API_STATUS ", "
                "iosb.Status=" FORMAT_NTSTATUS ", "
                "iosb.Info=" FORMAT_HEX_ULONG ".\n",
                TreeName, ntstatus, ApiStatus, iosb.Status, iosb.Information ));

        return (ApiStatus);
    }

    // Clean up.
    ntstatus = NtClose(TreeConnHandle);
#if DBG
       if (!NT_SUCCESS(ntstatus)) {
           NetpKdPrint(( PREFIX_NETLIB
                   "NetpRdrFsControlTree: "
                   "Unexpected error closing tree connect handle: "
                   FORMAT_NTSTATUS "\n", ntstatus ));
       }
#endif

    NetpMemoryFree(pszTreeConn);

#ifndef UNICODE
    if (UnicodeTransportName != NULL) {
        NetpMemoryFree(UnicodeTransportName);

    }
#endif

    if (EaBuffer != NULL) {
        NetpMemoryFree(EaBuffer);
    }

    return (NERR_Success);

} // NetpRdrFsControlTree
Пример #10
0
VOID
NTAPI
FatSetFcbNames(IN PFAT_IRP_CONTEXT IrpContext,
               IN PFCB Fcb)
{
    FF_DIRENT DirEnt;
    FF_ERROR Err;
    POEM_STRING ShortName;
    CHAR ShortNameRaw[13];
    UCHAR EntryBuffer[32];
    UCHAR NumLFNs;
    PUNICODE_STRING UnicodeName;
    OEM_STRING LongNameOem;
    NTSTATUS Status;

    /* Get the dir entry */
    Err = FF_GetEntry(Fcb->Vcb->Ioman,
                      Fcb->FatHandle->DirEntry,
                      Fcb->FatHandle->DirCluster,
                      &DirEnt);

    if (Err != FF_ERR_NONE)
    {
        DPRINT1("Error %d getting dirent of a file\n", Err);
        return;
    }

    /* Read the dirent to fetch the raw short name */
    FF_FetchEntry(Fcb->Vcb->Ioman,
                  Fcb->FatHandle->DirCluster,
                  Fcb->FatHandle->DirEntry,
                  EntryBuffer);
    NumLFNs = (UCHAR)(EntryBuffer[0] & ~0x40);
    RtlCopyMemory(ShortNameRaw, EntryBuffer, 11);

    /* Initialize short name string */
    ShortName = &Fcb->ShortName.Name.Ansi;
    ShortName->Buffer = Fcb->ShortNameBuffer;
    ShortName->Length = 0;
    ShortName->MaximumLength = sizeof(Fcb->ShortNameBuffer);

    /* Convert raw short name to a proper string */
    Fati8dot3ToString(ShortNameRaw, FALSE, ShortName);

    /* Add the short name link */
    FatInsertName(IrpContext, &Fcb->ParentFcb->Dcb.SplayLinksAnsi, &Fcb->ShortName);
    Fcb->ShortName.Fcb = Fcb;

    /* Get the long file name (if any) */
    if (NumLFNs > 0)
    {
        /* Prepare the oem string */
        LongNameOem.Buffer = DirEnt.FileName;
        LongNameOem.MaximumLength = FF_MAX_FILENAME;
        LongNameOem.Length = strlen(DirEnt.FileName);

        /* Prepare the unicode string */
        UnicodeName = &Fcb->LongName.Name.String;
        UnicodeName->Length = (LongNameOem.Length + 1) * sizeof(WCHAR);
        UnicodeName->MaximumLength = UnicodeName->Length;
        UnicodeName->Buffer = FsRtlAllocatePool(PagedPool, UnicodeName->Length);

        /* Convert it to unicode */
        Status = RtlOemStringToUnicodeString(UnicodeName, &LongNameOem, FALSE);
        if (!NT_SUCCESS(Status))
        {
            ASSERT(FALSE);
        }

        /* Set its length */
        Fcb->FileNameLength = UnicodeName->Length;

        /* Save case-preserved copy */
        Fcb->ExactCaseLongName.Length = UnicodeName->Length;
        Fcb->ExactCaseLongName.MaximumLength = UnicodeName->Length;
        Fcb->ExactCaseLongName.Buffer =
            FsRtlAllocatePoolWithTag(PagedPool, UnicodeName->Length, TAG_FILENAME);

        RtlCopyMemory(Fcb->ExactCaseLongName.Buffer,
                      UnicodeName->Buffer,
                      UnicodeName->Length);

        /* Perform a trick which is done by MS's FASTFAT driver to monocase
           the filename */
        RtlDowncaseUnicodeString(UnicodeName, UnicodeName, FALSE);
        RtlUpcaseUnicodeString(UnicodeName, UnicodeName, FALSE);

        DPRINT("Converted long name: %wZ\n", UnicodeName);

        /* Add the long unicode name link */
        FatInsertName(IrpContext, &Fcb->ParentFcb->Dcb.SplayLinksUnicode, &Fcb->LongName);
        Fcb->LongName.Fcb = Fcb;

        /* Indicate that this FCB has a unicode long name */
        SetFlag(Fcb->State, FCB_STATE_HAS_UNICODE_NAME);
    }
    else
    {
        /* No LFN, set exact case name to 0 length */
        Fcb->ExactCaseLongName.Length = 0;
        Fcb->ExactCaseLongName.MaximumLength = 0;

        /* Set the length based on the short name */
        Fcb->FileNameLength = RtlOemStringToCountedUnicodeSize(ShortName);
    }

    /* Mark the fact that names were added to splay trees*/
    SetFlag(Fcb->State, FCB_STATE_HAS_NAMES);
}
Пример #11
0
VOID
NTAPI
FatGetFcbUnicodeName(IN PFAT_IRP_CONTEXT IrpContext,
                     IN PFCB Fcb,
                     OUT PUNICODE_STRING LongName)
{
    FF_DIRENT DirEnt;
    FF_ERROR Err;
    OEM_STRING ShortName;
    CHAR ShortNameBuf[13];
    UCHAR EntryBuffer[32];
    UCHAR NumLFNs;
    OEM_STRING LongNameOem;
    NTSTATUS Status;

    /* Make sure this FCB has a FullFAT handle associated with it */
    if (Fcb->FatHandle == NULL &&
        FatNodeType(Fcb) == FAT_NTC_DCB)
    {
        /* Open the dir with FullFAT */
        Fcb->FatHandle = FF_OpenW(Fcb->Vcb->Ioman, &Fcb->FullFileName, FF_MODE_DIR, NULL);
        if (!Fcb->FatHandle)
        {
            ASSERT(FALSE);
        }
    }

    /* Get the dir entry */
    Err = FF_GetEntry(Fcb->Vcb->Ioman,
                      Fcb->FatHandle->DirEntry,
                      Fcb->FatHandle->DirCluster,
                      &DirEnt);

    if (Err != FF_ERR_NONE)
    {
        DPRINT1("Error %d getting dirent of a file\n", Err);
        return;
    }

    /* Read the dirent to fetch the raw short name */
    FF_FetchEntry(Fcb->Vcb->Ioman,
                  Fcb->FatHandle->DirCluster,
                  Fcb->FatHandle->DirEntry,
                  EntryBuffer);
    NumLFNs = (UCHAR)(EntryBuffer[0] & ~0x40);

    /* Check if we only have a short name.
       Convert it to unicode and return if that's the case */
    if (NumLFNs == 0)
    {
        /* Initialize short name string */
        ShortName.Buffer = ShortNameBuf;
        ShortName.Length = 0;
        ShortName.MaximumLength = 12;

        /* Convert raw short name to a proper string */
        Fati8dot3ToString((PCHAR)EntryBuffer, FALSE, &ShortName);

        /* Convert it to unicode */
        Status = RtlOemStringToCountedUnicodeString(LongName,
                                                    &ShortName,
                                                    FALSE);

        /* Ensure conversion was successful */
        ASSERT(Status == STATUS_SUCCESS);

        /* Exit */
        return;
    }

    /* Convert LFN from OEM to unicode and return */
    LongNameOem.Buffer = DirEnt.FileName;
    LongNameOem.MaximumLength = FF_MAX_FILENAME;
    LongNameOem.Length = strlen(DirEnt.FileName);

    /* Convert it to unicode */
    Status = RtlOemStringToUnicodeString(LongName, &LongNameOem, FALSE);

    /* Ensure conversion was successful */
    ASSERT(Status == STATUS_SUCCESS);
}
Пример #12
0
NET_API_STATUS
FileEnumCommon (
    IN LPTSTR BasePath,
    IN LPTSTR UserName,
    IN DWORD Level,
    OUT LPBYTE *Buffer,
    IN DWORD PreferredMaximumLength,
    OUT LPDWORD EntriesRead,
    OUT LPDWORD TotalEntries,
    IN OUT LPDWORD ResumeHandle OPTIONAL,
    IN BOOLEAN IsGetInfo
    )

{
    NET_API_STATUS error;
    PSERVER_REQUEST_PACKET srp;

    //
    // Make sure that the level is valid.
    //

    if ( Level != 2 && Level != 3 ) {
        return ERROR_INVALID_LEVEL;
    }

    //
    // Set up the input parameters in the request buffer.
    //

    srp = SsAllocateSrp( );
    if ( srp == NULL ) {
        return ERROR_NOT_ENOUGH_MEMORY;
    }

#ifdef UNICODE
    RtlInitUnicodeString( &srp->Name1, BasePath );
    RtlInitUnicodeString( &srp->Name2, UserName );
#else
    {
        NTSTATUS status;
        OEM_STRING ansiString;
        RtlInitString( &ansiString, BasePath );
        status = RtlOemStringToUnicodeString( &srp->Name1, &ansiString, TRUE );
        RtlInitString( &ansiString, UserName );
        status = RtlOemStringToUnicodeString( &srp->Name2, &ansiString, TRUE );
    }
#endif

    srp->Level = Level;
    if ( IsGetInfo ) {
        srp->Flags = SRP_RETURN_SINGLE_ENTRY;
    }

    if ( ARGUMENT_PRESENT( ResumeHandle ) ) {
        srp->Parameters.Get.ResumeHandle = *ResumeHandle;
    } else {
        srp->Parameters.Get.ResumeHandle = 0;
    }

    //
    // Get the data from the server.  This routine will allocate the
    // return buffer and handle the case where PreferredMaximumLength ==
    // -1.
    //

    error = SsServerFsControlGetInfo(
                FSCTL_SRV_NET_FILE_ENUM,
                srp,
                (PVOID *)Buffer,
                PreferredMaximumLength
                );

    //
    // Set up return information.  Only change the resume handle if at
    // least one entry was returned.
    //

    *EntriesRead = srp->Parameters.Get.EntriesRead;
    *TotalEntries = srp->Parameters.Get.TotalEntries;
    if ( *EntriesRead > 0 && ARGUMENT_PRESENT( ResumeHandle ) ) {
        *ResumeHandle = srp->Parameters.Get.ResumeHandle;
    }

#ifndef UNICODE
    RtlFreeUnicodeString( &srp->Name1 );
    RtlFreeUnicodeString( &srp->Name2 );
#endif

    SsFreeSrp( srp );

    return error;

} // FileEnumCommon
Пример #13
0
NET_API_STATUS
MsgUnformatName(
    OUT LPTSTR  UnicodeName,
    IN  LPSTR   FormattedName
    )

/*++

Routine Description:

    This routine creates a Unicode NUL-Terminated version of a NetBios
    Formatted name.

Arguments:

    UnicodeName - This is a pointer to a location where the un-formatted
        NUL terminated Unicode Name is to be copied.

    FormattedName - This is a pointer to an NCB formatted name.  This
        name always contains NCBNAMSZ characters of which the last character
        is a code used for a forward/non-forward flag.  These strings
        are space padded.
        

Return Value:

    NERR_Success - The operation was successful.

    NERR_Internal - The operation was unsuccessful.

--*/
{
    UNICODE_STRING  unicodeString;
    OEM_STRING     ansiString;
    NTSTATUS        ntStatus;
    int             i;

    //
    // Translate the ansi string in the name table to a unicode name
    //
#ifdef UNICODE
    unicodeString.Length = (NCBNAMSZ -1) * sizeof(WCHAR);
    unicodeString.MaximumLength = NCBNAMSZ * sizeof(WCHAR);
    unicodeString.Buffer = (LPWSTR)UnicodeName;

    ansiString.Length = NCBNAMSZ-1;
    ansiString.MaximumLength = NCBNAMSZ;
    ansiString.Buffer = FormattedName;

    ntStatus = RtlOemStringToUnicodeString(
                &unicodeString,      // Destination
                &ansiString,         // Source
                FALSE);              // Don't allocate the destination.

    if (!NT_SUCCESS(ntStatus)) {
        MSG_LOG(ERROR,
            "UnformatName:RtlOemStringToUnicodeString Failed rc=%X\n",
            ntStatus);
        //
        // Indicate a failure
        //
        return(NERR_InternalError);  
    }
#else
    UNUSED (ntStatus);
    UNUSED (ansiString);
    UNUSED (unicodeString);
    strncpy(UnicodeName, FormattedName, NCBNAMSZ-1);
#endif

    //
    // Remove excess Space characters starting at the back (skipping
    // the 03 flag character.
    //
    i = NCBNAMSZ-2;

    while ( UnicodeName[i] == TEXT(' ')) {

        UnicodeName[i--] = TEXT('\0');

        if (i < 0) {
            MSG_LOG(ERROR,
                "UnformatName:Nothing but space characters\n",0);
            return(NERR_InternalError);
        }
    }
    return(NERR_Success);
}
Пример #14
0
VOID
BowserBecomeBackupWorker(
    IN PVOID WorkItem
    )

{
    PPOST_DATAGRAM_CONTEXT Context = WorkItem;
    PIRP Irp = NULL;
    PTRANSPORT Transport = Context->TransportName->Transport;
    UNICODE_STRING UPromoteeName;
    OEM_STRING APromoteeName;
    PPAGED_TRANSPORT PagedTransport = Transport->PagedTransport;
    PBECOME_BACKUP_1 BecomeBackupRequest = Context->Buffer;

    PAGED_CODE();

    UPromoteeName.Buffer = NULL;

    LOCK_TRANSPORT(Transport);

    try {
        NTSTATUS Status;


        RtlInitAnsiString(&APromoteeName, BecomeBackupRequest->BrowserToPromote);

        Status = RtlOemStringToUnicodeString(&UPromoteeName, &APromoteeName, TRUE);

        if (!NT_SUCCESS(Status)) {
            BowserWriteErrorLogEntry(EVENT_BOWSER_NAME_CONVERSION_FAILED, Status, APromoteeName.Buffer, APromoteeName.Length, 0);
            try_return(NOTHING);
        }

        if (RtlEqualUnicodeString(&UPromoteeName, &Transport->ComputerName->PagedTransportName->Name->Name, TRUE)) {

            if (PagedTransport->Role == Master) {

                BowserWriteErrorLogEntry(EVENT_BOWSER_PROMOTED_WHILE_ALREADY_MASTER,
                                        STATUS_UNSUCCESSFUL,
                                        NULL,
                                        0,
                                        0);

                try_return(NOTHING);

            }


            //
            //  Ignore become backup requests on point-to-point (RAS) links and
            //      transports which are actually duplicates of others.
            //

            if (PagedTransport->DisabledTransport) {
                try_return(NOTHING);
            }

            //
            //  Complete any the first become backup request outstanding against this
            //  workstation.
            //

            Irp = BowserDequeueQueuedIrp(&Transport->BecomeBackupQueue);

            if (Irp != NULL) {
                Irp->IoStatus.Information = 0;

                BowserCompleteRequest(Irp, STATUS_SUCCESS);
            }
        }


try_exit:NOTHING;
    } finally {

        UNLOCK_TRANSPORT(Transport);

        BowserDereferenceTransportName(Context->TransportName);
        BowserDereferenceTransport(Transport);

        if (UPromoteeName.Buffer != NULL) {
            RtlFreeUnicodeString(&UPromoteeName);
        }

        InterlockedDecrement( &BowserPostedDatagramCount );
        FREE_POOL(Context);

    }

}