Exemple #1
0
static
void
InitializeGeneralDriveDialog(HWND hwndDlg, WCHAR * szDrive)
{
   WCHAR szVolumeName[MAX_PATH+1] = {0};
   DWORD MaxComponentLength = 0;
   DWORD FileSystemFlags = 0;
   WCHAR FileSystemName[MAX_PATH+1] = {0};
   WCHAR szFormat[50];
   WCHAR szBuffer[128];
   BOOL ret;
   UINT DriveType;
   ULARGE_INTEGER FreeBytesAvailable;
   LARGE_INTEGER TotalNumberOfFreeBytes;
   LARGE_INTEGER TotalNumberOfBytes;

   ret = GetVolumeInformationW(szDrive, szVolumeName, MAX_PATH+1, NULL, &MaxComponentLength, &FileSystemFlags, FileSystemName, MAX_PATH+1);
   if (ret)
   {
      /* set volume label */
      SendDlgItemMessageW(hwndDlg, 14000, WM_SETTEXT, (WPARAM)NULL, (LPARAM)szVolumeName);

      /* set filesystem type */
      SendDlgItemMessageW(hwndDlg, 14002, WM_SETTEXT, (WPARAM)NULL, (LPARAM)FileSystemName);

   }

   DriveType = GetDriveTypeW(szDrive);
   if (DriveType == DRIVE_FIXED || DriveType == DRIVE_CDROM)
   {

      if(GetDiskFreeSpaceExW(szDrive, &FreeBytesAvailable, (PULARGE_INTEGER)&TotalNumberOfBytes, (PULARGE_INTEGER)&TotalNumberOfFreeBytes))
      {
         WCHAR szResult[128];
         LONGLONG Result;
         HANDLE hVolume;
         DWORD BytesReturned = 0;

         swprintf(szResult, L"\\\\.\\%c:", towupper(szDrive[0]));
         hVolume = CreateFileW(szResult, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
         if (hVolume != INVALID_HANDLE_VALUE)
         {
            ret = DeviceIoControl(hVolume, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, (LPVOID)&TotalNumberOfBytes, sizeof(ULARGE_INTEGER), &BytesReturned, NULL);
            if (ret && StrFormatByteSizeW(TotalNumberOfBytes.QuadPart, szResult, sizeof(szResult) / sizeof(WCHAR)))
               SendDlgItemMessageW(hwndDlg, 14007, WM_SETTEXT, (WPARAM)NULL, (LPARAM)szResult);

            CloseHandle(hVolume);
         }

         TRACE("szResult %s hVOlume %p ret %d LengthInformation %ul Bytesreturned %d\n", debugstr_w(szResult), hVolume, ret, TotalNumberOfBytes.QuadPart, BytesReturned);

         if (StrFormatByteSizeW(TotalNumberOfBytes.QuadPart - FreeBytesAvailable.QuadPart, szResult, sizeof(szResult) / sizeof(WCHAR)))
             SendDlgItemMessageW(hwndDlg, 14003, WM_SETTEXT, (WPARAM)NULL, (LPARAM)szResult);

         if (StrFormatByteSizeW(FreeBytesAvailable.QuadPart, szResult, sizeof(szResult) / sizeof(WCHAR)))
             SendDlgItemMessageW(hwndDlg, 14005, WM_SETTEXT, (WPARAM)NULL, (LPARAM)szResult);

         Result = GetFreeBytesShare(TotalNumberOfFreeBytes.QuadPart, TotalNumberOfBytes.QuadPart);
         /* set free bytes percentage */
         swprintf(szResult, L"%02d%%", Result);
         SendDlgItemMessageW(hwndDlg, 14006, WM_SETTEXT, (WPARAM)0, (LPARAM)szResult);
         /* store used share amount */
         Result = 100 - Result;
         swprintf(szResult, L"%02d%%", Result);
         SendDlgItemMessageW(hwndDlg, 14004, WM_SETTEXT, (WPARAM)0, (LPARAM)szResult);
         if (DriveType == DRIVE_FIXED)
         {
            if (LoadStringW(shell32_hInstance, IDS_DRIVE_FIXED, szBuffer, sizeof(szBuffer) / sizeof(WCHAR)))
               SendDlgItemMessageW(hwndDlg, 14001, WM_SETTEXT, (WPARAM)0, (LPARAM)szBuffer);
         }
         else /* DriveType == DRIVE_CDROM) */
         {
            if (LoadStringW(shell32_hInstance, IDS_DRIVE_CDROM, szBuffer, sizeof(szBuffer) / sizeof(WCHAR)))
               SendDlgItemMessageW(hwndDlg, 14001, WM_SETTEXT, (WPARAM)0, (LPARAM)szBuffer);
         }
      }
   }
   /* set drive description */
   SendDlgItemMessageW(hwndDlg, 14009, WM_GETTEXT, (WPARAM)50, (LPARAM)szFormat);
   swprintf(szBuffer, szFormat, szDrive);
   SendDlgItemMessageW(hwndDlg, 14009, WM_SETTEXT, (WPARAM)NULL, (LPARAM)szBuffer);
}
Exemple #2
0
extern void __declspec(dllexport) Open(PLUGINDATA *pd)
{
	INT_PTR res;
	DWORD_PTR* param;
	EDITINFO ei;
	BOOL bInsert = FALSE;
	pd->dwSupport |= PDS_NOANSI|PDS_NOAUTOLOAD;
	if(pd->dwSupport & PDS_GETSUPPORT)
		return;
	if(pd->bOldWindows)
	{
		pd->nUnload = UD_UNLOAD;
		return;
	}
	if(!g_bLoaded)
	{
		LoadPlugin(pd);
		if(!g_bLoaded)
		{
			pd->nUnload = UD_UNLOAD;
			return;
		}
	}
	g_nLock++;
	ei.hWndEdit = NULL;
	if(SendMessageW(g_hMainWnd,AKD_GETEDITINFO,0,(LPARAM)&ei))
	{
		if(ei.hWndEdit && ei.wszFile)
			bInsert = !ei.bReadOnly;
	}
	param = (DWORD_PTR*)pd->lParam;
	if(	param
		&& (param[0]==3*sizeof(DWORD_PTR))
		&& (param[1]==OPEN_FUNCTION_OPEN
			|| param[1]==OPEN_FUNCTION_EDIT
			|| param[1]==OPEN_FUNCTION_INSERT)
		&& param[2])
	{
		LPCWSTR p = (LPCWSTR)param[2];
		res = (param[1]==OPEN_FUNCTION_OPEN)
					?(IDOK)
					:((param[1]==OPEN_FUNCTION_EDIT)
							?IDC_EDIT:
							IDC_INSERT);
		if(p[0])
		{
			lstrcpyW(g_szTemplate,g_szAkelPath);
			lstrcatW(g_szTemplate,TEMPLATES_PATH);
			lstrcatW(g_szTemplate,L"\\");
			lstrcatW(g_szTemplate,p);
		}
		else g_szTemplate[0] = 0;
		if(res==IDC_EDIT)
		{
			HANDLE h = CreateFileW(g_szTemplate,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
			if(h == INVALID_HANDLE_VALUE)
			{
				res = IDCANCEL;
			}
			else
			{
				CloseHandle(h);
			}
		}
		else if((res == IDC_INSERT) && (!bInsert))
		{
			res = IDCANCEL;
		}
	}
	else
	{
		res = DialogBoxParamW(g_hDll,MAKEINTRESOURCEW(IDD_TEMPLATE),g_hMainWnd,(DLGPROC)TemplateDlg,(LPARAM)DCP_ALLOWEDIT|(bInsert?DCP_ALLOWINSERT:0));
	}
	if(IDOK == res || IDC_EDIT == res || IDC_INSERT == res)
	{
		if(g_bMainReady)
		{
			g_bInternalNew = TRUE;
		}
		if(res == IDC_EDIT)
		{
			EditTemplate(FALSE);
		}
		else if(res == IDOK)
		{
			ei.hWndEdit = NULL;
			if(SendMessageW(g_hMainWnd,AKD_GETEDITINFO,0,(LPARAM)&ei))
			{
				if(!ei.hWndEdit || ei.bModified || ei.wszFile[0])
				{
					if(SendMessageW(g_hMainWnd,WM_COMMAND,MAKEWPARAM(IDM_FILE_NEW,0),TRUE))
					{
						SendMessageW(g_hMainWnd,AKD_GETEDITINFO,0,(LPARAM)&ei);
					}
				}
			}
			else if(g_nMDI == WMD_MDI)
			{
				if(SendMessageW(g_hMainWnd,WM_COMMAND,MAKEWPARAM(IDM_FILE_NEW,0),TRUE))
				{
					SendMessageW(g_hMainWnd,AKD_GETEDITINFO,0,(LPARAM)&ei);
				}
			}
			if(ei.hWndEdit && !((g_nMDI == WMD_SDI)&&(ei.bModified)))
			{
				OpenTemplate(ei.hWndEdit,FALSE);
			}
		}
		else if(res == IDC_INSERT)
		{
			if(SendMessageW(g_hMainWnd,AKD_GETEDITINFO,0,(LPARAM)&ei))
			{
				if(ei.hWndEdit)
				{
					OpenTemplate(ei.hWndEdit,TRUE);
				}
			}
		}
		if(g_bMainReady)
		{
			g_bInternalNew = FALSE;
		}
	}
	g_nLock--;
	pd->nUnload = (g_nLock)?UD_NONUNLOAD_NONACTIVE:UD_UNLOAD;
	if(!g_nLock) UnloadPlugin(pd);
}
Exemple #3
0
static void CALLCONV OpenTemplate(HWND hWnd, BOOL bInsert)
{
	LRESULT			res = 0;
	LRESULT			pos = 0;
	TEXTFINDW		tf = {FRF_BEGINNING|FRF_DOWN|FRF_MATCHCASE,CARETPOSMARKER,-1};
	TEXTREPLACEW	tr = {FRF_BEGINNING|FRF_DOWN|FRF_MATCHCASE,CARETPOSMARKER,-1,L"",0,TRUE,0};
	DETECTFILEW	dc = {g_szTemplate,1024,ADT_BINARY_ERROR|ADT_DETECT_BOM|ADT_DETECT_CODEPAGE,0,FALSE};
	if(g_szTemplate[0]/*!<EMPTY>*/ && (EDT_SUCCESS == SendMessageW(g_hMainWnd, AKD_DETECTFILEW,0,(LPARAM)&dc)))
	{
		HANDLE hFile = CreateFileW(g_szTemplate, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);
		if(hFile != INVALID_HANDLE_VALUE/*always TRUE if we are here*/)
		{
			FILECONTENT fc;
			LRESULT lSize = 0;
			PLG_CHARRANGE cursel = {0,0};
			fc.hFile = hFile;
			fc.dwMax = (UINT_PTR)-1;
			fc.nCodePage = dc.nCodePage;
			fc.bBOM = dc.bBOM;
			fc.wpContent = NULL;
			if(lSize = SendMessageW(g_hMainWnd,AKD_READFILECONTENT,0,(LPARAM)&fc))
			{
				LPCWSTR pText = SplitTemplate(fc.wpContent);
				tf.pFindIt = fc.wpContent;
				tr.pFindIt = fc.wpContent;
				lSize -= pText - fc.wpContent;
				if(*pText)
				{
					if(!bInsert)
					{
						SendMessageW(hWnd,EM_SETSEL,(WPARAM)0,(LPARAM)-1);
					}
					else if(g_bRemoveMarker)
					{
						//! Store selection for future
						SendMessageW(hWnd, PEM_EXGETSEL,0,(LPARAM)&cursel);
					}
					//! Insert text
					SendMessageW(hWnd,EM_REPLACESEL,(WPARAM)FALSE,(LPARAM)pText);
					if(!bInsert)
					{
						//! Find first cursor position
						res = SendMessageW(g_hMainWnd, AKD_TEXTFINDW, (WPARAM)hWnd, (LPARAM)&tf);
						if(res != -1) pos = res;
						if(g_bRemoveMarker)
						{
							//! Remove all caret markers
							SendMessageW(g_hMainWnd, AKD_TEXTREPLACEW, (WPARAM)hWnd, (LPARAM)&tr);
						}
						//! Put caret there
						SendMessageW(hWnd,EM_SETSEL,(WPARAM)pos,(LPARAM)pos);
						if(g_bCPFT)
						{
							SAVEDOCUMENTW sd = {L"",fc.nCodePage,fc.bBOM,SD_UPDATE};
							SendMessageW(g_hMainWnd,AKD_SAVEDOCUMENTW,(WPARAM)hWnd,(LPARAM)&sd);
						}
						//! Reset modification flag
						SendMessageW(g_hMainWnd, AKD_SETMODIFY,(WPARAM)hWnd,(LPARAM)FALSE);
					}
					else if(bInsert && g_bRemoveMarker)
					//! User requested to remove markers
					{
						//! Mark newly inserted text
						cursel.cpMax = cursel.cpMin + lSize;
						SendMessageW(hWnd,PEM_EXSETSEL,0,(LPARAM)&cursel);
						tr.dwFlags = FRF_SELECTION|FRF_DOWN|FRF_MATCHCASE;
						//! Remove all markers
						SendMessageW(g_hMainWnd,AKD_TEXTREPLACEW,(WPARAM)hWnd,(LPARAM)&tr);
						//! Put caret after inserted text
						SendMessageW(hWnd, PEM_EXGETSEL,0,(LPARAM)&cursel);
						cursel.cpMin = cursel.cpMax;
						SendMessageW(hWnd, PEM_EXSETSEL,0,(LPARAM)&cursel);
					}
				}
				else
				{
					//! Empty template - do "nothing" i.e. only insert text, do not try to deal with markers
					SendMessageW(hWnd,EM_REPLACESEL,(WPARAM)FALSE,(LPARAM)pText);
				}
				//! Call Coder only on creation and on insertion if no theme assigned yet
				if((!bInsert) || (g_bHighLightAtInsert && IsHighLightThemeAssigned(hWnd)))
				{
					CallCoder(g_szTemplate);
				}
				SendMessageW(g_hMainWnd, AKD_FREETEXT,0,(LPARAM)fc.wpContent);
				if(bInsert)
				{
					SendMessageW(g_hMainWnd, AKD_SETMODIFY,(WPARAM)hWnd,(LPARAM)TRUE);
				}
			}
			CloseHandle(hFile);
		}
	}
}
Exemple #4
0
static
DWORD WINAPI
ThreadFunc(LPVOID Context)
{
    CComPtr<IBindStatusCallback> dl;
    WCHAR path[MAX_PATH];
    PWSTR p, q;
    HWND Dlg = (HWND) Context;
    ULONG dwContentLen, dwBytesWritten, dwBytesRead, dwStatus;
    ULONG dwCurrentBytesRead = 0;
    ULONG dwStatusLen = sizeof(dwStatus);
    BOOL bCancelled = FALSE;
    BOOL bTempfile = FALSE;
    BOOL bCab = FALSE;
    HINTERNET hOpen = NULL;
    HINTERNET hFile = NULL;
    HANDLE hOut = INVALID_HANDLE_VALUE;
    unsigned char lpBuffer[4096];
    PCWSTR lpszAgent = L"RApps/1.0";
    URL_COMPONENTS urlComponents;
    size_t urlLength, filenameLength;

    /* build the path for the download */
    p = wcsrchr(AppInfo->szUrlDownload, L'/');
    q = wcsrchr(AppInfo->szUrlDownload, L'?');
 
    /* do we have a final slash separator? */
    if (!p)
        goto end;

    /* prepare the tentative length of the filename, maybe we've to remove part of it later on */
    filenameLength = wcslen(p) * sizeof(WCHAR);

    /* do we have query arguments in the target URL after the filename? account for them
      (e.g. https://example.org/myfile.exe?no_adware_plz) */
    if (q && q > p && (q - p) > 0)
        filenameLength -= wcslen(q - 1) * sizeof(WCHAR);

    /* is this URL an update package for RAPPS? if so store it in a different place */
    if (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0)
    {
        bCab = TRUE;
        if (!GetStorageDirectory(path, _countof(path)))
            goto end;
    }
    else
    {
        if (FAILED(StringCbCopyW(path, sizeof(path),  SettingsInfo.szDownloadDir)))
            goto end;
    }

    /* is the path valid? can we access it? */
    if (GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES)
    {
        if (!CreateDirectoryW(path, NULL))
            goto end;
    }

    /* append a \ to the provided file system path, and the filename portion from the URL after that */
    if (FAILED(StringCbCatW(path, sizeof(path), L"\\")))
        goto end;
    if (FAILED(StringCbCatNW(path, sizeof(path), p + 1, filenameLength)))
        goto end;

    if (!bCab && AppInfo->szSHA1[0] != 0 && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES)
    {
        /* only open it in case of total correctness */
        if (VerifyInteg(AppInfo->szSHA1, path))
            goto run;
    }

    /* download it */
    bTempfile = TRUE;
    CDownloadDialog_Constructor(Dlg, &bCancelled, IID_PPV_ARG(IBindStatusCallback, &dl));

    if (dl == NULL)
        goto end;

    /* FIXME: this should just be using the system-wide proxy settings */
    switch(SettingsInfo.Proxy)
    {
        case 0: /* preconfig */
            hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
            break;
        case 1: /* direct (no proxy) */
            hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
            break;
        case 2: /* use proxy */
            hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PROXY, SettingsInfo.szProxyServer, SettingsInfo.szNoProxyFor, 0);
            break;
        default: /* preconfig */
            hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
            break;
    }

    if (!hOpen)
        goto end;

    hFile = InternetOpenUrlW(hOpen, AppInfo->szUrlDownload, NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_KEEP_CONNECTION, 0);
    if (!hFile)
        goto end;

    if (!HttpQueryInfoW(hFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwStatusLen, NULL))
        goto end;

    if(dwStatus != HTTP_STATUS_OK)
    {
        WCHAR szMsgText[MAX_STR_LEN];

        if (!LoadStringW(hInst, IDS_UNABLE_TO_DOWNLOAD, szMsgText, sizeof(szMsgText) / sizeof(WCHAR)))
            goto end;

        MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR);
        goto end;
    }

    dwStatusLen = sizeof(dwStatus);

    memset(&urlComponents, 0, sizeof(urlComponents));
    urlComponents.dwStructSize = sizeof(urlComponents);

    if(FAILED(StringCbLengthW(AppInfo->szUrlDownload, sizeof(AppInfo->szUrlDownload), &urlLength)))
        goto end;

    urlLength /= sizeof(WCHAR);
    urlComponents.dwSchemeLength = urlLength + 1;
    urlComponents.lpszScheme = (LPWSTR)malloc(urlComponents.dwSchemeLength * sizeof(WCHAR));
    urlComponents.dwHostNameLength = urlLength + 1;
    urlComponents.lpszHostName = (LPWSTR)malloc(urlComponents.dwHostNameLength * sizeof(WCHAR));

    if(!InternetCrackUrlW(AppInfo->szUrlDownload, urlLength+1, ICU_DECODE | ICU_ESCAPE, &urlComponents))
        goto end;
    
    if(urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS)
        HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatus, 0);

    if(urlComponents.nScheme == INTERNET_SCHEME_FTP)
        dwContentLen = FtpGetFileSize(hFile, &dwStatus);

