/**
 * Internal worker for RTFileRename and RTFileMove.
 *
 * @returns iprt status code.
 * @param   pszSrc      The source filename.
 * @param   pszDst      The destination filename.
 * @param   fFlags      The windows MoveFileEx flags.
 * @param   fFileType   The filetype. We use the RTFMODE filetypes here. If it's 0,
 *                      anything goes. If it's RTFS_TYPE_DIRECTORY we'll check that the
 *                      source is a directory. If Its RTFS_TYPE_FILE we'll check that it's
 *                      not a directory (we are NOT checking whether it's a file).
 */
DECLHIDDEN(int) rtPathWin32MoveRename(const char *pszSrc, const char *pszDst, uint32_t fFlags, RTFMODE fFileType)
{
    /*
     * Convert the strings.
     */
    PRTUTF16 pwszSrc;
    int rc = RTStrToUtf16(pszSrc, &pwszSrc);
    if (RT_SUCCESS(rc))
    {
        PRTUTF16 pwszDst;
        rc = RTStrToUtf16(pszDst, &pwszDst);
        if (RT_SUCCESS(rc))
        {
            /*
             * Check object type if requested.
             * This is open to race conditions.
             */
            if (fFileType)
            {
                DWORD dwAttr = GetFileAttributesW(pwszSrc);
                if (dwAttr == INVALID_FILE_ATTRIBUTES)
                    rc = RTErrConvertFromWin32(GetLastError());
                else if (RTFS_IS_DIRECTORY(fFileType))
                    rc = dwAttr & FILE_ATTRIBUTE_DIRECTORY ? VINF_SUCCESS : VERR_NOT_A_DIRECTORY;
                else
                    rc = dwAttr & FILE_ATTRIBUTE_DIRECTORY ? VERR_IS_A_DIRECTORY : VINF_SUCCESS;
            }
            if (RT_SUCCESS(rc))
            {
                if (MoveFileExW(pwszSrc, pwszDst, fFlags))
                    rc = VINF_SUCCESS;
                else
                {
                    DWORD Err = GetLastError();
                    rc = RTErrConvertFromWin32(Err);
                    Log(("MoveFileExW('%s', '%s', %#x, %RTfmode): fails with rc=%Rrc & lasterr=%d\n",
                         pszSrc, pszDst, fFlags, fFileType, rc, Err));
                }
            }
            RTUtf16Free(pwszDst);
        }
        RTUtf16Free(pwszSrc);
    }
    return rc;
}
示例#2
0
/**
 * Creates the service.
 *
 * @returns VBox status code.
 * @retval  VWRN_ALREADY_EXISTS if it already exists.
 */
static int suplibOsCreateService(void)
{
    /*
     * Assume it didn't exist, so we'll create the service.
     */
    int        rc;
    SC_HANDLE hSMgrCreate = OpenSCManager(NULL, NULL, SERVICE_CHANGE_CONFIG);
    DWORD     dwErr = GetLastError();
    AssertMsg(hSMgrCreate, ("OpenSCManager(,,create) failed dwErr=%d\n", dwErr));
    if (hSMgrCreate != NULL)
    {
        char szDriver[RTPATH_MAX];
        rc = RTPathExecDir(szDriver, sizeof(szDriver) - sizeof("\\VBoxDrv.sys"));
        if (RT_SUCCESS(rc))
        {
            strcat(szDriver, "\\VBoxDrv.sys");
            SC_HANDLE hService = CreateService(hSMgrCreate,
                                               SERVICE_NAME,
                                               "VBox Support Driver",
                                               SERVICE_QUERY_STATUS,
                                               SERVICE_KERNEL_DRIVER,
                                               SERVICE_DEMAND_START,
                                               SERVICE_ERROR_NORMAL,
                                               szDriver,
                                               NULL, NULL, NULL, NULL, NULL);
            dwErr = GetLastError();
            if (hService)
            {
                CloseServiceHandle(hService);
                rc = VINF_SUCCESS;
            }
            else if (dwErr == ERROR_SERVICE_EXISTS)
                rc = VWRN_ALREADY_EXISTS;
            else
            {
                AssertMsgFailed(("CreateService failed! dwErr=%Rwa szDriver=%s\n", dwErr, szDriver));
                rc = RTErrConvertFromWin32(dwErr);
            }
        }
        CloseServiceHandle(hSMgrCreate);
    }
    else
        rc = RTErrConvertFromWin32(GetLastError());
    return rc;
}
示例#3
0
/**
 * Builds and allocates the security descriptor required for securing the local pipe.
 *
 * @return  IPRT status code.
 * @param   ppDesc              Where to store the allocated security descriptor on success.
 *                              Must be free'd using LocalFree().
 */
static int rtLocalIpcServerWinAllocSecurityDescriptior(PSECURITY_DESCRIPTOR *ppDesc, bool fServer)
{
    /** @todo Stuff this into RTInitOnce? Later. */
    PFNCONVERTSTRINGSECURITYDESCRIPTORTOSECURITYDESCRIPTOR
        pfnConvertStringSecurityDescriptorToSecurityDescriptor = NULL;

    RTLDRMOD hAdvApi32 = NIL_RTLDRMOD;
    int rc = RTLdrLoadSystem("Advapi32.dll", true /*fNoUnload*/, &hAdvApi32);
    if (RT_SUCCESS(rc))
        rc = RTLdrGetSymbol(hAdvApi32, "ConvertStringSecurityDescriptorToSecurityDescriptorW",
                            (void**)&pfnConvertStringSecurityDescriptorToSecurityDescriptor);

    PSECURITY_DESCRIPTOR pSecDesc = NULL;
    if (RT_SUCCESS(rc))
    {
        AssertPtr(pfnConvertStringSecurityDescriptorToSecurityDescriptor);

        /*
         * We'll create a security descriptor from a SDDL that denies
         * access to network clients (this is local IPC after all), it
         * makes some further restrictions to prevent non-authenticated
         * users from screwing around.
         */
        PRTUTF16 pwszSDDL;
        rc = RTStrToUtf16(fServer
                          ? RTLOCALIPC_WIN_SDDL_SERVER : RTLOCALIPC_WIN_SDDL_CLIENT, &pwszSDDL);
        if (RT_SUCCESS(rc))
        {
            if (!pfnConvertStringSecurityDescriptorToSecurityDescriptor((LPCTSTR)pwszSDDL,
                                                                        SDDL_REVISION_1,
                                                                        &pSecDesc,
                                                                        NULL))
            {
                rc = RTErrConvertFromWin32(GetLastError());
            }

            RTUtf16Free(pwszSDDL);
        }
    }
    else
    {
        /* Windows OSes < W2K SP2 not supported for now, bail out. */
        /** @todo Implement me! */
        rc = VERR_NOT_SUPPORTED;
    }

    if (hAdvApi32 != NIL_RTLDRMOD)
         RTLdrClose(hAdvApi32);

    if (RT_SUCCESS(rc))
    {
        AssertPtr(pSecDesc);
        *ppDesc = pSecDesc;
    }

    return rc;
}
示例#4
0
/**
 * Creates the service.
 *
 * @returns 0 on success.
 * @returns < 0 on failure.
 */