#ifdef USE_CERT_PINNING
    /* are we using HTTPS to download the RAPPS update package? check if the certificate is original */
    if ((urlComponents.nScheme == INTERNET_SCHEME_HTTPS) &&
        (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0) &&
        (!CertIsValid(hOpen, urlComponents.lpszHostName)))
    {
        WCHAR szMsgText[MAX_STR_LEN];

        if (!LoadStringW(hInst, IDS_CERT_DOES_NOT_MATCH, szMsgText, sizeof(szMsgText) / sizeof(WCHAR)))
            goto end;

        MessageBoxW(Dlg, szMsgText, NULL, MB_OK | MB_ICONERROR);
        goto end;
    }
#endif

    free(urlComponents.lpszScheme);
    free(urlComponents.lpszHostName);

    hOut = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);

    if (hOut == INVALID_HANDLE_VALUE)
        goto end;

    do
    {
        if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead))
        {
            WCHAR szMsgText[MAX_STR_LEN];

            if (!LoadStringW(hInst, IDS_INTERRUPTED_DOWNLOAD, szMsgText, _countof(szMsgText)))
                goto end;

            MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR);
            goto end;
        }
        if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL))
        {
            WCHAR szMsgText[MAX_STR_LEN];

            if (!LoadStringW(hInst, IDS_UNABLE_TO_WRITE, szMsgText, _countof(szMsgText)))
                goto end;

            MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR);
            goto end;
        }
        dwCurrentBytesRead += dwBytesRead;
        dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, AppInfo->szUrlDownload);
    }
    while (dwBytesRead && !bCancelled);

    CloseHandle(hOut);
    hOut = INVALID_HANDLE_VALUE;

    if (bCancelled)
        goto end;

    /* if this thing isn't a RAPPS update and it has a SHA-1 checksum
       verify its integrity by using the native advapi32.A_SHA1 functions */
    if (!bCab && AppInfo->szSHA1[0] != 0)
    {
        WCHAR szMsgText[MAX_STR_LEN];

        /* change a few strings in the download dialog to reflect the verification process */
        LoadStringW(hInst, IDS_INTEG_CHECK_TITLE, szMsgText, _countof(szMsgText));

        SetWindowText(Dlg, szMsgText);
        SendMessageW(GetDlgItem(Dlg, IDC_DOWNLOAD_STATUS), WM_SETTEXT, 0, (LPARAM)path);

        /* this may take a while, depending on the file size */
        if (!VerifyInteg(AppInfo->szSHA1, path))
        {
            if (!LoadStringW(hInst, IDS_INTEG_CHECK_FAIL, szMsgText, _countof(szMsgText)))
                goto end;

            MessageBoxW(Dlg, szMsgText, NULL, MB_OK | MB_ICONERROR);
            goto end;
        }
    }

    ShowWindow(Dlg, SW_HIDE);

run:
    /* run it */
    if (!bCab)
        ShellExecuteW( NULL, L"open", path, NULL, NULL, SW_SHOWNORMAL );

end:
    if (hOut != INVALID_HANDLE_VALUE)
        CloseHandle(hOut);

    InternetCloseHandle(hFile);
    InternetCloseHandle(hOpen);

    if (bTempfile)
    {
        if (bCancelled || (SettingsInfo.bDelInstaller && !bCab))
            DeleteFileW(path);
    }

    EndDialog(Dlg, 0);

    return 0;
}
Exemple #5
0
/*
 * __win_open_file --
 *	Open a file handle.
 */
static int
__win_open_file(WT_FILE_SYSTEM *file_system, WT_SESSION *wt_session,
    const char *name, WT_FS_OPEN_FILE_TYPE file_type, uint32_t flags,
    WT_FILE_HANDLE **file_handlep)
{
	DWORD dwCreationDisposition, windows_error;
	WT_CONNECTION_IMPL *conn;
	WT_DECL_RET;
	WT_DECL_ITEM(name_wide);
	WT_FILE_HANDLE *file_handle;
	WT_FILE_HANDLE_WIN *win_fh;
	WT_SESSION_IMPL *session;
	int desired_access, f;

	WT_UNUSED(file_system);
	session = (WT_SESSION_IMPL *)wt_session;
	conn = S2C(session);
	*file_handlep = NULL;

	WT_RET(__wt_calloc_one(session, &win_fh));
	win_fh->direct_io = false;

	/* Set up error handling. */
	win_fh->filehandle =
	    win_fh->filehandle_secondary = INVALID_HANDLE_VALUE;

	WT_ERR(__wt_to_utf16_string(session, name, &name_wide));

	/*
	 * Opening a file handle on a directory is only to support filesystems
	 * that require a directory sync for durability, and Windows doesn't
	 * require that functionality: create an empty WT_FH structure with
	 * invalid handles.
	 */
	if (file_type == WT_FS_OPEN_FILE_TYPE_DIRECTORY)
		goto directory_open;

	desired_access = GENERIC_READ;
	if (!LF_ISSET(WT_FS_OPEN_READONLY))
		desired_access |= GENERIC_WRITE;

	/*
	 * Security:
	 * The application may spawn a new process, and we don't want another
	 * process to have access to our file handles.
	 *
	 * TODO: Set tighter file permissions but set bInheritHandle to false
	 * to prevent inheritance
	 */
	f = FILE_ATTRIBUTE_NORMAL;

	dwCreationDisposition = 0;
	if (LF_ISSET(WT_FS_OPEN_CREATE)) {
		dwCreationDisposition = CREATE_NEW;
		if (LF_ISSET(WT_FS_OPEN_EXCLUSIVE))
			dwCreationDisposition = CREATE_ALWAYS;
	} else
		dwCreationDisposition = OPEN_EXISTING;

	/* Direct I/O. */
	if (LF_ISSET(WT_FS_OPEN_DIRECTIO)) {
		f |= FILE_FLAG_NO_BUFFERING;
		win_fh->direct_io = true;
	}

	/* FILE_FLAG_WRITE_THROUGH does not require aligned buffers */
	if (FLD_ISSET(conn->write_through, file_type))
		f |= FILE_FLAG_WRITE_THROUGH;

	if (file_type == WT_FS_OPEN_FILE_TYPE_LOG &&
	    FLD_ISSET(conn->txn_logsync, WT_LOG_DSYNC))
		f |= FILE_FLAG_WRITE_THROUGH;

	/* Disable read-ahead on trees: it slows down random read workloads. */
	if (file_type == WT_FS_OPEN_FILE_TYPE_DATA)
		f |= FILE_FLAG_RANDOM_ACCESS;

	win_fh->filehandle = CreateFileW(name_wide->data, desired_access,
	    FILE_SHARE_READ | FILE_SHARE_WRITE,
	    NULL, dwCreationDisposition, f, NULL);
	if (win_fh->filehandle == INVALID_HANDLE_VALUE) {
		if (LF_ISSET(WT_FS_OPEN_CREATE) &&
		    GetLastError() == ERROR_FILE_EXISTS)
			win_fh->filehandle = CreateFileW(name_wide->data,
			    desired_access, FILE_SHARE_READ | FILE_SHARE_WRITE,
			    NULL, OPEN_EXISTING, f, NULL);
		if (win_fh->filehandle == INVALID_HANDLE_VALUE) {
			windows_error = __wt_getlasterror();
			__wt_errx(session,
			    win_fh->direct_io ?
			    "%s: handle-open: CreateFileW: failed with direct "
			    "I/O configured, some filesystem types do not "
			    "support direct I/O: %s" :
			    "%s: handle-open: CreateFileW: %s",
			    name, __wt_formatmessage(session, windows_error));
			WT_ERR(__wt_map_windows_error(windows_error));
		}
	}

	/*
	 * Open a second handle to file to support file extension/truncation
	 * concurrently with reads on the file. Writes would also move the
	 * file pointer.
	 */
	if (!LF_ISSET(WT_FS_OPEN_READONLY)) {
		win_fh->filehandle_secondary = CreateFileW(name_wide->data,
		    desired_access, FILE_SHARE_READ | FILE_SHARE_WRITE,
		    NULL, OPEN_EXISTING, f, NULL);
		if (win_fh->filehandle_secondary == INVALID_HANDLE_VALUE) {
			windows_error = __wt_getlasterror();
			__wt_errx(session,
			    "%s: handle-open: Creatively: secondary: %s",
			    name, __wt_formatmessage(session, windows_error));
			WT_ERR(__wt_map_windows_error(windows_error));
		}
	}

directory_open:
	/* Initialize public information. */
	file_handle = (WT_FILE_HANDLE *)win_fh;
	WT_ERR(__wt_strdup(session, name, &file_handle->name));

	file_handle->close = __win_file_close;
	file_handle->fh_lock = __win_file_lock;
#ifdef WORDS_BIGENDIAN
	/*
	 * The underlying objects are little-endian, mapping objects isn't
	 * currently supported on big-endian systems.
	 */
#else
	file_handle->fh_map = __wt_win_map;
	file_handle->fh_unmap = __wt_win_unmap;
#endif
	file_handle->fh_read = __win_file_read;
	file_handle->fh_size = __win_file_size;
	file_handle->fh_sync = __win_file_sync;

	/* Extend and truncate share the same implementation. */
	file_handle->fh_extend = __win_file_set_end;
	file_handle->fh_truncate = __win_file_set_end;

	file_handle->fh_write = __win_file_write;

	*file_handlep = file_handle;

	__wt_scr_free(session, &name_wide);
	return (0);

err:	__wt_scr_free(session, &name_wide);
	WT_TRET(__win_file_close((WT_FILE_HANDLE *)win_fh, wt_session));
	return (ret);
}
Exemple #6
0
bool LocateConverter::LocateUpdate(const wchar_t *locate, const wchar_t *patch, const wchar_t *path, bool compress/* = false */, OnProgress progress/* = NULL */)
{
    LocateReader loc(locate);
    if ( !loc.IsAvailable() ) return false;

    const uint8_t *diff_buffer = 0;
    PDIFFHEADER diff_header = 0;

    HANDLE hfile = CreateFileW(patch, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if(hfile!=INVALID_HANDLE_VALUE)
    {
        uint32_t file_length = GetFileSize(hfile, NULL);

        HANDLE hfilemap = CreateFileMapping(hfile, NULL, PAGE_READONLY, 0, 0, NULL);
        CloseHandle(hfile);

        diff_buffer = (const uint8_t*) MapViewOfFile(hfilemap, FILE_MAP_READ, 0, 0, 0);
        CloseHandle(hfilemap);

        diff_header = (PDIFFHEADER)diff_buffer;
        int data_size = file_length - sizeof(DIFFHEADER) - LZMA_PROPS_SIZE;
        if( data_size<0 || diff_header->magic != DIFF_MAGIC || CRC32_MEM(diff_buffer, sizeof(DIFFHEADER) - 4)!=diff_header->crc32 )
        {
            UnmapViewOfFile((void*)diff_buffer);
            return false;
        }
        else
        {
            uint32_t lzma_buffer_len = diff_header->size;
            uint8_t *lzma_buffer = (uint8_t *)malloc(sizeof(DIFFHEADER) + lzma_buffer_len);

            if( LzmaUncompress(lzma_buffer + sizeof(DIFFHEADER), &lzma_buffer_len, (unsigned char*)diff_header->data + LZMA_PROPS_SIZE, (uint32_t*)&data_size, (unsigned char*)diff_header->data, LZMA_PROPS_SIZE)==SZ_OK )
            {
                memcpy(lzma_buffer, diff_buffer, sizeof(DIFFHEADER));
                UnmapViewOfFile((void*)diff_buffer);
                diff_buffer = lzma_buffer;

                diff_header = (PDIFFHEADER)diff_buffer;
                diff_header->table1 += (uint32_t)diff_buffer;
                diff_header->table2 += (uint32_t)diff_buffer;
            }
            else
            {
                free(lzma_buffer);
                UnmapViewOfFile((void*)diff_buffer);
                return false;
            }
        }
    }
    else
    {
        return false;
    }

    if ( loc.GetInfo()->count!=diff_header->total1 || loc.GetInfo()->time!=diff_header->time1 ) return false;

    PDIFFITEM diffitem = diff_header->data;
    LocateItem *Locate = (LocateItem *)malloc( diff_header->total2 * sizeof(LocateItem) );

    uint32_t last_diff = ( diff_header->table1 - sizeof(DIFFHEADER) - (uint32_t)diff_buffer ) / sizeof(DIFFITEM) - 1;
    uint32_t last_line = diff_header->total2 - 1;

    uint32_t i = loc.GetInfo()->count;
    for(; i>0; i--)
    {
        LocateItem *item = loc.GetItem(i);

        if(i!=diffitem[last_diff].line)
        {
            Locate[last_line].begin_ip = item->begin_ip;
            Locate[last_line].region = item->region;
            Locate[last_line].address = item->address;
            last_line--;
        }
        else
        {
            switch(diffitem[last_diff].method)
            {
            case INSERT:
                //printf("INSERT %d %d\n", i, diffitem[last_diff-1].line);
                Locate[last_line].begin_ip = diffitem[last_diff].begin_ip;
                Locate[last_line].region = (const char*)( diffitem[last_diff].table1 + diff_header->table1 );
                Locate[last_line].address = (const char*)( diffitem[last_diff].table2 + diff_header->table2 );
                last_line--;
                i++;
                break;
            case REMOVE:
                //printf("REMOVE %d %d %d\n", i, diffitem[last_diff-1].line, diffitem[last_diff-2].line);
                break;
            case MODIFY:
                Locate[last_line].begin_ip = item->begin_ip;
                Locate[last_line].region = (const char*)( diffitem[last_diff].table1 + diff_header->table1 );
                Locate[last_line].address = (const char*)( diffitem[last_diff].table2 + diff_header->table2 );
                //printf("MODIFY %d %s %s\n", last_line+1, Locate[last_line].region, Locate[last_line].address);
                //getchar();
                last_line--;
                break;
            }
            last_diff--;
        }
    }

    //printf("%d %d\n",last_diff,last_line);
    if ( last_diff!=-1 || last_line!=-1 ) return false;

    StringTable string_table1;
    StringTable string_table2;
    RecordTable record_table;

    Buffer buffer;

    uint32_t last_begin_ip = 0;

    for(i=last_line+1; i<diff_header->total2; i++)
    {
        LocateItem *item = &Locate[i];

        LOCATE record;
        record.begin_ip = item->begin_ip;
        record.table1 = string_table1.Append(item->region);
        record.table2 = string_table2.Append(item->address);

        if ( i > 0 )
        {
            uint32_t diff = record.begin_ip - last_begin_ip;
            if ( compress && isPowerOf2(diff) )
            {
                record.begin_ip = LogBase2(diff);
            }
        }

        record_table.Append(&record);

        last_begin_ip = item->begin_ip;
    }
    free(Locate);

    //合并数据区
    Buffer *record_table_buffer = record_table;
    Buffer *string_table1_buffer = string_table1;
    Buffer *string_table2_buffer = string_table2;

    std::copy(record_table_buffer->begin(), record_table_buffer->end(), std::back_inserter(buffer));
    std::copy(string_table1_buffer->begin(), string_table1_buffer->end(), std::back_inserter(buffer));
    std::copy(string_table2_buffer->begin(), string_table2_buffer->end(), std::back_inserter(buffer));

    //生成文件头
    HEADER header;
    header.magic = LOCATE_MAGIC;
    header.version = LOCATE_VERISON;
    header.compress = compress?1:0;
    header.total = diff_header->total2;
    header.time = diff_header->time2;

    header.table1 = sizeof(header) + record_table_buffer->size(); // 这里不加LZMA_PROPS_SIZE的原因是解压后,抛弃props信息
    header.table2 = header.table1 + string_table1_buffer->size();
    header.size = buffer.size();
    header.crc32 = CRC32_MEM((uint8_t*)&header, sizeof(header) - 4);

    uint32_t lzma_buffer_len = buffer.size();
    uint8_t *lzma_buffer = 0;

    size_t prop_size = LZMA_PROPS_SIZE;
    BYTE outProps[LZMA_PROPS_SIZE];

    //准备压缩
    if(compress)
    {
        lzma_buffer = (uint8_t *)malloc(lzma_buffer_len);
        
        ProgressCallback LzmaCompressProgress;
        LzmaCompressProgress.Progress = LzmaOnProgress;
        LzmaCompressProgress.totalInSize = buffer.size();
        LzmaCompressProgress.progress = progress;
        LzmaCompress(lzma_buffer, &lzma_buffer_len, &buffer[0], buffer.size(), (ICompressProgress*)&LzmaCompressProgress, outProps, &prop_size, 5, 1<<27, 8, 0, 2, 64, 4);
    }

    //保存文件
    FILE * out = _wfopen(path, L"wb");
    fwrite(&header, 1, sizeof(header), out);

    if(compress)
    {
        fwrite(outProps, 1, sizeof(outProps), out);
        fwrite(lzma_buffer, 1, lzma_buffer_len, out);
    }
    else
    {
        fwrite(&buffer[0], 1, buffer.size(), out);
    }
    fclose(out);

    if(compress)
    {
        free(lzma_buffer);
    }

    free((void*)diff_buffer);
    return true;
}
Exemple #7
0
    void* MemoryMappedFile::map(const char *filenameIn, unsigned long long &length, int options) {
        verify( fd == 0 && len == 0 ); // can't open more than once
        setFilename(filenameIn);
        FileAllocator::get()->allocateAsap( filenameIn, length );
        /* big hack here: Babble uses db names with colons.  doesn't seem to work on windows.  temporary perhaps. */
        char filename[256];
        strncpy(filename, filenameIn, 255);
        filename[255] = 0;
        {
            size_t len = strlen( filename );
            for ( size_t i=len-1; i>=0; i-- ) {
                if ( filename[i] == '/' ||
                        filename[i] == '\\' )
                    break;

                if ( filename[i] == ':' )
                    filename[i] = '_';
            }
        }

        updateLength( filename, length );

        {
            DWORD createOptions = FILE_ATTRIBUTE_NORMAL;
            if ( options & SEQUENTIAL )
                createOptions |= FILE_FLAG_SEQUENTIAL_SCAN;
            DWORD rw = GENERIC_READ | GENERIC_WRITE;
            fd = CreateFileW(
                     toWideString(filename).c_str(),
                     rw, // desired access
                     FILE_SHARE_WRITE | FILE_SHARE_READ, // share mode
                     NULL, // security
                     OPEN_ALWAYS, // create disposition
                     createOptions , // flags
                     NULL); // hTempl
            if ( fd == INVALID_HANDLE_VALUE ) {
                DWORD dosError = GetLastError();
                log() << "CreateFileW for " << filename
                        << " failed with " << errnoWithDescription( dosError )
                        << " (file size is " << length << ")"
                        << " in MemoryMappedFile::map"
                        << endl;
                return 0;
            }
        }

        mapped += length;

        {
            DWORD flProtect = PAGE_READWRITE; //(options & READONLY)?PAGE_READONLY:PAGE_READWRITE;
            maphandle = CreateFileMappingW(fd, NULL, flProtect,
                                          length >> 32 /*maxsizehigh*/,
                                          (unsigned) length /*maxsizelow*/,
                                          NULL/*lpName*/);
            if ( maphandle == NULL ) {
                DWORD dosError = GetLastError();
                log() << "CreateFileMappingW for " << filename
                        << " failed with " << errnoWithDescription( dosError )
                        << " (file size is " << length << ")"
                        << " in MemoryMappedFile::map"
                        << endl;
                close();
                fassertFailed( 16225 );
            }
        }

        void *view = 0;
        {
            stdx::lock_guard<stdx::mutex> lk(mapViewMutex);
            DWORD access = ( options & READONLY ) ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS;

            int current_retry = 0;
            while (true) {

                LPVOID thisAddress = getNextMemoryMappedFileLocation(length);

                view = MapViewOfFileEx(
                    maphandle,      // file mapping handle
                    access,         // access
                    0, 0,           // file offset, high and low
                    0,              // bytes to map, 0 == all
                    thisAddress);  // address to place file

                if (view == 0) {
                    DWORD dosError = GetLastError();

                    ++current_retry;

                    // If we failed to allocate a memory mapped file, try again in case we picked
                    // an address that Windows is also trying to use for some other VM allocations
                    if (dosError == ERROR_INVALID_ADDRESS && current_retry < 5) {
                        continue;
                    }

#ifndef _WIN64
                    // Warn user that if they are running a 32-bit app on 64-bit Windows
                    if (dosError == ERROR_NOT_ENOUGH_MEMORY) {
                        BOOL wow64Process;
                        BOOL retWow64 = IsWow64Process(GetCurrentProcess(), &wow64Process);
                        if (retWow64 && wow64Process) {
                            log() << "This is a 32-bit MongoDB binary running on a 64-bit"
                                " operating system that has run out of virtual memory for"
                                " databases. Switch to a 64-bit build of MongoDB to open"
                                " the databases.";
                        }
                    }
#endif

                    log() << "MapViewOfFileEx for " << filename
                        << " at address " << thisAddress
                        << " failed with " << errnoWithDescription(dosError)
                        << " (file size is " << length << ")"
                        << " in MemoryMappedFile::map"
                        << endl;

                    close();
                    fassertFailed(16166);
                }

                break;
            }
        }

        views.push_back(view);
        len = length;
        return view;
    }
void bad()
{
    wchar_t * data;
    wchar_t * *dataPtr1 = &data;
    wchar_t * *dataPtr2 = &data;
    wchar_t dataBuffer[FILENAME_MAX] = L"";
    data = dataBuffer;
    {
        wchar_t * data = *dataPtr1;
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            wchar_t *replace;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            size_t dataLen = wcslen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
                /* Eliminate CRLF */
                replace = wcschr(data, L'\r');
                if (replace)
                {
                    *replace = L'\0';
                }
                replace = wcschr(data, L'\n');
                if (replace)
                {
                    *replace = L'\0';
                }
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
        *dataPtr1 = data;
    }
    {
        wchar_t * data = *dataPtr2;
        {
            HANDLE hFile;
            /* POTENTIAL FLAW: Possibly creating and opening a file without validating the file name or path */
            hFile = CreateFileW(data,
                                (GENERIC_WRITE|GENERIC_READ),
                                0,
                                NULL,
                                OPEN_ALWAYS,
                                FILE_ATTRIBUTE_NORMAL,
                                NULL);
            if (hFile != INVALID_HANDLE_VALUE)
            {
                CloseHandle(hFile);
            }
        }
    }
}
Exemple #9
0
HRESULT CFileWatcher::WatchFile(PCWSTR fileName, FileModifiedCallback callback, void* data)
{
	HRESULT hr;
	WatchedFile* file;
	WatchedDirectory* directory;
	WatchedDirectory* newDirectory;
	WCHAR fileOnly[_MAX_FNAME];
	WCHAR ext[_MAX_EXT];
	WCHAR* directoryName = NULL;
	DWORD fileNameLength;
	DWORD fileNameOnlyLength;
	DWORD directoryLength;	
	WIN32_FILE_ATTRIBUTE_DATA attributes;

	CheckNull(callback);
	CheckNull(fileName);
	fileNameLength = wcslen(fileName);

	// allocate new WatchedFile, get snapshot of the last write time

	ErrorIf(NULL == (file = new WatchedFile), ERROR_NOT_ENOUGH_MEMORY);
	RtlZeroMemory(file, sizeof WatchedFile);
	file->callback = callback;
	file->data = data;
	ErrorIf(!GetFileAttributesExW(fileName, GetFileExInfoStandard, &attributes), GetLastError());
	memcpy(&file->lastWrite, &attributes.ftLastWriteTime, sizeof attributes.ftLastWriteTime);

	// create and normalize a copy of directory name and file name

	ErrorIf(0 != _wsplitpath_s(fileName, NULL, 0, NULL, 0, fileOnly, _MAX_FNAME, ext, _MAX_EXT), ERROR_INVALID_PARAMETER);	
	fileNameOnlyLength = wcslen(fileOnly) + wcslen(ext);	
	directoryLength = fileNameLength - fileNameOnlyLength; 
	ErrorIf(NULL == (directoryName = new WCHAR[directoryLength + 8]), ERROR_NOT_ENOUGH_MEMORY); // pessimistic length after normalization with prefix \\?\UNC\ 
	ErrorIf(NULL == (file->fileName = new WCHAR[fileNameLength + 1]), ERROR_NOT_ENOUGH_MEMORY);
	wcscpy(file->fileName, fileName);

	if (fileNameLength > 8 && 0 == memcmp(fileName, L"\\\\?\\UNC\\", 8 * sizeof WCHAR))
	{
		// normalized UNC path
		file->unc = TRUE;
		memcpy(directoryName, fileName, directoryLength * sizeof WCHAR);
		directoryName[directoryLength] = L'\0';
	}
	else if (fileNameLength > 4 && 0 == memcmp(fileName, L"\\\\?\\", 4 * sizeof WCHAR))
	{
		// normalized local file
		file->unc = FALSE;
		memcpy(directoryName, fileName, directoryLength * sizeof WCHAR);
		directoryName[directoryLength] = L'\0';
	}
	else if (fileNameLength > 2 && 0 == memcmp(fileName, L"\\\\", 2 * sizeof(WCHAR)))
	{
		// not normalized UNC path
		file->unc = TRUE;
		wcscpy(directoryName, L"\\\\?\\UNC\\");
		memcpy(directoryName + 8, fileName + 2, (directoryLength - 2) * sizeof WCHAR);
		directoryName[8 + directoryLength - 2] = L'\0';
	}
	else
	{
		// not normalized local file
		file->unc = FALSE;
		wcscpy(directoryName, L"\\\\?\\");
		memcpy(directoryName + 4, fileName, directoryLength * sizeof WCHAR);
		directoryName[4 + directoryLength] = L'\0';	
	}

	// find matching directory watcher entry

	directory = this->directories;
	while (NULL != directory)
	{
		if (0 == wcscmp(directory->directoryName, directoryName))
		{
			delete [] directoryName;
			directoryName = NULL;
			break;
		}

		directory = directory->next;
	}

	// if directory watcher not found, create one

	if (NULL == directory)
	{
		ErrorIf(NULL == (newDirectory = new WatchedDirectory), ERROR_NOT_ENOUGH_MEMORY);	
		RtlZeroMemory(newDirectory, sizeof WatchedDirectory);
		newDirectory->directoryName = directoryName;
		directoryName = NULL;
		newDirectory->files = file;

		ErrorIf(INVALID_HANDLE_VALUE == (newDirectory->watchHandle = CreateFileW(
			newDirectory->directoryName,           
			FILE_LIST_DIRECTORY,    
			FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
			NULL, 
			OPEN_EXISTING,         
			FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
			NULL)),
			GetLastError());

		ErrorIf(NULL == CreateIoCompletionPort(newDirectory->watchHandle, this->completionPort, (ULONG_PTR)newDirectory, 0), 
			GetLastError());

		ErrorIf(0 == ReadDirectoryChangesW(
			newDirectory->watchHandle,
			&newDirectory->info,
			sizeof newDirectory->info,
			FALSE,
			FILE_NOTIFY_CHANGE_LAST_WRITE,
			NULL,
			&newDirectory->overlapped,
			NULL),
			GetLastError());

		if (NULL == this->directories)
		{
			// no watchers exist yet, start the watcher thread

			ErrorIf(NULL == (this->worker = (HANDLE)_beginthreadex(
				NULL, 
				4096, 
				CFileWatcher::Worker, 
				this, 
				0, 
				NULL)), 
				ERROR_NOT_ENOUGH_MEMORY);
		}

		newDirectory->next = this->directories;
		this->directories = newDirectory;
		newDirectory = NULL;
	}
	else
	{
		file->next = directory->files;
		directory->files = file;
		file = NULL;
	}

	return S_OK;
Error:

	if (NULL != newDirectory)
	{
		if (NULL != newDirectory->directoryName)
		{
			delete [] newDirectory->directoryName;
		}

		if (NULL != newDirectory->watchHandle)
		{
			CloseHandle(newDirectory->watchHandle);
		}

		delete newDirectory;
	}

	if (NULL != file)
	{
		delete [] file->fileName;
		delete file;
	}

	if (NULL != directoryName)
	{
		delete [] directoryName;
	}

	return hr;
}
bool FileSystem::openAndSeekFileSharedRead(QFile *file, QString *errorOrNull, qint64 seek)
{
    QString errorDummy;
    // avoid many if (errorOrNull) later.
    QString &error = errorOrNull ? *errorOrNull : errorDummy;
    error.clear();

#ifdef Q_OS_WIN
    //
    // The following code is adapted from Qt's QFSFileEnginePrivate::nativeOpen()
    // by including the FILE_SHARE_DELETE share mode.
    //

    // Enable full sharing.
    DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;

    int accessRights = GENERIC_READ;
    DWORD creationDisp = OPEN_EXISTING;

    // Create the file handle.
    SECURITY_ATTRIBUTES securityAtts = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE };
    QString fName = longWinPath(file->fileName());

    HANDLE fileHandle = CreateFileW(
        (const wchar_t *)fName.utf16(),
        accessRights,
        shareMode,
        &securityAtts,
        creationDisp,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    // Bail out on error.
    if (fileHandle == INVALID_HANDLE_VALUE) {
        error = qt_error_string();
        return false;
    }

    // Convert the HANDLE to an fd and pass it to QFile's foreign-open
    // function. The fd owns the handle, so when QFile later closes
    // the fd the handle will be closed too.
    int fd = _open_osfhandle((intptr_t)fileHandle, _O_RDONLY);
    if (fd == -1) {
        error = "could not make fd from handle";
        return false;
    }
    if (!file->open(fd, QIODevice::ReadOnly, QFile::AutoCloseHandle)) {
        error = file->errorString();
        return false;
    }

    // Seek to the right spot
    LARGE_INTEGER *li = reinterpret_cast<LARGE_INTEGER *>(&seek);
    DWORD newFilePointer = SetFilePointer(fileHandle, li->LowPart, &li->HighPart, FILE_BEGIN);
    if (newFilePointer == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
        error = qt_error_string();
        return false;
    }

    return true;
#else
    if (!file->open(QFile::ReadOnly)) {
        error = file->errorString();
        return false;
    }
    if (!file->seek(seek)) {
        error = file->errorString();
        return false;
    }
    return true;
#endif
}
Exemple #11
0
bool create_bob_txt() {
	wchar_t *buf = NULL;
	uint32_t buflen = 0;
	buflen = GetCurrentDirectoryW(buflen, buf);

	if (buflen == 0) {
		printf("[error] GetCurrentDirectoryW() failed!!! gle = 0x%08x\n", GetLastError());
		return false;
	}

	buf = (PWSTR)malloc(sizeof(WCHAR)*buflen);

	if (GetCurrentDirectoryW(buflen, buf) == 0) {
		printf("[error] GetCurrentDirectoryW() failed!!! gle = 0x%08x\n", GetLastError());
		free(buf);
		return false;
	}

	// current directory\\bob.txt 생성
	wchar_t file_name[260];
	if (!SUCCEEDED(StringCbPrintfW(
		file_name,
		sizeof(file_name),
		L"%ws\\bob.txt",
		buf))) {
		printf("[error] can not create bob.txt\n");
		free(buf);
		return false;
	}
	free(buf);
	buf = NULL;

	if (is_file_existsW(file_name)) {
		DeleteFileW(file_name);
	}

	// 파일 생성
	HANDLE file_handle = CreateFileW(
		file_name,
		GENERIC_WRITE,
		FILE_SHARE_READ,
		NULL,
		CREATE_NEW,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	/////////////////////////////////////////////////////////
	DWORD numberOfBytesWritten;
	int result;
	unsigned char mark[3];

	mark[0] = 0xEF;
	mark[1] = 0xBB;

	// UTF-8
	mark[2] = 0xBF;	

	wchar_t strUnicode[256] = L"안녕하세요 굳 굳굳 HelloWorld";
	char strUtf8[256] = { 0, };

	if (file_handle == INVALID_HANDLE_VALUE) {
		printf("[error] can not CreateFile, gle=0x%08x\n", GetLastError());
		return false;
	}

	int nlen = WideCharToMultiByte(CP_UTF8, 0, strUnicode, lstrlenW(strUnicode), NULL, 0, NULL, NULL);
	WideCharToMultiByte(CP_UTF8, 0, strUnicode, lstrlenW(strUnicode), strUtf8, nlen, NULL, NULL);

	result = WriteFile(file_handle, &mark, 3, &numberOfBytesWritten, NULL);
	result = WriteFile(file_handle, strUtf8, strlen(strUtf8), &numberOfBytesWritten, NULL);

	// bob.txt -> bob2.txt 파일 복사
	LPCWSTR file_name2 = L"C:\\Users\\kahissa\\Documents\\Visual Studio 2013\\Projects\\Console_test1\\bob2.txt";
	CopyFile(file_name, file_name2, false);


	// bob2.txt 파일 내용 읽기
	char readBuf[256] = { 0, };
	DWORD dwRead = 0;
	BOOL readOK;
	HANDLE file_handle2 = CreateFileW(file_name2, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if (file_handle2 == INVALID_HANDLE_VALUE) {
		printf("[error] can not file open, gle=0x%08x\n", GetLastError());
	}

	readOK = ReadFile(file_handle2, readBuf, 256, &dwRead, NULL);	// 파일 내용 읽어서 rBuf에 저장

	if (readOK && dwRead == 0)
		printf("[error] can not read file, gle=0x%08x\n", GetLastError());


	//readBuf에 UTF8 적용
	int len = MultiByteToWideChar(CP_UTF8, 0, readBuf, strlen(readBuf), NULL, NULL);

	wchar_t MultiByte[256] = { 0, };

	// UTF8 -> 유니코드
	MultiByteToWideChar(CP_UTF8, 0, readBuf, strlen(readBuf), MultiByte, len);

	char MultiByte2[256] = { 0, };

	/// 유니코드 -> 멀티바이트
	len = WideCharToMultiByte(CP_ACP, 0, MultiByte, -1, NULL, 0, NULL, NULL);
	WideCharToMultiByte(CP_ACP, 0, MultiByte, -1, MultiByte2, len, NULL, NULL);

	printf("%s\n", MultiByte2 + 1);	// header 다음부터 출력

	CloseHandle(file_handle);
	CloseHandle(file_handle2);

	DeleteFile(file_name);
	DeleteFile(file_name2);

	return true;
}
Exemple #12
0
RTR3DECL(int) RTPathSetTimesEx(const char *pszPath, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
                               PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime, uint32_t fFlags)
{
    /*
     * Validate input.
     */
    AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
    AssertReturn(*pszPath, VERR_INVALID_PARAMETER);
    AssertPtrNullReturn(pAccessTime, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pModificationTime, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pChangeTime, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pBirthTime, VERR_INVALID_POINTER);
    AssertMsgReturn(RTPATH_F_IS_VALID(fFlags, 0), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);

    /*
     * Convert the path.
     */
    PRTUTF16 pwszPath;
    int rc = RTStrToUtf16(pszPath, &pwszPath);
    if (RT_SUCCESS(rc))
    {
        HANDLE hFile;
        if (fFlags & RTPATH_F_FOLLOW_LINK)
            hFile = CreateFileW(pwszPath,
                                FILE_WRITE_ATTRIBUTES,   /* dwDesiredAccess */
                                FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, /* dwShareMode */
                                NULL,                    /* security attribs */
                                OPEN_EXISTING,           /* dwCreationDisposition */
                                FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,
                                NULL);
        else
        {
/** @todo Symlink: Test RTPathSetTimesEx on Windows. (The code is disabled
 *        because it's not tested yet.) */
#if 0 //def FILE_FLAG_OPEN_REPARSE_POINT
            hFile = CreateFileW(pwszPath,
                                FILE_WRITE_ATTRIBUTES,   /* dwDesiredAccess */
                                FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, /* dwShareMode */
                                NULL,                    /* security attribs */
                                OPEN_EXISTING,           /* dwCreationDisposition */
                                FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
                                NULL);

            if (hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_PARAMETER)
#endif
                hFile = CreateFileW(pwszPath,
                                    FILE_WRITE_ATTRIBUTES,   /* dwDesiredAccess */
                                    FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, /* dwShareMode */
                                    NULL,                    /* security attribs */
                                    OPEN_EXISTING,           /* dwCreationDisposition */
                                    FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,
                                    NULL);
        }
        if (hFile != INVALID_HANDLE_VALUE)
        {
            /*
             * Check if it's a no-op.
             */
            if (!pAccessTime && !pModificationTime && !pBirthTime)
                rc = VINF_SUCCESS;    /* NOP */
            else
            {
                /*
                 * Convert the input and call the API.
                 */
                FILETIME    CreationTimeFT;
                PFILETIME   pCreationTimeFT = NULL;
                if (pBirthTime)
                    pCreationTimeFT = RTTimeSpecGetNtFileTime(pBirthTime, &CreationTimeFT);

                FILETIME    LastAccessTimeFT;
                PFILETIME   pLastAccessTimeFT = NULL;
                if (pAccessTime)
                    pLastAccessTimeFT = RTTimeSpecGetNtFileTime(pAccessTime, &LastAccessTimeFT);

                FILETIME    LastWriteTimeFT;
                PFILETIME   pLastWriteTimeFT = NULL;
                if (pModificationTime)
                    pLastWriteTimeFT = RTTimeSpecGetNtFileTime(pModificationTime, &LastWriteTimeFT);

                if (SetFileTime(hFile, pCreationTimeFT, pLastAccessTimeFT, pLastWriteTimeFT))
                    rc = VINF_SUCCESS;
                else
                {
                    DWORD Err = GetLastError();
                    rc = RTErrConvertFromWin32(Err);
                    Log(("RTPathSetTimes('%s', %p, %p, %p, %p): SetFileTime failed with lasterr %d (%Rrc)\n",
                         pszPath, pAccessTime, pModificationTime, pChangeTime, pBirthTime, Err, rc));
                }
            }
            BOOL fRc = CloseHandle(hFile); Assert(fRc); NOREF(fRc);
        }
        else
        {
            DWORD Err = GetLastError();
            rc = RTErrConvertFromWin32(Err);
            Log(("RTPathSetTimes('%s',,,,): failed with %Rrc and lasterr=%u\n", pszPath, rc, Err));
        }

        RTUtf16Free(pwszPath);
    }

    LogFlow(("RTPathSetTimes(%p:{%s}, %p:{%RDtimespec}, %p:{%RDtimespec}, %p:{%RDtimespec}, %p:{%RDtimespec}): return %Rrc\n",
             pszPath, pszPath, pAccessTime, pAccessTime, pModificationTime, pModificationTime,
             pChangeTime, pChangeTime, pBirthTime, pBirthTime));
    return rc;
}
Exemple #13
0
/*
 * Code based off of code located here
 * http://www.codeproject.com/gdi/fontnamefromfile.asp
 */
static WCHAR *load_ttf_name_id( const WCHAR *filename, DWORD id )
{
    TT_TABLE_DIRECTORY tblDir;
    BOOL bFound = FALSE;
    TT_OFFSET_TABLE ttOffsetTable;
    TT_NAME_TABLE_HEADER ttNTHeader;
    TT_NAME_RECORD ttRecord;
    DWORD dwRead;
    HANDLE handle;
    LPWSTR ret = NULL;
    int i;

    handle = CreateFileW(filename ,GENERIC_READ, 0, NULL, OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL, 0 );
    if (handle == INVALID_HANDLE_VALUE)
    {
        ERR("Unable to open font file %s\n", debugstr_w(filename));
        return NULL;
    }

    if (!ReadFile(handle,&ttOffsetTable, sizeof(TT_OFFSET_TABLE),&dwRead,NULL))
        goto end;

    ttOffsetTable.uNumOfTables = SWAPWORD(ttOffsetTable.uNumOfTables);
    ttOffsetTable.uMajorVersion = SWAPWORD(ttOffsetTable.uMajorVersion);
    ttOffsetTable.uMinorVersion = SWAPWORD(ttOffsetTable.uMinorVersion);

    if ((ttOffsetTable.uMajorVersion != 1 || ttOffsetTable.uMinorVersion != 0) &&
        (ttOffsetTable.uMajorVersion != 0x4f54 || ttOffsetTable.uMinorVersion != 0x544f))
        goto end;

    for (i=0; i< ttOffsetTable.uNumOfTables; i++)
    {
        if (!ReadFile(handle,&tblDir, sizeof(TT_TABLE_DIRECTORY),&dwRead,NULL))
            break;
        if (memcmp(tblDir.szTag,"name",4)==0)
        {
            bFound = TRUE;
            tblDir.uLength = SWAPLONG(tblDir.uLength);
            tblDir.uOffset = SWAPLONG(tblDir.uOffset);
            break;
        }
    }

    if (!bFound)
        goto end;

    SetFilePointer(handle, tblDir.uOffset, NULL, FILE_BEGIN);
    if (!ReadFile(handle,&ttNTHeader, sizeof(TT_NAME_TABLE_HEADER), &dwRead,NULL))
        goto end;

    ttNTHeader.uNRCount = SWAPWORD(ttNTHeader.uNRCount);
    ttNTHeader.uStorageOffset = SWAPWORD(ttNTHeader.uStorageOffset);
    for(i=0; i<ttNTHeader.uNRCount; i++)
    {
        if (!ReadFile(handle,&ttRecord, sizeof(TT_NAME_RECORD),&dwRead,NULL))
            break;

        ttRecord.uNameID = SWAPWORD(ttRecord.uNameID);
        ttRecord.uPlatformID = SWAPWORD(ttRecord.uPlatformID);
        ttRecord.uEncodingID = SWAPWORD(ttRecord.uEncodingID);
        if (ttRecord.uNameID == id && ttRecord.uPlatformID == 3 &&
            (ttRecord.uEncodingID == 0 || ttRecord.uEncodingID == 1))
        {
            WCHAR *buf;
            unsigned int i;

            ttRecord.uStringLength = SWAPWORD(ttRecord.uStringLength);
            ttRecord.uStringOffset = SWAPWORD(ttRecord.uStringOffset);
            SetFilePointer(handle, tblDir.uOffset + ttRecord.uStringOffset + ttNTHeader.uStorageOffset,
                           NULL, FILE_BEGIN);
            if (!(buf = msi_alloc_zero( ttRecord.uStringLength + sizeof(WCHAR) ))) goto end;
            dwRead = 0;
            ReadFile(handle, buf, ttRecord.uStringLength, &dwRead, NULL);
            if (dwRead % sizeof(WCHAR))
            {
                msi_free(buf);
                goto end;
            }
            for (i = 0; i < dwRead / sizeof(WCHAR); i++) buf[i] = SWAPWORD(buf[i]);
            ret = strdupW(buf);
            msi_free(buf);
            break;
        }
    }

end:
    CloseHandle(handle);
    return ret;
}
Exemple #14
0
bool create_bob_txt()
{
    // current directory 를 구한다.
    wchar_t *buf=NULL;
    uint32_t buflen = 0;
    buflen = GetCurrentDirectoryW(buflen, buf);
        if (0 == buflen)
        {
        print("err, GetCurrentDirectoryW() failed. gle = 0x%08x", GetLastError());
        return false;
        }
 
        buf = (PWSTR) malloc(sizeof(WCHAR) * buflen);
        if (0 == GetCurrentDirectoryW(buflen, buf))
        {
                print("err, GetCurrentDirectoryW() failed. gle = 0x%08x", GetLastError());
                free(buf);
                return false;
        }
 
    // current dir \\ bob.txt 파일명 생성
    wchar_t file_name[260];
    if (!SUCCEEDED(StringCbPrintfW(
                            file_name,
                            sizeof(file_name),
                            L"%ws\\bob.txt",
                            buf)))
    {  
        print("err, can not create file name");
        free(buf);
        return false;
    }
    free(buf); buf = NULL;
 
    if (true == is_file_existsW(file_name))
    {
        ::DeleteFileW(file_name);
    }
 
    // 파일 생성
    HANDLE file_handle = CreateFileW(
                                file_name,
                                                        GENERIC_WRITE,
                                                        FILE_SHARE_READ,
                                                        NULL,
                                                        CREATE_NEW,
                                                        FILE_ATTRIBUTE_NORMAL,
                                                        NULL); 
        if(file_handle == INVALID_HANDLE_VALUE)
        {                                              
        print("err, CreateFile(path=%ws), gle=0x%08x", file_name, GetLastError());
        return false;
        }
 
    // 파일에 데이터 쓰기
    DWORD bytes_written = 0;
    wchar_t string_buf[1024];
    if (!SUCCEEDED(StringCbPrintfW(
                        string_buf,
                        sizeof(string_buf),
                        L"동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세")))
    {
        print("err, can not create data to write.");
        CloseHandle(file_handle);
        return false;
    }
 
    if (!WriteFile(file_handle, string_buf, wcslen(string_buf), &bytes_written, NULL))
    {
        print("err, WriteFile() failed. gle = 0x%08x", GetLastError());
        CloseHandle(file_handle);
        return false;
    }
 
    // 영어로 쓰기
    if (!SUCCEEDED(StringCbPrintfW(
                        string_buf,
                        sizeof(string_buf),
                        L"All work and no play makes jack a dull boy.")))
    {
        print("err, can not create data to write.");
        CloseHandle(file_handle);
        return false;
    }
 
    if (!WriteFile(file_handle, string_buf, wcslen(string_buf), &bytes_written, NULL))
    {
        print("err, WriteFile() failed. gle = 0x%08x", GetLastError());
        CloseHandle(file_handle);
        return false;
    }
 
 
 
 
    char string_bufa[1024];
    if (!SUCCEEDED(StringCbPrintfA(
                        string_bufa,
                        sizeof(string_bufa),
                        "동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세")))
    {
        print("err, can not create data to write.");
        CloseHandle(file_handle);
        return false;
    }
 
    if (!WriteFile(file_handle, string_bufa, strlen(string_bufa), &bytes_written, NULL))
    {
        print("err, WriteFile() failed. gle = 0x%08x", GetLastError());
        CloseHandle(file_handle);
        return false;
    }
 
    // 영어로 쓰기
    if (!SUCCEEDED(StringCbPrintfA(
                        string_bufa,
                        sizeof(string_bufa),
                        "All work and no play makes jack a dull boy.")))
    {
        print("err, can not create data to write.");
        CloseHandle(file_handle);
        return false;
    }
 
    if (!WriteFile(file_handle, string_bufa, strlen(string_bufa), &bytes_written, NULL))
    {
        print("err, WriteFile() failed. gle = 0x%08x", GetLastError());
        CloseHandle(file_handle);
        return false;
    }
 
    // 파일 닫기
    CloseHandle(file_handle);
    return true;
 
}
Exemple #15
0
void uv_pipe_connect(uv_connect_t* req, uv_pipe_t* handle,
    const char* name, uv_connect_cb cb) {
  uv_loop_t* loop = handle->loop;
  int errno, nameSize;
  HANDLE pipeHandle;

  handle->handle = INVALID_HANDLE_VALUE;

  uv_req_init(loop, (uv_req_t*) req);
  req->type = UV_CONNECT;
  req->handle = (uv_stream_t*) handle;
  req->cb = cb;

  /* Convert name to UTF16. */
  nameSize = uv_utf8_to_utf16(name, NULL, 0) * sizeof(wchar_t);
  handle->name = (wchar_t*)malloc(nameSize);
  if (!handle->name) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
  }

  if (!uv_utf8_to_utf16(name, handle->name, nameSize / sizeof(wchar_t))) {
    errno = GetLastError();
    goto error;
  }

  pipeHandle = CreateFileW(handle->name,
                          GENERIC_READ | GENERIC_WRITE,
                          0,
                          NULL,
                          OPEN_EXISTING,
                          FILE_FLAG_OVERLAPPED,
                          NULL);

  if (pipeHandle == INVALID_HANDLE_VALUE) {
    if (GetLastError() == ERROR_PIPE_BUSY) {
      /* Wait for the server to make a pipe instance available. */
      if (!QueueUserWorkItem(&pipe_connect_thread_proc,
                             req,
                             WT_EXECUTELONGFUNCTION)) {
        errno = GetLastError();
        goto error;
      }

      handle->reqs_pending++;

      return;
    }

    errno = GetLastError();
    goto error;
  }

  if (uv_set_pipe_handle(loop, (uv_pipe_t*)req->handle, pipeHandle)) {
    errno = GetLastError();
    goto error;
  }

  handle->handle = pipeHandle;

  SET_REQ_SUCCESS(req);
  uv_insert_pending_req(loop, (uv_req_t*) req);
  handle->reqs_pending++;
  return;

error:
  if (handle->name) {
    free(handle->name);
    handle->name = NULL;
  }

  if (pipeHandle != INVALID_HANDLE_VALUE) {
    CloseHandle(pipeHandle);
  }

  /* Make this req pending reporting an error. */
  SET_REQ_ERROR(req, errno);
  uv_insert_pending_req(loop, (uv_req_t*) req);
  handle->reqs_pending++;
  return;
}
Exemple #16
0
int cop_filemap_open(struct cop_filemap *map, const char *filename, unsigned flags)
{
	DWORD faccess;
	DWORD mapprotect;
	DWORD mapaccess;
	LARGE_INTEGER fsz;
	LPWSTR wfn;
	int fnlen;

	if ((flags & COP_FILEMAP_FLAG_W) == 0) {
		/* read only access */
		faccess    = GENERIC_READ;
		mapprotect = PAGE_READONLY;
		mapaccess  = FILE_MAP_READ;
	} else if ((flags & COP_FILEMAP_SHARED)) {
		/* shared write access */
		faccess    = GENERIC_READ | GENERIC_WRITE;
		mapprotect = PAGE_READWRITE;
		mapaccess  = FILE_MAP_WRITE;
	} else {
		/* unshared write access */
		faccess    = GENERIC_READ;
		mapprotect = PAGE_READONLY;
		mapaccess  = FILE_MAP_COPY;
	}

	fnlen = MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
	if (fnlen == 0)
		return -1;

	wfn = malloc(sizeof(*wfn) * fnlen);
	if (wfn == NULL)
		return -1;

	if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, wfn, fnlen) != fnlen) {
		free(wfn);
		return -1;
	}

	map->filehandle = CreateFileW(wfn, faccess, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (map->filehandle == INVALID_HANDLE_VALUE) {
		free(wfn);
		return -1;
	}

	free(wfn);

	if (!GetFileSizeEx(map->filehandle, &fsz)) {
		CloseHandle(map->filehandle);
		return -1;
	}

	if (fsz.QuadPart > SIZE_MAX) {
		CloseHandle(map->filehandle);
		return -1;
	}

	map->size = (size_t)fsz.QuadPart;

	map->maphandle = CreateFileMapping(map->filehandle, NULL, mapprotect, 0, 0, NULL);
	if (map->maphandle == INVALID_HANDLE_VALUE) {
		CloseHandle(map->filehandle);
		return -1;
	}

	map->ptr = MapViewOfFile(map->maphandle, mapaccess, 0, 0, 0);
	if (map->ptr == NULL) {
		CloseHandle(map->maphandle);
		CloseHandle(map->filehandle);
		return -1;
	}

	return 0;
}
Exemple #17
0
int __cdecl main(int argc, char *argv[])
{
    DWORD   dwRc = 0;

    WCHAR   szReturnedPath[_MAX_DIR+1];
    WCHAR   szFullFileName[_MAX_DIR+1];
    WCHAR   szDirectory[256];
    WCHAR   szCreatedDir[]     = {'t','e','s','t','_','d','i','r','\0'};

    LPWSTR  pPathPtr;
    HANDLE  hFile = NULL;
    BOOL    bRetVal = FAIL;

    /* Initialize the PAL.
     */
    if (0 != PAL_Initialize(argc,argv))
    {
        return (FAIL);
    }

    /* Initialize the buffer.
     */
    memset(szDirectory, '\0', 256);

    /* Create the path to the next level of directory to create.
     */
    wcscat(szDirectory, szDotDot);        /* ..                  */
    wcscat(szDirectory, szSeperator);     /* ../                 */
    wcscat(szDirectory, szCreatedDir);    /* ../test_directory   */

    /* Create a test directory.
     */
    if (!CreateDirectoryW(szDirectory, NULL))
    {
        Fail("ERROR:%u: Unable to create directories \"%S\".\n",
             GetLastError(),
             szDirectory);
    }

    /* Initialize the receiving char buffers.
     */
    memset(szReturnedPath, 0, _MAX_DIR+1);
    memset(szFullFileName, 0, _MAX_DIR+1);

    /* Create Full filename to pass, will include '..\'
     * in the middle of the path.
     */
    wcscat( szFullFileName, szDotDot );     /* ..                            */
    wcscat( szFullFileName, szSeperator );  /* ../                           */
    wcscat( szFullFileName, szCreatedDir ); /* ../test_directory             */
    wcscat( szFullFileName, szSeperator );  /* ../test_directory/            */
    wcscat( szFullFileName, szFileName );   /* ../test_directory/testing.tmp */

    /* Get the full path to the filename.
     */
    dwRc = GetFullPathNameW(szFullFileName, 
                            _MAX_DIR,
                            szReturnedPath, 
                            &pPathPtr);
    if (dwRc == 0)
    {
        Trace("ERROR :%ld: GetFullPathName failed to "
              "retrieve the path of \"%S\".\n",
              GetLastError(),
              szFileName);
        bRetVal = FAIL;
        goto cleanUpOne;
    }

    /* The returned value should be the parent directory with the 
     * file name appended. */
    hFile = CreateFileW(szReturnedPath,
                        GENERIC_READ,
                        FILE_SHARE_READ,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        Trace("ERROR :%ld: CreateFileA failed to create \"%S\".\n", 
              GetLastError(),
              szReturnedPath);
        bRetVal = FAIL;
        goto cleanUpOne;
    }

    /* Close the handle to the created file.
     */
    if (CloseHandle(hFile) != TRUE)
    {
        Trace("ERROR :%ld: CloseHandle failed close hFile=0x%lx.\n",
              GetLastError());
        bRetVal = FAIL;
        goto cleanUpTwo;
    }

    /* Verify that the file was created, attempt to create 
     * the file again. */
    hFile = CreateFileW(szReturnedPath,
                        GENERIC_READ,
                        FILE_SHARE_READ,
                        NULL,
                        CREATE_NEW,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);
    if ((hFile != INVALID_HANDLE_VALUE) && 
        (GetLastError() != ERROR_ALREADY_EXISTS))
    {
        Trace("ERROR :%ld: CreateFileA succeeded to create file "
              "\"%S\", that already existed.\n",
              GetLastError(),
              szFullFileName);
        bRetVal = FAIL;
        goto cleanUpTwo;
    }

    /* Verify that the returned filename is the same as the supplied.
     */
    if (wcscmp(pPathPtr, szFileName) != 0)
    {
        Trace("ERROR : Returned filename \"%S\" is not equal to "
              "supplied filename \"%S\".\n",
              pPathPtr, 
              szFileName);
        bRetVal = FAIL;
        goto cleanUpTwo;
    }

    /* Successful test.
     */
    bRetVal = PASS;

cleanUpTwo:
    
    /* Delete the create file. 
     */
    if (DeleteFileW(szReturnedPath) != TRUE)
    {
        Fail("ERROR :%ld: DeleteFileA failed to delete \"%S\".\n",
             GetLastError(),
             szFileName);
    }

cleanUpOne:

    /* Remove the empty directory.
     */
    if (!RemoveDirectoryW(szDirectory))
    {
        Fail("ERROR:%u: Unable to remove directory \"%s\".\n",
             GetLastError(),
             szCreatedDir);
    }

    /* Terminate the PAL.*/
    PAL_Terminate();
    return bRetVal;
}
Exemple #18
0
CPipe::CPipe(char *szName, DWORD dWait){
	int	iTemp;
	int	iFlag = 1;
	WCHAR	wbuffer[MAX_PATH+1];
	dTHX;
	
	hPipe = 0;                 
	dBufferSize = BUFFER_SIZE;
	dBytes = 0;
			              	
	char szPipeName[PIPE_NAME_SIZE + 1];				
	dwOpenMode = PIPE_ACCESS_DUPLEX;		
	dwPipeMode = 	PIPE_TYPE_BYTE	 |      
					PIPE_READMODE_BYTE	 |  
					PIPE_WAIT;				
	nMaxInstances =	PIPE_UNLIMITED_INSTANCES;
	nOutBufferSize = dBufferSize;			
	nInBufferSize  = dBufferSize;
	nDefaultTimeOut = PIPE_TIMEOUT;			
	lpSecurityAttributes= NULL; 
	iError = 0;
	strcpy((char *)szError, "");
	
	cBuffer = new char [dBufferSize];
	if (! cBuffer){
		dBufferSize = 0;
	}

	memset((void *)szError, 0, ERROR_TEXT_SIZE);
	memset((void *)szPipeName, 0, PIPE_NAME_SIZE + 1);
	if (strncmp((char *)szName, "\\\\", 2) == 0){
		iPipeType = CLIENT;
		iTemp = 0;
	}else{
		iPipeType = SERVER;
		strcpy(szPipeName, PIPE_NAME_PREFIX);
		iTemp = strlen(PIPE_NAME_PREFIX);
	}
	strncat(szPipeName, szName, PIPE_NAME_SIZE - iTemp);
	if (USING_WIDE()) {
	    A2WHELPER(szPipeName, wbuffer, sizeof(wbuffer));
	}
	if(iPipeType == SERVER){
	    if (USING_WIDE()) {
		hPipe = CreateNamedPipeW(wbuffer,
					dwOpenMode, 
					dwPipeMode, 
					nMaxInstances, 
					nOutBufferSize, 
					nInBufferSize, 
					nDefaultTimeOut,
					lpSecurityAttributes);
	    }
	    else {
		hPipe = CreateNamedPipeA(szPipeName,
					dwOpenMode, 
					dwPipeMode, 
					nMaxInstances, 
					nOutBufferSize, 
					nInBufferSize, 
					nDefaultTimeOut,
					lpSecurityAttributes);
	    }
	}else{
		while(iFlag){
		    if (USING_WIDE()) {
			hPipe = CreateFileW(wbuffer,
					    GENERIC_READ | GENERIC_WRITE, 
					    FILE_SHARE_READ	| FILE_SHARE_WRITE,
					    NULL,
					    OPEN_EXISTING,
					    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
					    NULL);
		    }
		    else {
			hPipe = CreateFileA(szPipeName,
					    GENERIC_READ | GENERIC_WRITE, 
					    FILE_SHARE_READ	| FILE_SHARE_WRITE,
					    NULL,
					    OPEN_EXISTING,
					    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
					    NULL);
		    }

		    if (GetLastError() == ERROR_PIPE_BUSY){
			if (USING_WIDE())
			    iFlag = WaitNamedPipeW(wbuffer, dWait);
			else
			    iFlag = WaitNamedPipeA(szPipeName, dWait);
		    }else{
			    iFlag = 0;
		    }
		}
	}
	if (cBuffer == 0){
		iError = 998;
		strcpy((char *)szError, "Could not allocate a buffer for the pipe connection");
	}
	if (hPipe == INVALID_HANDLE_VALUE){
		iError = 999;
		strcpy((char *)szError, "Could not connect");
		delete this;
	}
}									  
Exemple #19
0
    void* MemoryMappedFile::map(const char *filenameIn, unsigned long long &length, int options) {
        verify( fd == 0 && len == 0 ); // can't open more than once
        setFilename(filenameIn);
        FileAllocator::get()->allocateAsap( filenameIn, length );
        /* big hack here: Babble uses db names with colons.  doesn't seem to work on windows.  temporary perhaps. */
        char filename[256];
        strncpy(filename, filenameIn, 255);
        filename[255] = 0;
        {
            size_t len = strlen( filename );
            for ( size_t i=len-1; i>=0; i-- ) {
                if ( filename[i] == '/' ||
                        filename[i] == '\\' )
                    break;

                if ( filename[i] == ':' )
                    filename[i] = '_';
            }
        }

        updateLength( filename, length );

        {
            DWORD createOptions = FILE_ATTRIBUTE_NORMAL;
            if ( options & SEQUENTIAL )
                createOptions |= FILE_FLAG_SEQUENTIAL_SCAN;
            DWORD rw = GENERIC_READ | GENERIC_WRITE;
            fd = CreateFileW(
                     toWideString(filename).c_str(),
                     rw, // desired access
                     FILE_SHARE_WRITE | FILE_SHARE_READ, // share mode
                     NULL, // security
                     OPEN_ALWAYS, // create disposition
                     createOptions , // flags
                     NULL); // hTempl
            if ( fd == INVALID_HANDLE_VALUE ) {
                DWORD dosError = GetLastError();
                log() << "CreateFileW for " << filename
                        << " failed with " << errnoWithDescription( dosError )
                        << " (file size is " << length << ")"
                        << " in MemoryMappedFile::map"
                        << endl;
                return 0;
            }
        }

        mapped += length;

        {
            DWORD flProtect = PAGE_READWRITE; //(options & READONLY)?PAGE_READONLY:PAGE_READWRITE;
            maphandle = CreateFileMappingW(fd, NULL, flProtect,
                                          length >> 32 /*maxsizehigh*/,
                                          (unsigned) length /*maxsizelow*/,
                                          NULL/*lpName*/);
            if ( maphandle == NULL ) {
                DWORD dosError = GetLastError();
                log() << "CreateFileMappingW for " << filename
                        << " failed with " << errnoWithDescription( dosError )
                        << " (file size is " << length << ")"
                        << " in MemoryMappedFile::map"
                        << endl;
                close();
                fassertFailed( 16225 );
            }
        }

        void *view = 0;
        {
            scoped_lock lk(mapViewMutex);
            DWORD access = ( options & READONLY ) ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS;
            LPVOID thisAddress = getNextMemoryMappedFileLocation( length );
            view = MapViewOfFileEx(
                    maphandle,      // file mapping handle
                    access,         // access
                    0, 0,           // file offset, high and low
                    0,              // bytes to map, 0 == all
                    thisAddress );  // address to place file
            if ( view == 0 ) {
                DWORD dosError = GetLastError();
                log() << "MapViewOfFileEx for " << filename
                        << " failed with " << errnoWithDescription( dosError )
                        << " (file size is " << length << ")"
                        << " in MemoryMappedFile::map"
                        << endl;
                close();
                fassertFailed( 16166 );
            }
        }
        views.push_back(view);
        memconcept::is(view, memconcept::concept::memorymappedfile, this->filename(), (unsigned) length);
        len = length;
        return view;
    }
Exemple #20
0
/*
 * Parts of the The p_readlink function are heavily inspired by the php 
 * readlink function in link_win32.c
 *
 * Copyright (c) 1999 - 2012 The PHP Group. All rights reserved.
 *
 * For details of the PHP license see http://www.php.net/license/3_01.txt
 */
int p_readlink(const char *link, char *target, size_t target_len)
{
	typedef DWORD (WINAPI *fpath_func)(HANDLE, LPWSTR, DWORD, DWORD);
	static fpath_func pGetFinalPath = NULL;
	HANDLE hFile;
	DWORD dwRet;
	git_win32_path link_w;
	wchar_t* target_w;
	int error = 0;

	assert(link && target && target_len > 0);

	/*
	 * Try to load the pointer to pGetFinalPath dynamically, because
	 * it is not available in platforms older than Vista
	 */
	if (pGetFinalPath == NULL) {
		HMODULE module = GetModuleHandle("kernel32");

		if (module != NULL)
			pGetFinalPath = (fpath_func)GetProcAddress(module, "GetFinalPathNameByHandleW");

		if (pGetFinalPath == NULL) {
			giterr_set(GITERR_OS,
				"'GetFinalPathNameByHandleW' is not available in this platform");
			return -1;
		}
	}

	git_win32_path_from_c(link_w, link);

	hFile = CreateFileW(link_w,			// file to open
			GENERIC_READ,			// open for reading
			FILE_SHARE_READ,		// share for reading
			NULL,					// default security
			OPEN_EXISTING,			// existing file only
			FILE_FLAG_BACKUP_SEMANTICS, // normal file
			NULL);					// no attr. template

	if (hFile == INVALID_HANDLE_VALUE) {
		giterr_set(GITERR_OS, "Cannot open '%s' for reading", link);
		return -1;
	}

	target_w = (wchar_t*)git__malloc(target_len * sizeof(wchar_t));
	GITERR_CHECK_ALLOC(target_w);

	dwRet = pGetFinalPath(hFile, target_w, (DWORD)target_len, 0x0);
	if (dwRet == 0 ||
		dwRet >= target_len ||
		!WideCharToMultiByte(CP_UTF8, 0, target_w, -1, target,
			(int)(target_len * sizeof(char)), NULL, NULL))
		error = -1;

	git__free(target_w);
	CloseHandle(hFile);

	if (error)
		return error;

	/* Skip first 4 characters if they are "\\?\" */
	if (dwRet > 4 &&
		target[0] == '\\' && target[1] == '\\' &&
		target[2] == '?' && target[3] == '\\')
	{
		unsigned int offset = 4;
		dwRet -= 4;

		/* \??\UNC\ */
		if (dwRet > 7 &&
			target[4] == 'U' && target[5] == 'N' && target[6] == 'C')
		{
			offset += 2;
			dwRet -= 2;
			target[offset] = '\\';
		}

		memmove(target, target + offset, dwRet);
	}

	target[dwRet] = '\0';

	return dwRet;
}
Exemple #21
0
        BOOL GetCatSignSubject(LPCWSTR FileFullPath, std::vector<std::string>& subInfo)
        {
            BOOL fRetval = FALSE;
            LPBYTE Hash = NULL;
            DWORD HashSize;
            CATALOG_INFO CatInfo;
            HANDLE hFile = NULL;
            HCATADMIN hCatAdmin;
            HCATINFO hCatInfo;
            HCATINFO PrevCat;
            DWORD Err;
            WINTRUST_DATA WintrustData;
            WINTRUST_CATALOG_INFO WintrustCatalogInfo;
            LPWSTR CatalogFullPath;
            WCHAR UnicodeKey[MAX_PATH];
            GUID DriverVerifyGuid = DRIVER_ACTION_VERIFY;
            PWCHAR Key = NULL;

            if (NULL == m_pWinVerifyTrust) {

                return FALSE;
            }

            StringCchCopyW( UnicodeKey, MAX_PATH, FileFullPath );
            Key = MyGetFileTitle( UnicodeKey );

            if (!m_pCryptCATAdminAcquireContext( &hCatAdmin, &DriverVerifyGuid, 0 )) {

                goto clean0;
            }

            hFile = CreateFileW( FileFullPath,
                GENERIC_READ,
                FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE,
                NULL,
                OPEN_EXISTING,
                0,
                NULL );

            if (INVALID_HANDLE_VALUE == hFile) {

                goto clean0;
            }

            ZeroMemory(&WintrustData, sizeof(WINTRUST_DATA));
            WintrustData.cbStruct = sizeof(WINTRUST_DATA);
            WintrustData.dwUIChoice = WTD_UI_NONE;
            WintrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
            WintrustData.dwStateAction = WTD_STATEACTION_AUTO_CACHE;
            WintrustData.dwProvFlags = WTD_REVOCATION_CHECK_NONE;

            HashSize = 100;
            Hash = new BYTE[HashSize];

            if(NULL == Hash) {

                goto clean0;
            }

            if (!m_pCryptCATAdminCalcHashFromFileHandle( hFile, &HashSize, Hash, 0 )) {

                goto clean0;
            }

            WintrustData.dwUnionChoice = WTD_CHOICE_CATALOG;
            WintrustData.pCatalog = &WintrustCatalogInfo;

            ZeroMemory(&WintrustCatalogInfo, sizeof(WINTRUST_CATALOG_INFO));
            WintrustCatalogInfo.cbStruct = sizeof(WINTRUST_CATALOG_INFO);
            WintrustCatalogInfo.pbCalculatedFileHash = Hash;
            WintrustCatalogInfo.cbCalculatedFileHash = HashSize;

            StringCchCopyW( UnicodeKey, MAX_PATH, Key);
            CharLowerW( UnicodeKey );

            WintrustCatalogInfo.pcwszMemberTag = UnicodeKey;

            PrevCat = NULL;
            hCatInfo = m_pCryptCATAdminEnumCatalogFromHash(
                hCatAdmin,
                Hash,
                HashSize,
                0,
                &PrevCat );

            while (hCatInfo) {
                CatInfo.cbStruct = sizeof(CATALOG_INFO);
                if (m_pCryptCATCatalogInfoFromContext( hCatInfo, &CatInfo, 0 )) {

                    CatalogFullPath = CatInfo.wszCatalogFile;
                    WintrustCatalogInfo.pcwszCatalogFilePath = CatInfo.wszCatalogFile;

                    Err = (DWORD)m_pWinVerifyTrust(NULL,
                        &DriverVerifyGuid,
                        &WintrustData
                        );

                    if (NO_ERROR  == Err) {

                        if (GetEmbedSignSubject(CatInfo.wszCatalogFile, subInfo))
                        {
                            CHAR szInfo[1024] = {0};

                            WideCharToMultiByte( CP_ACP,
                                0,
                                CatInfo.wszCatalogFile,
                                -1,
                                szInfo,
                                1024,
                                NULL,
                                NULL );
                            subInfo.push_back(std::string(szInfo));
                            // m_pCryptCATAdminReleaseCatalogContext( hCatAdmin, hCatInfo, 0 );

                            fRetval = TRUE;
                            break;
                        }
                    }
                }

                PrevCat = hCatInfo;

                hCatInfo = m_pCryptCATAdminEnumCatalogFromHash(
                    hCatAdmin, Hash, HashSize, 0, &PrevCat );

            }

clean0:
            if (Hash) {

                delete[] Hash;
                Hash = NULL;
            }

            if (hCatAdmin) {

                m_pCryptCATAdminReleaseContext( hCatAdmin, 0 );
            }

            if (hFile) {

                ::CloseHandle( hFile );
                hFile = NULL;
            }

            return fRetval;
        }
Exemple #22
0
static DWORD shgfi_get_exe_type(LPCWSTR szFullPath)
{
    BOOL status = FALSE;
    HANDLE hfile;
    DWORD BinaryType;
    IMAGE_DOS_HEADER mz_header;
    IMAGE_NT_HEADERS nt;
    DWORD len;
    char magic[4];

    status = GetBinaryTypeW (szFullPath, &BinaryType);
    if (!status)
        return 0;
    if (BinaryType == SCS_DOS_BINARY || BinaryType == SCS_PIF_BINARY)
        return 0x4d5a;

    hfile = CreateFileW( szFullPath, GENERIC_READ, FILE_SHARE_READ,
                         NULL, OPEN_EXISTING, 0, 0 );
    if ( hfile == INVALID_HANDLE_VALUE )
        return 0;

    /*
     * The next section is adapted from MODULE_GetBinaryType, as we need
     * to examine the image header to get OS and version information. We
     * know from calling GetBinaryTypeA that the image is valid and either
     * an NE or PE, so much error handling can be omitted.
     * Seek to the start of the file and read the header information.
     */

    SetFilePointer( hfile, 0, NULL, SEEK_SET );
    ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL );

    SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
    ReadFile( hfile, magic, sizeof(magic), &len, NULL );
    if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
    {
        SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
        ReadFile( hfile, &nt, sizeof(nt), &len, NULL );
        CloseHandle( hfile );
        /* DLL files are not executable and should return 0 */
        if (nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
            return 0;
        if (nt.OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
        {
             return IMAGE_NT_SIGNATURE | 
                   (nt.OptionalHeader.MajorSubsystemVersion << 24) |
                   (nt.OptionalHeader.MinorSubsystemVersion << 16);
        }
        return IMAGE_NT_SIGNATURE;
    }
    else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
    {
        IMAGE_OS2_HEADER ne;
        SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
        ReadFile( hfile, &ne, sizeof(ne), &len, NULL );
        CloseHandle( hfile );
        if (ne.ne_exetyp == 2)
            return IMAGE_OS2_SIGNATURE | (ne.ne_expver << 16);
        return 0;
    }
    CloseHandle( hfile );
    return 0;
}
Exemple #23
0
int process_start(char *name, char *part, process_info_t *p, int is_helper) {
  HANDLE file = INVALID_HANDLE_VALUE;
  HANDLE nul = INVALID_HANDLE_VALUE;
  WCHAR path[MAX_PATH], filename[MAX_PATH];
  WCHAR image[MAX_PATH + 1];
  WCHAR args[MAX_PATH * 2];
  STARTUPINFOW si;
  PROCESS_INFORMATION pi;
  DWORD result;

  if (GetTempPathW(sizeof(path) / sizeof(WCHAR), (WCHAR*)&path) == 0)
    goto error;
  if (GetTempFileNameW((WCHAR*)&path, L"uv", 0, (WCHAR*)&filename) == 0)
    goto error;

  file = CreateFileW((WCHAR*)filename,
                     GENERIC_READ | GENERIC_WRITE,
                     0,
                     NULL,
                     CREATE_ALWAYS,
                     FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
                     NULL);
  if (file == INVALID_HANDLE_VALUE)
    goto error;

  if (!SetHandleInformation(file, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
    goto error;

  nul = CreateFileA("nul",
                    GENERIC_READ,
                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                    NULL,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL,
                    NULL);
  if (nul == INVALID_HANDLE_VALUE)
    goto error;

  if (!SetHandleInformation(nul, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
    goto error;

  result = GetModuleFileNameW(NULL,
                              (WCHAR*) &image,
                              sizeof(image) / sizeof(WCHAR));
  if (result == 0 || result == sizeof(image))
    goto error;

  if (part) {
    if (_snwprintf((WCHAR*)args,
                   sizeof(args) / sizeof(WCHAR),
                   L"\"%s\" %S %S",
                   image,
                   name,
                   part) < 0) {
      goto error;
    }
  } else {
    if (_snwprintf((WCHAR*)args,
                   sizeof(args) / sizeof(WCHAR),
                   L"\"%s\" %S",
                   image,
                   name) < 0) {
      goto error;
    }
  }

  memset((void*)&si, 0, sizeof(si));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESTDHANDLES;
  si.hStdInput = nul;
  si.hStdOutput = file;
  si.hStdError = file;

  if (!CreateProcessW(image, args, NULL, NULL, TRUE,
                      0, NULL, NULL, &si, &pi))
    goto error;

  CloseHandle(pi.hThread);

  SetHandleInformation(nul, HANDLE_FLAG_INHERIT, 0);
  SetHandleInformation(file, HANDLE_FLAG_INHERIT, 0);

  p->stdio_in = nul;
  p->stdio_out = file;
  p->process = pi.hProcess;
  p->name = part;

  return 0;

error:
  if (file != INVALID_HANDLE_VALUE)
    CloseHandle(file);
  if (nul != INVALID_HANDLE_VALUE)
    CloseHandle(nul);

  return -1;
}
Exemple #24
0
/***********************************************************************
 *      CryptCATOpen  (WINTRUST.@)
 */
HANDLE WINAPI CryptCATOpen(LPWSTR pwszFileName, DWORD fdwOpenFlags, HCRYPTPROV hProv,
                           DWORD dwPublicVersion, DWORD dwEncodingType)
{
    HANDLE file, hmsg;
    BYTE *buffer = NULL;
    DWORD size, flags = OPEN_EXISTING;
    struct cryptcat *cc;

    TRACE("%s, %x, %lx, %x, %x\n", debugstr_w(pwszFileName), fdwOpenFlags,
          hProv, dwPublicVersion, dwEncodingType);

    if (!pwszFileName)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return INVALID_HANDLE_VALUE;
    }

    if (!dwEncodingType)  dwEncodingType  = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;

    if (fdwOpenFlags & CRYPTCAT_OPEN_ALWAYS)    flags |= OPEN_ALWAYS;
    if (fdwOpenFlags & CRYPTCAT_OPEN_CREATENEW) flags |= CREATE_NEW;

    file = CreateFileW(pwszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, flags, 0, NULL);
    if (file == INVALID_HANDLE_VALUE) return INVALID_HANDLE_VALUE;

    size = GetFileSize(file, NULL);
    if (!(buffer = HeapAlloc(GetProcessHeap(), 0, size)))
    {
        CloseHandle(file);
        SetLastError(ERROR_OUTOFMEMORY);
        return INVALID_HANDLE_VALUE;
    }
    if (!(hmsg = CryptMsgOpenToDecode(dwEncodingType, 0, 0, hProv, NULL, NULL)))
    {
        CloseHandle(file);
        HeapFree(GetProcessHeap(), 0, buffer);
        return INVALID_HANDLE_VALUE;
    }
    if (!ReadFile(file, buffer, size, &size, NULL) || !CryptMsgUpdate(hmsg, buffer, size, TRUE))
    {
        CloseHandle(file);
        HeapFree(GetProcessHeap(), 0, buffer);
        CryptMsgClose(hmsg);
        return INVALID_HANDLE_VALUE;
    }
    HeapFree(GetProcessHeap(), 0, buffer);
    CloseHandle(file);

    size = sizeof(DWORD);
    if (!(cc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*cc))))
    {
        CryptMsgClose(hmsg);
        SetLastError(ERROR_OUTOFMEMORY);
        return INVALID_HANDLE_VALUE;
    }

    cc->msg = hmsg;
    cc->encoding = dwEncodingType;
    if (CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_COUNT_PARAM, 0, &cc->attr_count, &size))
    {
        DWORD i, sum = 0;
        BYTE *p;

        for (i = 0; i < cc->attr_count; i++)
        {
            if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, NULL, &size))
            {
                CryptMsgClose(hmsg);
                return INVALID_HANDLE_VALUE;
            }
            sum += size;
        }
        if (!(cc->attr = HeapAlloc(GetProcessHeap(), 0, sizeof(*cc->attr) * cc->attr_count + sum)))
        {
            CryptMsgClose(hmsg);
            SetLastError(ERROR_OUTOFMEMORY);
            return INVALID_HANDLE_VALUE;
        }
        p = (BYTE *)(cc->attr + cc->attr_count);
        for (i = 0; i < cc->attr_count; i++)
        {
            if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, NULL, &size))
            {
                CryptMsgClose(hmsg);
                HeapFree(GetProcessHeap(), 0, cc->attr);
                return INVALID_HANDLE_VALUE;
            }
            if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, p, &size))
            {
                CryptMsgClose(hmsg);
                HeapFree(GetProcessHeap(), 0, cc->attr);
                return INVALID_HANDLE_VALUE;
            }
            p += size;
        }
        cc->inner = decode_inner_content(hmsg, dwEncodingType, &cc->inner_len);
        if (!cc->inner || !CryptSIPRetrieveSubjectGuid(pwszFileName, NULL, &cc->subject))
        {
            CryptMsgClose(hmsg);
            HeapFree(GetProcessHeap(), 0, cc->attr);
            HeapFree(GetProcessHeap(), 0, cc->inner);
            HeapFree(GetProcessHeap(), 0, cc);
            return INVALID_HANDLE_VALUE;
        }
        cc->magic = CRYPTCAT_MAGIC;
        return cc;
    }
    return INVALID_HANDLE_VALUE;
}
Exemple #25
0
// Entry point where control comes on an unhandled exception
static
LONG WINAPI TopLevelExceptionFilter(PEXCEPTION_POINTERS pExceptionInfo)
{
	static bool bBeenHere = FALSE;

	if(!bBeenHere)
	{
		UINT fuOldErrorMode;

		bBeenHere = TRUE;

		fuOldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);

		hReportFile = CreateFileW(
			szLogFileName,
			GENERIC_WRITE,
			0,
			0,
			OPEN_ALWAYS,
			FILE_FLAG_WRITE_THROUGH,
			0
		);
		if (hReportFile == INVALID_HANDLE_VALUE)
		{
			// Retrieve the system error message for the last-error code

			LPVOID lpMsgBuf;
			DWORD dw = GetLastError();
			TCHAR szBuffer[4196];

			FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER |
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				dw,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
				(LPTSTR) &lpMsgBuf,
				0, NULL );

			wsprintf(szBuffer, _T("Exception handler failed with error %d: %s\n"), dw, lpMsgBuf);
			MessageBox((HWND)MB_ICONEXCLAMATION, szBuffer, _T("Error"), MB_OK);

			LocalFree(lpMsgBuf);
			debug(LOG_ERROR, "Exception handler failed to create file!");
		}