int usblibOsCreateService(void)
{
    /*
     * Assume it didn't exist, so we'll create the service.
     */
    SC_HANDLE hSMgrCreate = OpenSCManager(NULL, NULL, SERVICE_CHANGE_CONFIG);
    DWORD dwLastError = GetLastError();
    int rc = RTErrConvertFromWin32(dwLastError);
    AssertMsg(hSMgrCreate, ("OpenSCManager(,,create) failed rc=%d\n", dwLastError));
    if (hSMgrCreate)
    {
        char szDriver[RTPATH_MAX];
        int rc = RTPathExecDir(szDriver, sizeof(szDriver) - sizeof("\\VBoxUSBMon.sys"));
        if (RT_SUCCESS(rc))
        {
            strcat(szDriver, "\\VBoxUSBMon.sys");
            RTPrintf("Creating USB monitor driver service with path %s ...\n", szDriver);
            SC_HANDLE hService = CreateService(hSMgrCreate,
                                               SERVICE_NAME,
                                               "VBox USB Monitor Driver",
                                               SERVICE_QUERY_STATUS,
                                               SERVICE_KERNEL_DRIVER,
                                               SERVICE_DEMAND_START,
                                               SERVICE_ERROR_NORMAL,
                                               szDriver,
                                               NULL, NULL, NULL, NULL, NULL);
            DWORD dwLastError = GetLastError();
            if (dwLastError == ERROR_SERVICE_EXISTS)
            {
                RTPrintf("USB monitor driver service already exists, skipping creation.\n");
                rc = usblibOsChangeService(szDriver);
            }
            else
            {
                AssertMsg(hService, ("CreateService failed! LastError=%Rwa, szDriver=%s\n", dwLastError, szDriver));
                rc = RTErrConvertFromWin32(dwLastError);
                if (hService != NULL)
                    CloseServiceHandle(hService);
            }
        }
        CloseServiceHandle(hSMgrCreate);
    }
    return rc;
}
RTR3DECL(int)  RTFileFlush(RTFILE hFile)
{
    if (!FlushFileBuffers((HANDLE)RTFileToNative(hFile)))
    {
        int rc = GetLastError();
        Log(("FlushFileBuffers failed with %d\n", rc));
        return RTErrConvertFromWin32(rc);
    }
    return VINF_SUCCESS;
}
示例#6
0
RTDECL(int) RTLocalIpcServerCreate(PRTLOCALIPCSERVER phServer, const char *pszName, uint32_t fFlags)
{
    /*
     * Basic parameter validation.
     */
    AssertPtrReturn(phServer, VERR_INVALID_POINTER);
    AssertPtrReturn(pszName, VERR_INVALID_POINTER);
    AssertReturn(*pszName, VERR_INVALID_PARAMETER);
    AssertReturn(!(fFlags & ~(RTLOCALIPC_FLAGS_VALID_MASK)), VERR_INVALID_PARAMETER);
    AssertReturn((fFlags & RTLOCALIPC_FLAGS_MULTI_SESSION), VERR_INVALID_PARAMETER); /** @todo Implement !RTLOCALIPC_FLAGS_MULTI_SESSION */

    /*
     * Allocate and initialize the instance data.
     */
    size_t cchName = strlen(pszName);
    size_t cch = RT_OFFSETOF(RTLOCALIPCSERVERINT, szName[cchName + sizeof(RTLOCALIPC_WIN_PREFIX)]);
    PRTLOCALIPCSERVERINT pThis = (PRTLOCALIPCSERVERINT)RTMemAlloc(cch);
    if (!pThis)
        return VERR_NO_MEMORY;
    pThis->u32Magic = RTLOCALIPCSERVER_MAGIC;
    pThis->cRefs = 1; /* the one we return */
    pThis->fCancelled = false;
    memcpy(pThis->szName, RTLOCALIPC_WIN_PREFIX, sizeof(RTLOCALIPC_WIN_PREFIX) - 1);
    memcpy(&pThis->szName[sizeof(RTLOCALIPC_WIN_PREFIX) - 1], pszName, cchName + 1);
    int rc = RTCritSectInit(&pThis->CritSect);
    if (RT_SUCCESS(rc))
    {
        pThis->hEvent = CreateEvent(NULL /*lpEventAttributes*/, TRUE /*bManualReset*/,
                                    FALSE /*bInitialState*/, NULL /*lpName*/);
        if (pThis->hEvent != NULL)
        {
            RT_ZERO(pThis->OverlappedIO);
            pThis->OverlappedIO.Internal = STATUS_PENDING;
            pThis->OverlappedIO.hEvent = pThis->hEvent;

            rc = rtLocalIpcServerWinCreatePipeInstance(&pThis->hNmPipe,
                                                       pThis->szName, true /* fFirst */);
            if (RT_SUCCESS(rc))
            {
                *phServer = pThis;
                return VINF_SUCCESS;
            }

            BOOL fRc = CloseHandle(pThis->hEvent);
            AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
        }
        else
            rc = RTErrConvertFromWin32(GetLastError());

        int rc2 = RTCritSectDelete(&pThis->CritSect);
        AssertRC(rc2);
    }
    RTMemFree(pThis);
    return rc;
}
示例#7
0
RTDECL(int)  RTSemEventCreateEx(PRTSEMEVENT phEventSem, uint32_t fFlags, RTLOCKVALCLASS hClass, const char *pszNameFmt, ...)
{
    AssertReturn(!(fFlags & ~(RTSEMEVENT_FLAGS_NO_LOCK_VAL | RTSEMEVENT_FLAGS_BOOTSTRAP_HACK)), VERR_INVALID_PARAMETER);
    Assert(!(fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK) || (fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL));

    struct RTSEMEVENTINTERNAL *pThis;
    if (!(fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK))
        pThis = (struct RTSEMEVENTINTERNAL *)RTMemAlloc(sizeof(*pThis));
    else
        pThis = (struct RTSEMEVENTINTERNAL *)rtMemBaseAlloc(sizeof(*pThis));
    if (!pThis)
        return VERR_NO_MEMORY;

    /*
     * Create the semaphore.
     * (Auto reset, not signaled, private event object.)
     */
    pThis->hev = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (pThis->hev != NULL) /* not INVALID_HANDLE_VALUE */
    {
        pThis->u32Magic = RTSEMEVENT_MAGIC;
        pThis->fFlags   = fFlags;
#ifdef RTSEMEVENT_STRICT
        if (!pszNameFmt)
        {
            static uint32_t volatile s_iSemEventAnon = 0;
            RTLockValidatorRecSharedInit(&pThis->Signallers, hClass, RTLOCKVAL_SUB_CLASS_ANY, pThis,
                                         true /*fSignaller*/, !(fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL),
                                         "RTSemEvent-%u", ASMAtomicIncU32(&s_iSemEventAnon) - 1);
        }
        else
        {
            va_list va;
            va_start(va, pszNameFmt);
            RTLockValidatorRecSharedInitV(&pThis->Signallers, hClass, RTLOCKVAL_SUB_CLASS_ANY, pThis,
                                          true /*fSignaller*/, !(fFlags & RTSEMEVENT_FLAGS_NO_LOCK_VAL),
                                          pszNameFmt, va);
            va_end(va);
        }
        pThis->fEverHadSignallers = false;
#else
        RT_NOREF_PV(hClass); RT_NOREF_PV(pszNameFmt);
#endif

        *phEventSem = pThis;
        return VINF_SUCCESS;
    }

    DWORD dwErr = GetLastError();
    if (!(fFlags & RTSEMEVENT_FLAGS_BOOTSTRAP_HACK))
        RTMemFree(pThis);
    else
        rtMemBaseFree(pThis);
    return RTErrConvertFromWin32(dwErr);
}
示例#8
0
static int vboxClipboardChanged(PVBOXCLIPBOARDCONTEXT pCtx)
{
    AssertPtr(pCtx);

    /* Query list of available formats and report to host. */
    int rc = VINF_SUCCESS;
    if (FALSE == OpenClipboard(pCtx->hwnd))
    {
        rc = RTErrConvertFromWin32(GetLastError());
    }
    else
    {
        uint32_t u32Formats = 0;
        UINT format = 0;

        while ((format = EnumClipboardFormats(format)) != 0)
        {
            LogFlowFunc(("vboxClipboardChanged: format = 0x%08X\n", format));
            switch (format)
            {
                case CF_UNICODETEXT:
                case CF_TEXT:
                    u32Formats |= VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT;
                    break;

                case CF_DIB:
                case CF_BITMAP:
                    u32Formats |= VBOX_SHARED_CLIPBOARD_FMT_BITMAP;
                    break;

                default:
                {
                    if (format >= 0xC000)
                    {
                        TCHAR szFormatName[256];

                        int cActual = GetClipboardFormatName(format, szFormatName, sizeof(szFormatName)/sizeof (TCHAR));
                        if (cActual)
                        {
                            if (strcmp (szFormatName, "HTML Format") == 0)
                            {
                                u32Formats |= VBOX_SHARED_CLIPBOARD_FMT_HTML;
                            }
                        }
                    }
                    break;
                }
            }
        }

        CloseClipboard();
        rc = VbglR3ClipboardReportFormats(pCtx->u32ClientID, u32Formats);
    }
    return rc;
}
示例#9
0
/**
 * Deletes the service.
 *
 * @returns VBox status code.
 */