#ifdef HAVE_BFD
		bfd_set_error_handler((bfd_error_handler_type) rprintf);
#endif /* HAVE_BFD */

		if (hReportFile)
		{
			wchar_t szBuffer[4196];
			int err;

			SetFilePointer(hReportFile, 0, 0, FILE_END);

			// FIXME: We don't return from the below function call
			GenerateExceptionReport(pExceptionInfo);
			CloseHandle(hReportFile);

			wsprintfW(szBuffer, L"Warzone has crashed.\r\nSee %s for more details\r\n", szLogFileName);
			err = MessageBoxW((HWND)MB_ICONERROR, szBuffer, L"Warzone Crashed!", MB_OK | MB_ICONERROR);
			if (err == 0)
			{
				LPVOID lpMsgBuf;
				DWORD dw = GetLastError();
				wchar_t szBuffer[4196];

				FormatMessageW(
					FORMAT_MESSAGE_ALLOCATE_BUFFER |
					FORMAT_MESSAGE_FROM_SYSTEM |
					FORMAT_MESSAGE_IGNORE_INSERTS,
					NULL,
					dw,
					MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
					(LPWSTR) &lpMsgBuf,
					0, NULL );

				wsprintfW(szBuffer, L"Exception handler failed with error %d: %s\n", dw, lpMsgBuf);
				MessageBoxW((HWND)MB_ICONEXCLAMATION, szBuffer, L"Error", MB_OK);

				LocalFree(lpMsgBuf);
				debug(LOG_ERROR, "Exception handler failed to create file!");
			}
			hReportFile = 0;
		}
		SetErrorMode(fuOldErrorMode);
	}

	if(prevExceptionFilter)
		return prevExceptionFilter(pExceptionInfo);
	else
		return EXCEPTION_CONTINUE_SEARCH;
}
Exemple #26
0
static BOOL WINTRUST_GetSignedMsgFromPEFile(SIP_SUBJECTINFO *pSubjectInfo,
 DWORD *pdwEncodingType, DWORD dwIndex, DWORD *pcbSignedDataMsg,
 BYTE *pbSignedDataMsg)
{
    BOOL ret;
    WIN_CERTIFICATE *pCert = NULL;
    HANDLE file;

    TRACE("(%p %p %d %p %p)\n", pSubjectInfo, pdwEncodingType, dwIndex,
          pcbSignedDataMsg, pbSignedDataMsg);

    if(pSubjectInfo->hFile && pSubjectInfo->hFile!=INVALID_HANDLE_VALUE)
        file = pSubjectInfo->hFile;
    else
    {
        file = CreateFileW(pSubjectInfo->pwsFileName, GENERIC_READ,
                FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        if(file == INVALID_HANDLE_VALUE)
            return FALSE;
    }
 
    if (!pbSignedDataMsg)
    {
        WIN_CERTIFICATE cert;

        /* app hasn't passed buffer, just get the length */
        ret = ImageGetCertificateHeader(file, dwIndex, &cert);
        if (ret)
        {
            switch (cert.wCertificateType)
            {
            case WIN_CERT_TYPE_X509:
            case WIN_CERT_TYPE_PKCS_SIGNED_DATA:
                *pcbSignedDataMsg = cert.dwLength;
                break;
            default:
                WARN("unknown certificate type %d\n", cert.wCertificateType);
                ret = FALSE;
            }
        }
    }
    else
    {
        DWORD len = 0;

        ret = ImageGetCertificateData(file, dwIndex, NULL, &len);
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
            goto error;
        pCert = HeapAlloc(GetProcessHeap(), 0, len);
        if (!pCert)
        {
            ret = FALSE;
            goto error;
        }
        ret = ImageGetCertificateData(file, dwIndex, pCert, &len);
        if (!ret)
            goto error;
        pCert->dwLength -= FIELD_OFFSET(WIN_CERTIFICATE, bCertificate);
        if (*pcbSignedDataMsg < pCert->dwLength)
        {
            *pcbSignedDataMsg = pCert->dwLength;
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            ret = FALSE;
        }
        else
        {
            memcpy(pbSignedDataMsg, pCert->bCertificate, pCert->dwLength);
            *pcbSignedDataMsg = pCert->dwLength;
            switch (pCert->wCertificateType)
            {
            case WIN_CERT_TYPE_X509:
                *pdwEncodingType = X509_ASN_ENCODING;
                break;
            case WIN_CERT_TYPE_PKCS_SIGNED_DATA:
                *pdwEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
                break;
            default:
                WARN("don't know what to do for encoding type %d\n",
                 pCert->wCertificateType);
                *pdwEncodingType = 0;
                ret = FALSE;
            }
        }
    }
error:
    if(pSubjectInfo->hFile != file)
        CloseHandle(file);
    HeapFree(GetProcessHeap(), 0, pCert);
    return ret;
}
/**
 * Processes a software update command
 *
 * @param  argc           The number of arguments in argv
 * @param  argv           The arguments normally passed to updater.exe
 *                        argv[0] must be the path to updater.exe
 * @return TRUE if the update was successful.
 */
BOOL
ProcessSoftwareUpdateCommand(DWORD argc, LPWSTR *argv)
{
  BOOL result = TRUE;
  if (argc < 3) {
    LOG_WARN(("Not enough command line parameters specified. "
              "Updating update.status."));

    // We can only update update.status if argv[1] exists.  argv[1] is
    // the directory where the update.status file exists.
    if (argc < 2 || 
        !WriteStatusFailure(argv[1], 
                            SERVICE_NOT_ENOUGH_COMMAND_LINE_ARGS)) {
      LOG_WARN(("Could not write update.status service update failure.  (%d)",
                GetLastError()));
    }
    return FALSE;
  }

  WCHAR installDir[MAX_PATH] = {L'\0'};
  if (!GetInstallationDir(argc, argv, installDir)) {
    LOG_WARN(("Could not get the installation directory"));
    if (!WriteStatusFailure(argv[1],
                            SERVICE_INSTALLDIR_ERROR)) {
      LOG_WARN(("Could not write update.status for GetInstallationDir failure."));
    }
    return FALSE;
  }

  // Make sure the path to the updater to use for the update is local.
  // We do this check to make sure that file locking is available for
  // race condition security checks.
  BOOL isLocal = FALSE;
  if (!IsLocalFile(argv[0], isLocal) || !isLocal) {
    LOG_WARN(("Filesystem in path %ls is not supported (%d)",
              argv[0], GetLastError()));
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_UPDATER_NOT_FIXED_DRIVE)) {
      LOG_WARN(("Could not write update.status service update failure.  (%d)",
                GetLastError()));
    }
    return FALSE;
  }

  nsAutoHandle noWriteLock(CreateFileW(argv[0], GENERIC_READ, FILE_SHARE_READ, 
                                       NULL, OPEN_EXISTING, 0, NULL));
  if (INVALID_HANDLE_VALUE == noWriteLock) {
      LOG_WARN(("Could not set no write sharing access on file.  (%d)",
                GetLastError()));
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_COULD_NOT_LOCK_UPDATER)) {
      LOG_WARN(("Could not write update.status service update failure.  (%d)",
                GetLastError()));
    }
    return FALSE;
  }

  // Verify that the updater.exe that we are executing is the same
  // as the one in the installation directory which we are updating.
  // The installation dir that we are installing to is installDir.
  WCHAR installDirUpdater[MAX_PATH + 1] = {L'\0'};
  wcsncpy(installDirUpdater, installDir, MAX_PATH);
  if (!PathAppendSafe(installDirUpdater, L"updater.exe")) {
    LOG_WARN(("Install directory updater could not be determined."));
    result = FALSE;
  }

  BOOL updaterIsCorrect;
  if (result && !VerifySameFiles(argv[0], installDirUpdater, 
                                 updaterIsCorrect)) {
    LOG_WARN(("Error checking if the updaters are the same.\n"
              "Path 1: %ls\nPath 2: %ls", argv[0], installDirUpdater));
    result = FALSE;
  }

  if (result && !updaterIsCorrect) {
    LOG_WARN(("The updaters do not match, udpater will not run.")); 
    result = FALSE;
  }

  if (result) {
    LOG(("updater.exe was compared successfully to the installation directory"
         " updater.exe."));
  } else {
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_UPDATER_COMPARE_ERROR)) {
      LOG_WARN(("Could not write update.status updater compare failure."));
    }
    return FALSE;
  }

  // Check to make sure the udpater.exe module has the unique updater identity.
  // This is a security measure to make sure that the signed executable that
  // we will run is actually an updater.
  HMODULE updaterModule = LoadLibraryEx(argv[0], NULL, 
                                        LOAD_LIBRARY_AS_DATAFILE);
  if (!updaterModule) {
    LOG_WARN(("updater.exe module could not be loaded. (%d)", GetLastError()));
    result = FALSE;
  } else {
    char updaterIdentity[64];
    if (!LoadStringA(updaterModule, IDS_UPDATER_IDENTITY, 
                     updaterIdentity, sizeof(updaterIdentity))) {
      LOG_WARN(("The updater.exe application does not contain the Mozilla"
                " updater identity."));
      result = FALSE;
    }

    if (strcmp(updaterIdentity, UPDATER_IDENTITY_STRING)) {
      LOG_WARN(("The updater.exe identity string is not valid."));
      result = FALSE;
    }
    FreeLibrary(updaterModule);
  }

  if (result) {
    LOG(("The updater.exe application contains the Mozilla"
          " updater identity."));
  } else {
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_UPDATER_IDENTITY_ERROR)) {
      LOG_WARN(("Could not write update.status no updater identity."));
    }
    return TRUE;
  }

  // Check for updater.exe sign problems
  BOOL updaterSignProblem = FALSE;