int suplibOsDeleteService(void)
{
    /*
     * Assume it didn't exist, so we'll create the service.
     */
    int         rc;
    SC_HANDLE   hSMgr = OpenSCManager(NULL, NULL, SERVICE_CHANGE_CONFIG);
    DWORD       dwErr = GetLastError();
    AssertMsg(hSMgr, ("OpenSCManager(,,delete) failed rc=%d\n", dwErr));
    if (hSMgr)
    {
        SC_HANDLE hService = OpenService(hSMgr, SERVICE_NAME, DELETE);
        if (hService)
        {
            /*
             * Delete the service.
             */
            if (DeleteService(hService))
                rc = VINF_SUCCESS;
            else
            {
                dwErr = GetLastError();
                AssertMsgFailed(("DeleteService failed dwErr=%Rwa\n", dwErr));
                rc = RTErrConvertFromWin32(dwErr);
            }
            CloseServiceHandle(hService);
        }
        else
        {
            dwErr = GetLastError();
            if (dwErr == ERROR_SERVICE_DOES_NOT_EXIST)
                rc = VINF_SUCCESS;
            else
            {
                AssertMsgFailed(("OpenService failed dwErr=%Rwa\n", dwErr));
                rc = RTErrConvertFromWin32(dwErr);
            }
        }
        CloseServiceHandle(hSMgr);
    }
    return rc;
}
示例#10
0
static int vgsvcWinStart(void)
{
    int rc = VINF_SUCCESS;

    /*
     * Create a well-known SID for the "Builtin Users" group and modify the ACE
     * for the shared folders miniport redirector DN (whatever DN means).
     */
    PSID                     pBuiltinUsersSID = NULL;
    SID_IDENTIFIER_AUTHORITY SIDAuthWorld     = SECURITY_LOCAL_SID_AUTHORITY;
    if (AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_LOCAL_RID, 0, 0, 0, 0, 0, 0, 0, &pBuiltinUsersSID))
    {
        rc = vgsvcWinAddAceToObjectsSecurityDescriptor(TEXT("\\\\.\\VBoxMiniRdrDN"), SE_FILE_OBJECT,
                                                       (LPTSTR)pBuiltinUsersSID, TRUSTEE_IS_SID,
                                                       FILE_GENERIC_READ | FILE_GENERIC_WRITE, SET_ACCESS, NO_INHERITANCE);
        /* If we don't find our "VBoxMiniRdrDN" (for Shared Folders) object above,
           don't report an error; it just might be not installed. Otherwise this
           would cause the SCM to hang on starting up the service. */
        if (rc == VERR_FILE_NOT_FOUND || rc == VERR_PATH_NOT_FOUND)
            rc = VINF_SUCCESS;

        FreeSid(pBuiltinUsersSID);
    }
    else
        rc = RTErrConvertFromWin32(GetLastError());
    if (RT_SUCCESS(rc))
    {
        /*
         * Start the service.
         */
        vgsvcWinSetStatus(SERVICE_START_PENDING, 0);

        rc = VGSvcStartServices();
        if (RT_SUCCESS(rc))
        {
            vgsvcWinSetStatus(SERVICE_RUNNING, 0);
            VGSvcMainWait();
        }
        else
        {
            vgsvcWinSetStatus(SERVICE_STOPPED, 0);
#if 0 /** @todo r=bird: Enable this if SERVICE_CONTROL_STOP isn't triggered automatically */
            VGSvcStopServices();
#endif
        }
    }
    else
        vgsvcWinSetStatus(SERVICE_STOPPED, 0);

    if (RT_FAILURE(rc))
        VGSvcError("Service failed to start with rc=%Rrc!\n", rc);

    return rc;
}
DECLCALLBACK(int) rtldrNativeClose(PRTLDRMODINTERNAL pMod)
{
    PRTLDRMODNATIVE pModNative = (PRTLDRMODNATIVE)pMod;
    if (   (pModNative->fFlags & RTLDRLOAD_FLAGS_NO_UNLOAD)
        || FreeLibrary((HMODULE)pModNative->hNative))
    {
        pModNative->hNative = (uintptr_t)INVALID_HANDLE_VALUE;
        return VINF_SUCCESS;
    }
    return RTErrConvertFromWin32(GetLastError());
}
示例#12
0
RTR3DECL(int)  RTFileUnlock(RTFILE hFile, int64_t offLock, uint64_t cbLock)
{
    Assert(offLock >= 0);

    if (UnlockFile((HANDLE)RTFileToNative(hFile),
                   LOW_DWORD(offLock), HIGH_DWORD(offLock),
                   LOW_DWORD(cbLock), HIGH_DWORD(cbLock)))
        return VINF_SUCCESS;

    return RTErrConvertFromWin32(GetLastError());
}
示例#13
0
RTDECL(int) RTTimeSet(PCRTTIMESPEC pTime)
{
    FILETIME    FileTime;
    SYSTEMTIME  SysTime;
    if (FileTimeToSystemTime(RTTimeSpecGetNtFileTime(pTime, &FileTime), &SysTime))
    {
        if (SetSystemTime(&SysTime))
            return VINF_SUCCESS;
    }
    return RTErrConvertFromWin32(GetLastError());
}
static int vboxClipboardCreateWindow(PVBOXCLIPBOARDCONTEXT pCtx)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);

    int rc = VINF_SUCCESS;

    AssertPtr(pCtx->pEnv);
    HINSTANCE hInstance = pCtx->pEnv->hInstance;
    Assert(hInstance != 0);

    /* Register the Window Class. */
    WNDCLASSEX wc = { 0 };
    wc.cbSize     = sizeof(WNDCLASSEX);

    if (!GetClassInfoEx(hInstance, s_szClipWndClassName, &wc))
    {
        wc.style         = CS_NOCLOSE;
        wc.lpfnWndProc   = vboxClipboardWndProc;
        wc.hInstance     = pCtx->pEnv->hInstance;
        wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
        wc.lpszClassName = s_szClipWndClassName;

        ATOM wndClass = RegisterClassEx(&wc);
        if (wndClass == 0)
            rc = RTErrConvertFromWin32(GetLastError());
    }

    if (RT_SUCCESS(rc))
    {
        const PVBOXCLIPBOARDWINCTX pWinCtx = &pCtx->Win;

        /* Create the window. */
        pWinCtx->hWnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
                                       s_szClipWndClassName, s_szClipWndClassName,
                                       WS_POPUPWINDOW,
                                       -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
        if (pWinCtx->hWnd == NULL)
        {
            rc = VERR_NOT_SUPPORTED;
        }
        else
        {
            SetWindowPos(pWinCtx->hWnd, HWND_TOPMOST, -200, -200, 0, 0,
                         SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);

            VBoxClipboardWinAddToCBChain(pWinCtx);
            if (!VBoxClipboardWinIsNewAPI(&pWinCtx->newAPI))
                pWinCtx->oldAPI.timerRefresh = SetTimer(pWinCtx->hWnd, 0, 10 * 1000 /* 10s */, NULL);
        }
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}
示例#15
0
RTDECL(int) RTSymlinkDelete(const char *pszSymlink, uint32_t fDelete)
{
    /*
     * Convert the path.
     */
    PRTUTF16 pwszNativeSymlink;
    int rc = RTStrToUtf16(pszSymlink, &pwszNativeSymlink);
    if (RT_SUCCESS(rc))
    {
        /*
         * We have to use different APIs depending on whether this is a
         * directory or file link.  This means we're subject to one more race
         * than on posix at the moment.  We could probably avoid this though,
         * if we wanted to go talk with the native API layer below Win32...
         */
        DWORD dwAttr = GetFileAttributesW(pwszNativeSymlink);
        if (dwAttr != INVALID_FILE_ATTRIBUTES)
        {
            if (dwAttr & FILE_ATTRIBUTE_REPARSE_POINT)
            {
                BOOL fRc;
                if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
                    fRc = RemoveDirectoryW(pwszNativeSymlink);
                else
                    fRc = DeleteFileW(pwszNativeSymlink);
                if (fRc)
                    rc = VINF_SUCCESS;
                else
                    rc = RTErrConvertFromWin32(GetLastError());
            }
            else
                rc = VERR_NOT_SYMLINK;
        }
        else
            rc = RTErrConvertFromWin32(GetLastError());
        RTUtf16Free(pwszNativeSymlink);
    }

    LogFlow(("RTSymlinkDelete(%p={%s}, %#x): returns %Rrc\n", pszSymlink, pszSymlink, fDelete, rc));
    return rc;
}
示例#16
0
RTDECL(int) RTPathGetCurrent(char *pszPath, size_t cchPath)
{
    int rc;

    /*
     * GetCurrentDirectory may in some cases omit the drive letter, according
     * to MSDN, thus the GetFullPathName call.
     */
    RTUTF16 wszCurPath[RTPATH_MAX];
    if (GetCurrentDirectoryW(RTPATH_MAX, wszCurPath))
    {
        RTUTF16 wszFullPath[RTPATH_MAX];
        if (GetFullPathNameW(wszCurPath, RTPATH_MAX, wszFullPath, NULL))
            rc = RTUtf16ToUtf8Ex(&wszFullPath[0], RTSTR_MAX, &pszPath, cchPath, NULL);
        else
            rc = RTErrConvertFromWin32(GetLastError());
    }
    else
        rc = RTErrConvertFromWin32(GetLastError());
    return rc;
}
示例#17
0
RTDECL(int) RTFileAioCtxAssociateWithFile(RTFILEAIOCTX hAioCtx, RTFILE hFile)
{
    int rc = VINF_SUCCESS;
    PRTFILEAIOCTXINTERNAL pCtxInt = hAioCtx;
    RTFILEAIOCTX_VALID_RETURN(pCtxInt);

    HANDLE hTemp = CreateIoCompletionPort((HANDLE)RTFileToNative(hFile), pCtxInt->hIoCompletionPort, 0, 1);
    if (hTemp != pCtxInt->hIoCompletionPort)
        rc = RTErrConvertFromWin32(GetLastError());

    return rc;
}
示例#18
0
/**
 * Writes an IPC message to the IPC context's client.
 *
 * @return  IPRT status code.
 * @param   pCtx                    The IPC context.
 * @param   pMessage                Pointer to message to send.
 * @param   cbMessage               Size (in bytes) of message to send.
 */