#ifndef DISABLE_UPDATER_AUTHENTICODE_CHECK
  updaterSignProblem = !DoesBinaryMatchAllowedCertificates(installDir,
                                                           argv[0]);
#endif

  // Only proceed with the update if we have no signing problems
  if (!updaterSignProblem) {
    BOOL updateProcessWasStarted = FALSE;
    if (StartUpdateProcess(argc, argv, installDir,
                           updateProcessWasStarted)) {
      LOG(("updater.exe was launched and run successfully!"));
      LogFlush();

      // Don't attempt to update the service when the update is being staged.
      if (!IsUpdateBeingStaged(argc, argv)) {
        // We might not execute code after StartServiceUpdate because
        // the service installer will stop the service if it is running.
        StartServiceUpdate(installDir);
      }
    } else {
      result = FALSE;
      LOG_WARN(("Error running update process. Updating update.status  (%d)",
                GetLastError()));
      LogFlush();

      // If the update process was started, then updater.exe is responsible for
      // setting the failure code.  If it could not be started then we do the 
      // work.  We set an error instead of directly setting status pending 
      // so that the app.update.service.errors pref can be updated when 
      // the callback app restarts.
      if (!updateProcessWasStarted) {
        if (!WriteStatusFailure(argv[1], 
                                SERVICE_UPDATER_COULD_NOT_BE_STARTED)) {
          LOG_WARN(("Could not write update.status service update failure.  (%d)",
                    GetLastError()));
        }
      }
    }
  } else {
    result = FALSE;
    LOG_WARN(("Could not start process due to certificate check error on "
              "updater.exe. Updating update.status.  (%d)", GetLastError()));

    // When there is a certificate check error on the updater.exe application,
    // we want to write out the error.
    if (!WriteStatusFailure(argv[1], 
                            SERVICE_UPDATER_SIGN_ERROR)) {
      LOG_WARN(("Could not write pending state to update.status.  (%d)",
                GetLastError()));
    }
  }

  return result;
}
Exemple #28
0
oslPipe SAL_CALL osl_createPipe(rtl_uString *strPipeName, oslPipeOptions Options,
                       oslSecurity Security)
{
    rtl_uString* name = NULL;
    rtl_uString* path = NULL;
    rtl_uString* temp = NULL;
    oslPipe pPipe;

       PSECURITY_ATTRIBUTES  pSecAttr = NULL;

    rtl_uString_newFromAscii(&path, PIPESYSTEM);
    rtl_uString_newFromAscii(&name, PIPEPREFIX);

    if ( Security)
    {
        rtl_uString *Ident = NULL;
        rtl_uString *Delim = NULL;

        OSL_VERIFY(osl_getUserIdent(Security, &Ident));
        rtl_uString_newFromAscii(&Delim, "_");

        rtl_uString_newConcat(&temp, name, Ident);
        rtl_uString_newConcat(&name, temp, Delim);

        rtl_uString_release(Ident);
        rtl_uString_release(Delim);
    }
    else
    {
        if (Options & osl_Pipe_CREATE)
        {
            PSECURITY_DESCRIPTOR pSecDesc;

            pSecDesc = (PSECURITY_DESCRIPTOR) rtl_allocateMemory(SECURITY_DESCRIPTOR_MIN_LENGTH);

            /* add a NULL disc. ACL to the security descriptor */
            OSL_VERIFY(InitializeSecurityDescriptor(pSecDesc, SECURITY_DESCRIPTOR_REVISION));
            OSL_VERIFY(SetSecurityDescriptorDacl(pSecDesc, TRUE, (PACL) NULL, FALSE));

            pSecAttr = rtl_allocateMemory(sizeof(SECURITY_ATTRIBUTES));
            pSecAttr->nLength = sizeof(SECURITY_ATTRIBUTES);
            pSecAttr->lpSecurityDescriptor = pSecDesc;
            pSecAttr->bInheritHandle = TRUE;
        }
    }

    rtl_uString_assign(&temp, name);
    rtl_uString_newConcat(&name, temp, strPipeName);

    /* alloc memory */
    pPipe= __osl_createPipeImpl();
    osl_atomic_increment(&(pPipe->m_Reference));

    /* build system pipe name */
    rtl_uString_assign(&temp, path);
    rtl_uString_newConcat(&path, temp, name);
    rtl_uString_release(temp);
    temp = NULL;

    if (Options & osl_Pipe_CREATE)
    {
        SetLastError( ERROR_SUCCESS );

        pPipe->m_NamedObject = CreateMutexW( NULL, FALSE, name->buffer );

        if ( pPipe->m_NamedObject != INVALID_HANDLE_VALUE && pPipe->m_NamedObject != NULL )
        {
            if ( GetLastError() != ERROR_ALREADY_EXISTS )
            {
                pPipe->m_Security = pSecAttr;
                rtl_uString_assign(&pPipe->m_Name, name);

                /* try to open system pipe */
                pPipe->m_File = CreateNamedPipeW(
                    path->buffer,
                    PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                    PIPE_WAIT | PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
                    PIPE_UNLIMITED_INSTANCES,
                    4096, 4096,
                    NMPWAIT_WAIT_FOREVER,
                    pPipe->m_Security);

                if (pPipe->m_File != INVALID_HANDLE_VALUE)
                {
                    rtl_uString_release( name );
                    rtl_uString_release( path );

                    return pPipe;
                }
            }
            else
            {
                CloseHandle( pPipe->m_NamedObject );
                pPipe->m_NamedObject = INVALID_HANDLE_VALUE;
            }
        }
    }
    else
    {
        BOOL    fPipeAvailable;

        do
        {
            /* free instance should be available first */
            fPipeAvailable = WaitNamedPipeW(path->buffer, NMPWAIT_WAIT_FOREVER);

            /* first try to open system pipe */
            if ( fPipeAvailable )
            {
                pPipe->m_File = CreateFileW(
                    path->buffer,
                    GENERIC_READ|GENERIC_WRITE,
                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                    NULL,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                    NULL);

                if ( pPipe->m_File != INVALID_HANDLE_VALUE )
                {
                    // We got it !
                    rtl_uString_release( name );
                    rtl_uString_release( path );

                    return (pPipe);
                }
                else
                {
                    // Pipe instance maybe catched by another client -> try again
                }
            }
        } while ( fPipeAvailable );
    }

    /* if we reach here something went wrong */
    __osl_destroyPipeImpl(pPipe);

    return NULL;
}
Exemple #29
0
int __cdecl main(int argc, char *argv[])