int VBoxIPCWriteMessage(PVBOXIPCCONTEXT pCtx, BYTE *pMessage, DWORD cbMessage)
{
    int rc = VINF_SUCCESS;
    while (RT_SUCCESS(rc))
    {
        DWORD cbWritten;
        if (!WriteFile(pCtx->hPipe, pMessage, cbMessage, &cbWritten, 0))
            rc = RTErrConvertFromWin32(GetLastError());
        pMessage += cbWritten;
    }
    return rc;
}
DECLCALLBACK(int) rtldrNativeGetSymbol(PRTLDRMODINTERNAL pMod, const char *pszSymbol, void **ppvValue)
{
    PRTLDRMODNATIVE pModNative = (PRTLDRMODNATIVE)pMod;
    FARPROC pfn = GetProcAddress((HMODULE)pModNative->hNative, pszSymbol);
    if (pfn)
    {
        *ppvValue = (void *)pfn;
        return VINF_SUCCESS;
    }
    *ppvValue = NULL;
    return RTErrConvertFromWin32(GetLastError());
}
示例#20
0
int rtDirNativeOpen(PRTDIR pDir, char *pszPathBuf)
{
    /*
     * Setup the search expression.
     *
     * pszPathBuf is pointing to the return 4K return buffer for the RTPathReal()
     * call in rtDirOpenCommon(), so all we gota do is check that we don't overflow
     * it when adding the wildcard expression.
     */
    size_t cbExpr;
    const char *pszExpr;
    if (pDir->enmFilter == RTDIRFILTER_WINNT)
    {
        pszExpr = pDir->pszFilter;
        cbExpr  = pDir->cchFilter + 1;
    }
    else
    {
        pszExpr = "*";
        cbExpr  = sizeof("*");
    }
    if (pDir->cchPath + cbExpr > RTPATH_MAX)
        return VERR_FILENAME_TOO_LONG;
    memcpy(pszPathBuf + pDir->cchPath, pszExpr, cbExpr);


    /*
     * Attempt opening the search.
     */
    int rc = VINF_SUCCESS;
    PRTUTF16 pwszName;
    rc = RTStrToUtf16(pszPathBuf, &pwszName);
    if (RT_SUCCESS(rc))
    {
        pDir->hDir = FindFirstFileW((LPCWSTR)pwszName, &pDir->Data);
        if (pDir->hDir != INVALID_HANDLE_VALUE)
            pDir->fDataUnread = true;
        else
        {
            DWORD dwErr = GetLastError();
            /* Theoretical case of an empty directory or more normal case of no matches. */
            if (   dwErr == ERROR_FILE_NOT_FOUND
                || dwErr == ERROR_NO_MORE_FILES /* ???*/)
                pDir->fDataUnread = false;
            else
                rc = RTErrConvertFromWin32(GetLastError());
        }
        RTUtf16Free(pwszName);
    }

    return rc;
}
示例#21
0
RTDECL(int)  RTUuidCreate(PRTUUID pUuid)
{
    /* check params */
    AssertPtrReturn(pUuid, VERR_INVALID_POINTER);

    RPC_STATUS rc = UuidCreate((UUID *)pUuid);
    if (   rc == RPC_S_OK
        || rc == RPC_S_UUID_LOCAL_ONLY)
        return VINF_SUCCESS;

    /* error exit */
    return RTErrConvertFromWin32(rc);
}
示例#22
0
RTR3DECL(int)  RTFileDelete(const char *pszFilename)
{
    PRTUTF16 pwszFilename;
    int rc = RTStrToUtf16(pszFilename, &pwszFilename);
    if (RT_SUCCESS(rc))
    {
        if (!DeleteFileW(pwszFilename))
            rc = RTErrConvertFromWin32(GetLastError());
        RTUtf16Free(pwszFilename);
    }

    return rc;
}
示例#23
0
RTDECL(int) RTFileAioCtxSubmit(RTFILEAIOCTX hAioCtx, PRTFILEAIOREQ pahReqs, size_t cReqs)
{
    /*
     * Parameter validation.
     */
    int rc = VINF_SUCCESS;
    PRTFILEAIOCTXINTERNAL pCtxInt = hAioCtx;
    RTFILEAIOCTX_VALID_RETURN(pCtxInt);
    AssertReturn(cReqs > 0,  VERR_INVALID_PARAMETER);
    Assert(cReqs <= INT32_MAX);
    AssertPtrReturn(pahReqs, VERR_INVALID_POINTER);
    size_t i;

    for (i = 0; i < cReqs; i++)
    {
        PRTFILEAIOREQINTERNAL pReqInt = pahReqs[i];
        BOOL fSucceeded;

        Assert(pReqInt->cbTransfer == (DWORD)pReqInt->cbTransfer);
        if (pReqInt->enmTransferDirection == TRANSFERDIRECTION_READ)
        {
            fSucceeded = ReadFile(pReqInt->hFile, pReqInt->pvBuf,
                                  (DWORD)pReqInt->cbTransfer, NULL,
                                  &pReqInt->Overlapped);
        }
        else if (pReqInt->enmTransferDirection == TRANSFERDIRECTION_WRITE)
        {
            fSucceeded = WriteFile(pReqInt->hFile, pReqInt->pvBuf,
                                   (DWORD)pReqInt->cbTransfer, NULL,
                                   &pReqInt->Overlapped);
        }
        else
        {
            fSucceeded = false;
            AssertMsgFailed(("Invalid transfer direction\n"));
        }

        if (RT_UNLIKELY(!fSucceeded && GetLastError() != ERROR_IO_PENDING))
        {
            RTFILEAIOREQ_SET_STATE(pReqInt, COMPLETED);
            rc = RTErrConvertFromWin32(GetLastError());
            pReqInt->Rc = rc;
            break;
        }
        RTFILEAIOREQ_SET_STATE(pReqInt, SUBMITTED);
    }

    ASMAtomicAddS32(&pCtxInt->cRequests, (int32_t)i);

    return rc;
}
RTDECL(int) RTSemMutexRelease(RTSEMMUTEX hMutexSem)
{
    /*
     * Validate.
     */
    RTSEMMUTEXINTERNAL *pThis = hMutexSem;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSEMMUTEX_MAGIC, VERR_INVALID_HANDLE);

    /*
     * Check ownership and recursions.
     */
    RTNATIVETHREAD hNativeSelf = RTThreadNativeSelf();
    RTNATIVETHREAD hNativeOwner;
    ASMAtomicReadHandle(&pThis->hNativeOwner, &hNativeOwner);
    if (RT_UNLIKELY(hNativeOwner != hNativeSelf))
    {
        AssertMsgFailed(("Not owner of mutex %p!! hNativeSelf=%RTntrd Owner=%RTntrd cRecursions=%d\n",
                         pThis, hNativeSelf, hNativeOwner, pThis->cRecursions));
        return VERR_NOT_OWNER;
    }
    if (pThis->cRecursions > 1)
    {
#ifdef RTSEMMUTEX_STRICT
        int rc9 = RTLockValidatorRecExclUnwind(&pThis->ValidatorRec);
        if (RT_FAILURE(rc9))
            return rc9;
#endif
        ASMAtomicDecU32(&pThis->cRecursions);
        return VINF_SUCCESS;
    }

    /*
     * Unlock mutex semaphore.
     */