{



    BOOL testPass = TRUE;

    BOOL bRc = TRUE;

    HANDLE hFile; 



    const char* sBadFilePath = "bad/badPath.tmp";

    const char* sBadFileName = "badName.tmp";

    const char* sDest = "dest.tmp";

    const WCHAR wBadFilePath[] = 

        {'w','b','a','d','/','b','a',

        'd','.','t','m','p','\0'};

    const WCHAR wBadFileName[] = 

        {'w','B','a','d','.','t','m','p','\0'};

    const WCHAR wDest[] = 

        {'w','d','e','s','t','.','t','m','p','\0'};





    if (0 != PAL_Initialize(argc,argv))

    {

        return FAIL;

    }



    /*...................Test CopyFileW.............................*/



    /* test with an invalid path */

    bRc = CopyFileW(wBadFilePath,wDest,TRUE);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("CopyFileW: calling GetLastError() after copying a file"

                " with wrong path returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        testPass = FALSE; 

    }



    /* test with invalid file name */

    bRc = CopyFileW(wBadFileName,wDest,TRUE);

    if(!bRc)

    { 

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("CopyFileW: calling GetLastError() after copying a file"

                " with wrong name returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }



    }

    else

    {

        Trace("CopyFileW: managed to copy a file with wrong name\n");     

        testPass = FALSE;

    }



  



    /*..................CopyFileA...................................*/



    /* test with an invalid path */

    bRc = CopyFileA(sBadFilePath,sDest,TRUE);

    if(! bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("CopyFileA: calling GetLastError() after copying a file"

                " with wrong path returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("CopyFileA: managed to copy a file with wrong path\n");     

        testPass = FALSE;

    }



    /* test with an invalid file name */

    bRc = CopyFileA(sBadFileName,sDest,TRUE);

    if(! bRc)

    { 

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("CopyFileA: calling GetLastError() after copying a file"

                " with wrong name returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("CopyFileA: managed to copy a file with wrong name\n"); 

        testPass = FALSE;

    }



    



    /*............. Test CreateFileA..................................*/



    /* test with an invalid file name */

    hFile = CreateFileA(sBadFileName,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("CreateFileA: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad File Name\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileA: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileA: Call to CloseHandle failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFile(sBadFileName))

        {

            Trace("CreateFileA: Call to DeleteFile failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }



    /* test with an invalid path */

    hFile = CreateFileA(sBadFilePath,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("CreateFileA: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad file path name\n",

                GetLastError(), ERROR_PATH_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileA: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;

        /*this should not happen*/

        if(!CloseHandle(hFile))

        {

            Trace("CreateFileA: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFile(sBadFilePath))

        {

            Trace("CreateFileA: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }





    



    /*............. Test CreateFileW..................................*/



    /* test with an invalid file name */

    hFile = CreateFileW(wBadFileName,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("CreateFileW: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad filename\n",

                GetLastError(), ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileW: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileW: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }



        if(!DeleteFileW(wBadFileName))

        {

            Trace("CreateFileW: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }







    /* test with an invalid path */

    hFile = CreateFileW(wBadFilePath,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 



        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("CreateFileW: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad file path \n",

                GetLastError(), ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileW: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileW: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFileW(wBadFilePath))

        {

            Trace("CreateFileW: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }





    

    /* .............  DeleteFileW..................................*/



    /* test with an invalid path */

    if(DeleteFileW(wBadFilePath))

    {

        Trace("DeleteFileW: Call to DeleteFileW to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("DeleteFileW: Call GetLastError()returned "

                "[%u] while it should return ERROR_PATH_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



    /* test with an invalid file name */

    if(DeleteFileW(wBadFileName))

    {

        Trace("DeleteFileW: Call to DeleteFileW to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("DeleteFileW: Call GetLastError()returned [%u]"

                " while it should return ERROR_FILE_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }





    /* .............  DeleteFileA..................................*/



    /* test with an invalid path */

    if(DeleteFileA(sBadFilePath))

    {

        Trace("DeleteFileA: Call to DeleteFileA to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("DeleteFileA: Call GetLastError() returned [%u]"

                " while it should return ERROR_PATH_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



    /* test with an invalid file name */

    if(DeleteFileA(sBadFileName))

    {

        Trace("DeleteFileA: Call to DeleteFileA to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("DeleteFileA: Call GetLastError() returned [%u]"

                " while it should return ERROR_FILE_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



  



    if(! testPass)

    {

        Fail("");

    }

    PAL_Terminate();

    return PASS;

}
Exemple #30
-1
RTR3DECL(int) RTPathQueryInfoEx(const char *pszPath, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs, uint32_t fFlags)
{
    /*
     * Validate input.
     */
    AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
    AssertReturn(*pszPath, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pObjInfo, VERR_INVALID_POINTER);
    AssertMsgReturn(    enmAdditionalAttribs >= RTFSOBJATTRADD_NOTHING
                    &&  enmAdditionalAttribs <= RTFSOBJATTRADD_LAST,
                    ("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs),
                    VERR_INVALID_PARAMETER);
    AssertMsgReturn(RTPATH_F_IS_VALID(fFlags, 0), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);

    /*
     * Query file info.
     */
    WIN32_FILE_ATTRIBUTE_DATA Data;
    PRTUTF16 pwszPath;
    int rc = RTStrToUtf16(pszPath, &pwszPath);
    if (RT_FAILURE(rc))
        return rc;
    if (!GetFileAttributesExW(pwszPath, GetFileExInfoStandard, &Data))
    {
        /* Fallback to FindFileFirst in case of sharing violation. */
        if (GetLastError() == ERROR_SHARING_VIOLATION)
        {
            WIN32_FIND_DATAW FindData;
            HANDLE hDir = FindFirstFileW(pwszPath, &FindData);
            if (hDir == INVALID_HANDLE_VALUE)
            {
                rc = RTErrConvertFromWin32(GetLastError());
                RTUtf16Free(pwszPath);
                return rc;
            }
            FindClose(hDir);

            Data.dwFileAttributes   = FindData.dwFileAttributes;
            Data.ftCreationTime     = FindData.ftCreationTime;
            Data.ftLastAccessTime   = FindData.ftLastAccessTime;
            Data.ftLastWriteTime    = FindData.ftLastWriteTime;
            Data.nFileSizeHigh      = FindData.nFileSizeHigh;
            Data.nFileSizeLow       = FindData.nFileSizeLow;
        }
        else
        {
            rc = RTErrConvertFromWin32(GetLastError());
            RTUtf16Free(pwszPath);
            return rc;
        }
    }

    /*
     * Getting the information for the link target is a bit annoying and
     * subject to the same access violation mess as above.. :/
     */
    /** @todo we're too lazy wrt to error paths here... */
    if (   (fFlags & RTPATH_F_FOLLOW_LINK)
        && (Data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
    {
        HANDLE hFinal = CreateFileW(pwszPath,
                                    GENERIC_READ,
                                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                    NULL,
                                    OPEN_EXISTING,
                                    FILE_FLAG_BACKUP_SEMANTICS,
                                    NULL);
        if (hFinal != INVALID_HANDLE_VALUE)
        {
            BY_HANDLE_FILE_INFORMATION FileData;
            if (GetFileInformationByHandle(hFinal, &FileData))
            {
                Data.dwFileAttributes   = FileData.dwFileAttributes;
                Data.ftCreationTime     = FileData.ftCreationTime;
                Data.ftLastAccessTime   = FileData.ftLastAccessTime;
                Data.ftLastWriteTime    = FileData.ftLastWriteTime;
                Data.nFileSizeHigh      = FileData.nFileSizeHigh;
                Data.nFileSizeLow       = FileData.nFileSizeLow;
            }
            CloseHandle(hFinal);
        }
        else if (GetLastError() != ERROR_SHARING_VIOLATION)
        {
            rc = RTErrConvertFromWin32(GetLastError());
            RTUtf16Free(pwszPath);
            return rc;
        }
    }

    RTUtf16Free(pwszPath);

    /*
     * Setup the returned data.
     */
    pObjInfo->cbObject    = ((uint64_t)Data.nFileSizeHigh << 32)
                          |  (uint64_t)Data.nFileSizeLow;
    pObjInfo->cbAllocated = pObjInfo->cbObject;

    Assert(sizeof(uint64_t) == sizeof(Data.ftCreationTime));
    RTTimeSpecSetNtTime(&pObjInfo->BirthTime,         *(uint64_t *)&Data.ftCreationTime);
    RTTimeSpecSetNtTime(&pObjInfo->AccessTime,        *(uint64_t *)&Data.ftLastAccessTime);
    RTTimeSpecSetNtTime(&pObjInfo->ModificationTime,  *(uint64_t *)&Data.ftLastWriteTime);
    pObjInfo->ChangeTime  = pObjInfo->ModificationTime;

    pObjInfo->Attr.fMode  = rtFsModeFromDos((Data.dwFileAttributes << RTFS_DOS_SHIFT) & RTFS_DOS_MASK_NT,
                                            pszPath, strlen(pszPath));

    /*
     * Requested attributes (we cannot provide anything actually).
     */
    switch (enmAdditionalAttribs)
    {
        case RTFSOBJATTRADD_NOTHING:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_NOTHING;
            break;

        case RTFSOBJATTRADD_UNIX:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_UNIX;
            pObjInfo->Attr.u.Unix.uid             = ~0U;
            pObjInfo->Attr.u.Unix.gid             = ~0U;
            pObjInfo->Attr.u.Unix.cHardlinks      = 1;
            pObjInfo->Attr.u.Unix.INodeIdDevice   = 0; /** @todo use volume serial number */
            pObjInfo->Attr.u.Unix.INodeId         = 0; /** @todo use fileid (see GetFileInformationByHandle). */
            pObjInfo->Attr.u.Unix.fFlags          = 0;
            pObjInfo->Attr.u.Unix.GenerationId    = 0;
            pObjInfo->Attr.u.Unix.Device          = 0;
            break;

        case RTFSOBJATTRADD_UNIX_OWNER:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_UNIX_OWNER;
            pObjInfo->Attr.u.UnixOwner.uid        = ~0U;
            pObjInfo->Attr.u.UnixOwner.szName[0]  = '\0'; /** @todo return something sensible here. */
            break;

        case RTFSOBJATTRADD_UNIX_GROUP:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_UNIX_GROUP;
            pObjInfo->Attr.u.UnixGroup.gid        = ~0U;
            pObjInfo->Attr.u.UnixGroup.szName[0]  = '\0';
            break;

        case RTFSOBJATTRADD_EASIZE:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_EASIZE;
            pObjInfo->Attr.u.EASize.cb            = 0;
            break;

        default:
            AssertMsgFailed(("Impossible!\n"));
            return VERR_INTERNAL_ERROR;
    }

    return VINF_SUCCESS;
}