#ifdef RTSEMMUTEX_STRICT
    int rc9 = RTLockValidatorRecExclReleaseOwner(&pThis->ValidatorRec, false);
    if (RT_FAILURE(rc9))
        return rc9;
#endif
    ASMAtomicWriteU32(&pThis->cRecursions, 0);
    ASMAtomicWriteHandle(&pThis->hNativeOwner, NIL_RTNATIVETHREAD);

    if (ReleaseMutex(pThis->hMtx))
        return VINF_SUCCESS;

    int rc = RTErrConvertFromWin32(GetLastError());
    AssertMsgFailed(("%p/%p, rc=%Rrc lasterr=%d\n", pThis, pThis->hMtx, rc, GetLastError()));
    return rc;
}
示例#25
0
/**
 * Converts the given Windows error code to VBox handling unplugged devices.
 *
 * @returns VBox status code.
 * @param   pProxDev    The USB proxy device instance.
 * @param   dwErr       Windows error code.
 */
static int usbProxyWinHandleUnpluggedDevice(PUSBPROXYDEV pProxyDev, DWORD dwErr)
{
    PPRIV_USBW32 pPriv = USBPROXYDEV_2_DATA(pProxyDev, PPRIV_USBW32);

    if (   dwErr == ERROR_INVALID_HANDLE_STATE
        || dwErr == ERROR_BAD_COMMAND)
    {
        Log(("usbproxy: device %x unplugged!!\n", pPriv->hDev));
        pProxyDev->fDetached = true;
    }
    else
        AssertMsgFailed(("lasterr=%d\n", dwErr));
    return RTErrConvertFromWin32(dwErr);
}
示例#26
0
RTR3DECL(int)  RTFileGetSize(RTFILE hFile, uint64_t *pcbSize)
{
    /*
     * GetFileSize works for most handles.
     */
    ULARGE_INTEGER  Size;
    Size.LowPart = GetFileSize((HANDLE)RTFileToNative(hFile), &Size.HighPart);
    if (Size.LowPart != INVALID_FILE_SIZE)
    {
        *pcbSize = Size.QuadPart;
        return VINF_SUCCESS;
    }
    int rc = RTErrConvertFromWin32(GetLastError());

    /*
     * Could it be a volume or a disk?
     */
    DISK_GEOMETRY   DriveGeo;
    DWORD           cbDriveGeo;
    if (DeviceIoControl((HANDLE)RTFileToNative(hFile),
                        IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
                        &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
    {
        if (   DriveGeo.MediaType == FixedMedia
            || DriveGeo.MediaType == RemovableMedia)
        {
            *pcbSize = DriveGeo.Cylinders.QuadPart
                     * DriveGeo.TracksPerCylinder
                     * DriveGeo.SectorsPerTrack
                     * DriveGeo.BytesPerSector;

            GET_LENGTH_INFORMATION  DiskLenInfo;
            DWORD                   Ignored;
            if (DeviceIoControl((HANDLE)RTFileToNative(hFile),
                                IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
                                &DiskLenInfo, sizeof(DiskLenInfo), &Ignored, (LPOVERLAPPED)NULL))
            {
                /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
                *pcbSize = DiskLenInfo.Length.QuadPart;
            }
            return VINF_SUCCESS;
        }
    }

    /*
     * Return the GetFileSize result if not a volume/disk.
     */
    return rc;
}
示例#27
0
int VBoxSeamlessInit(const VBOXSERVICEENV *pEnv, void **ppInstance, bool *pfStartThread)
{
    Log(("VBoxTray: VBoxSeamlessInit\n"));

    *pfStartThread = false;
    gCtx.pEnv = pEnv;

    OSVERSIONINFO OSinfo;
    OSinfo.dwOSVersionInfoSize = sizeof (OSinfo);
    GetVersionEx (&OSinfo);

    int rc = VINF_SUCCESS;

    /* We have to jump out here when using NT4, otherwise it complains about
       a missing API function "UnhookWinEvent" used by the dynamically loaded VBoxHook.dll below */
    if (OSinfo.dwMajorVersion <= 4)         /* Windows NT 4.0 or older */
    {
        Log(("VBoxTray: VBoxSeamlessInit: Windows NT 4.0 or older not supported!\n"));
        rc = VERR_NOT_SUPPORTED;
    }
    else
    {
        /* Will fail if SetWinEventHook is not present (version < NT4 SP6 apparently) */
        gCtx.hModule = LoadLibrary(VBOXHOOK_DLL_NAME);
        if (gCtx.hModule)
        {
            *(uintptr_t *)&gCtx.pfnVBoxHookInstallWindowTracker = (uintptr_t)GetProcAddress(gCtx.hModule, "VBoxHookInstallWindowTracker");
            *(uintptr_t *)&gCtx.pfnVBoxHookRemoveWindowTracker  = (uintptr_t)GetProcAddress(gCtx.hModule, "VBoxHookRemoveWindowTracker");

            /* rc should contain success status */
            AssertRC(rc);

            VBoxSeamlessSetSupported(TRUE);

//            if (RT_SUCCESS(rc))
            {
                *pfStartThread = true;
                *ppInstance = &gCtx;
            }
        }
        else
        {
            rc = RTErrConvertFromWin32(GetLastError());
            Log(("VBoxTray: VBoxSeamlessInit: LoadLibrary of \"%s\" failed with rc=%Rrc\n", VBOXHOOK_DLL_NAME, rc));
        }
    }

    return rc;
}
static int rtCrStoreAddCertsFromNative(RTCRSTORE hStore, DWORD fStore, PCRTUTF16 pwszStoreName,
                                       PFNCERTOPENSTORE pfnOpenStore, PFNCERTCLOSESTORE pfnCloseStore,
                                       PFNCERTENUMCERTIFICATESINSTORE pfnEnumCerts, int rc, PRTERRINFO pErrInfo)
{
    DWORD fOpenStore = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG;
    HCERTSTORE hNativeStore = pfnOpenStore(CERT_STORE_PROV_SYSTEM_W, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
                                           NULL /* hCryptProv = default */, fStore | fOpenStore, pwszStoreName);
    if (hStore)
    {
        PCCERT_CONTEXT pCurCtx = NULL;
        while ((pCurCtx = pfnEnumCerts(hNativeStore, pCurCtx)) != NULL)
        {
            if (pCurCtx->dwCertEncodingType & X509_ASN_ENCODING)
            {
                RTERRINFOSTATIC StaticErrInfo;
                RTASN1CURSORPRIMARY PrimaryCursor;
                RTAsn1CursorInitPrimary(&PrimaryCursor, pCurCtx->pbCertEncoded, pCurCtx->cbCertEncoded,
                                        RTErrInfoInitStatic(&StaticErrInfo),
                                        &g_RTAsn1DefaultAllocator, RTASN1CURSOR_FLAGS_DER, "CurCtx");
                RTCRX509CERTIFICATE MyCert;
                int rc2 = RTCrX509Certificate_DecodeAsn1(&PrimaryCursor.Cursor, 0, &MyCert, "Cert");
                if (RT_SUCCESS(rc2))
                {
                    rc2 = RTCrStoreCertAddEncoded(hStore, RTCRCERTCTX_F_ENC_X509_DER | RTCRCERTCTX_F_ADD_IF_NOT_FOUND,
                                                  pCurCtx->pbCertEncoded, pCurCtx->cbCertEncoded,
                                                  RTErrInfoInitStatic(&StaticErrInfo));
                    RTCrX509Certificate_Delete(&MyCert);
                }
                if (RT_FAILURE(rc2))
                {
                    if (RTErrInfoIsSet(&StaticErrInfo.Core))
                        RTErrInfoAddF(pErrInfo, -rc2, "  %s", StaticErrInfo.Core.pszMsg);
                    else
                        RTErrInfoAddF(pErrInfo, -rc2, "  %Rrc adding cert", rc2);
                    rc = -rc2;
                }
            }
        }
        pfnCloseStore(hNativeStore, CERT_CLOSE_STORE_CHECK_FLAG);
    }
    else
    {
        DWORD uLastErr = GetLastError();
        if (uLastErr != ERROR_FILE_NOT_FOUND)
            rc = RTErrInfoAddF(pErrInfo, -RTErrConvertFromWin32(uLastErr),
                               " CertOpenStore(%#x,'%ls') failed: %u", fStore, pwszStoreName);
    }
    return rc;
}
示例#29
0
int CollectorWin::getRawHostCpuLoad(uint64_t *user, uint64_t *kernel, uint64_t *idle)
{
    LogFlowThisFuncEnter();

    FILETIME ftIdle, ftKernel, ftUser;

    if (mpfnGetSystemTimes)
    {
        if (!mpfnGetSystemTimes(&ftIdle, &ftKernel, &ftUser))
        {
            DWORD dwError = GetLastError();
            Log (("GetSystemTimes() -> 0x%x\n", dwError));
            return RTErrConvertFromWin32(dwError);
        }

        *user   = FILETTIME_TO_100NS(ftUser);
        *idle   = FILETTIME_TO_100NS(ftIdle);
        *kernel = FILETTIME_TO_100NS(ftKernel) - *idle;
    }
    else
    {
        /* GetSystemTimes is not available, fall back to NtQuerySystemInformation */
        if (!mpfnNtQuerySystemInformation)
            return VERR_NOT_IMPLEMENTED;

        SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION sppi[MAXIMUM_PROCESSORS];
        ULONG ulReturned;
        NTSTATUS status = mpfnNtQuerySystemInformation(
            SystemProcessorPerformanceInformation, &sppi, sizeof(sppi), &ulReturned);
        if (NT_ERROR(status))
        {
            Log(("NtQuerySystemInformation() -> 0x%x\n", status));
            return RTErrConvertFromNtStatus(status);
        }
        /* Sum up values across all processors */
        *user = *kernel = *idle = 0;
        for (unsigned i = 0; i < ulReturned / sizeof(sppi[0]); ++i)
        {
            *idle   += sppi[i].IdleTime.QuadPart;
            *kernel += sppi[i].KernelTime.QuadPart - sppi[i].IdleTime.QuadPart;
            *user   += sppi[i].UserTime.QuadPart;
        }
    }

    LogFlowThisFunc(("user=%lu kernel=%lu idle=%lu\n", *user, *kernel, *idle));
    LogFlowThisFuncLeave();

    return VINF_SUCCESS;
}
RTDECL(int) RTPathGetCurrentOnDrive(char chDrive, char *pszPath, size_t cbPath)
{
    WCHAR wszInput[4];
    wszInput[0] = chDrive;
    wszInput[1] = ':';
    wszInput[2] = '\0';

    int rc;
    RTUTF16 wszFullPath[RTPATH_MAX];
    if (GetFullPathNameW(wszInput, RTPATH_MAX, wszFullPath, NULL))
        rc = RTUtf16ToUtf8Ex(&wszFullPath[0], RTSTR_MAX, &pszPath, cbPath, NULL);
    else
        rc = RTErrConvertFromWin32(GetLastError());
    return rc;
}