HRESULT CProteinSurfaceBase::CreateAdjacentVertex()
{
	char drive[_MAX_DRIVE];
	char dir[_MAX_DIR];
	char fname[_MAX_FNAME];
	char ext[_MAX_EXT];
	_splitpath(m_pPDB->m_strFilename, drive, dir, fname, ext );

	CString strSurfaceDir = GetMainApp()->m_strBaseSurfacePath;

	CString outputName;
	outputName.Format ( _T("%s%s_%02d_%c_%03d_%.2f_%d_%d_%d") , strSurfaceDir, fname, m_modelID, m_chainID, m_arrayAtom.size(), m_probeSphere, m_surfaceQuality, m_bAddHETATM, GetTypeGenSurface() );

	CString outputFilenameAdjacentVertex = outputName + _T(".Adjacent");

	BOOL bExistSurface = FALSE;
	HANDLE fileAdjacent = CreateFile( outputFilenameAdjacentVertex, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
	if( INVALID_HANDLE_VALUE != fileAdjacent )
	{
		bExistSurface = TRUE;
	}
	if ( fileAdjacent != INVALID_HANDLE_VALUE ) CloseHandle(fileAdjacent);

	BOOL bReadSuccess = FALSE;
	if ( bExistSurface == TRUE )
	{
		CFile fileAdjacentVertex;
		CFileException ex;
		if ( fileAdjacentVertex.Open(outputFilenameAdjacentVertex, CFile::modeRead, &ex) )
		{
			TCHAR buffHeader[512] = {0,};
			fileAdjacentVertex.Read(buffHeader, _tcslen(SURFACE_CURVATURE_HEADER));
			if ( CString(SURFACE_CURVATURE_HEADER) == CString(buffHeader) )
			{
				long numArray;
				fileAdjacentVertex.Read(&numArray, sizeof(long));

				m_ArrayArrayAdjacentVertex.clear();
				m_ArrayArrayAdjacentVertex.resize(numArray);

				long iProgress = GetMainActiveView()->InitProgress(100);
				for ( int i = 0 ; i < m_ArrayArrayAdjacentVertex.size(); i++ )
				{
					if ( i % (m_ArrayArrayAdjacentVertex.size()/100) == 0 )
						GetMainActiveView()->SetProgress(i*100/m_ArrayArrayAdjacentVertex.size(), iProgress);

					CSTLLONGArray & arrayAdjacentVertex = m_ArrayArrayAdjacentVertex[i];

					long numAdjacentVertex;
					fileAdjacentVertex.Read(&numAdjacentVertex, sizeof(long));
					arrayAdjacentVertex.resize(numAdjacentVertex);

					fileAdjacentVertex.Read(&arrayAdjacentVertex[0], sizeof(long)*numAdjacentVertex);
				}
				GetMainActiveView()->EndProgress(iProgress);

				fileAdjacentVertex.Close();

				if ( m_ArrayArrayAdjacentVertex.size() == i )
					bReadSuccess = TRUE;
			}
		}
	}

	if ( bReadSuccess == FALSE )
	{
		//	setArrayAdjacentVertex 를 구함
		m_ArrayArrayAdjacentVertex.clear();
		m_ArrayArrayAdjacentVertex.resize(m_arrayVertex.size());

		long iProgress = GetMainActiveView()->InitProgress(100);

		long deltaProgress = m_arrayIndexFace.size()/90;
		deltaProgress -= deltaProgress%3;

		//	
		for ( int i = 0 ; i < m_arrayIndexFace.size() ; i+=3 )
		{
			if ( deltaProgress && (i % deltaProgress == 0) )
				GetMainActiveView()->SetProgress(i*100/m_arrayIndexFace.size() , iProgress);

			long index1 = m_arrayIndexFace[i];
			long index2 = m_arrayIndexFace[i+1];
			long index3 = m_arrayIndexFace[i+2];

			if ( m_ArrayArrayAdjacentVertex[index1].capacity() == 0 )
				m_ArrayArrayAdjacentVertex[index1].reserve(20);
			if ( m_ArrayArrayAdjacentVertex[index2].capacity() == 0 )
				m_ArrayArrayAdjacentVertex[index2].reserve(20);
			if ( m_ArrayArrayAdjacentVertex[index3].capacity() == 0 )
				m_ArrayArrayAdjacentVertex[index3].reserve(20);

			m_ArrayArrayAdjacentVertex[index1].push_back(index2);
			m_ArrayArrayAdjacentVertex[index1].push_back(index3);

			m_ArrayArrayAdjacentVertex[index2].push_back(index1);
			m_ArrayArrayAdjacentVertex[index2].push_back(index3);

			m_ArrayArrayAdjacentVertex[index3].push_back(index1);
			m_ArrayArrayAdjacentVertex[index3].push_back(index2);
		}

		//	중복되는것 지움
		for ( int i = 0 ; i < m_ArrayArrayAdjacentVertex.size(); i++ )
		{
			CSTLLONGArray & arrayAdjacentVertex = m_ArrayArrayAdjacentVertex[i];
			for ( int j = 0 ; j < arrayAdjacentVertex.size() ; j++ )
			{
				for ( int k = j+1 ; k < arrayAdjacentVertex.size() ; k++ )
				{
					if ( arrayAdjacentVertex[j] == arrayAdjacentVertex[k] )
					{
						//	delete k.
						arrayAdjacentVertex.erase(arrayAdjacentVertex.begin()+k);
						//	20091010 수정.
						k--;
					}
				}
			}
		}

		//	outputFilenameAdjacentVertex 로 저장.
		CFile fileAdjacentVertex;
		CFileException ex;
		if ( !fileAdjacentVertex.Open(outputFilenameAdjacentVertex, CFile::modeWrite|CFile::modeCreate, &ex) )
		{
			fileAdjacentVertex.Write(SURFACE_CURVATURE_HEADER, _tcslen(SURFACE_CURVATURE_HEADER));

			long numArray = m_ArrayArrayAdjacentVertex.size();
			fileAdjacentVertex.Write(&numArray, sizeof(long));

			for ( int i = 0 ; i < m_ArrayArrayAdjacentVertex.size(); i++ )
			{
				CSTLLONGArray & arrayAdjacentVertex = m_ArrayArrayAdjacentVertex[i];

				long numAdjacentVertex = arrayAdjacentVertex.size();
				fileAdjacentVertex.Write(&numAdjacentVertex, sizeof(long));
				fileAdjacentVertex.Write(&arrayAdjacentVertex[0], sizeof(long)*arrayAdjacentVertex.size());
			}

			fileAdjacentVertex.Close();
		}
		GetMainActiveView()->EndProgress(iProgress);
	}

	return S_OK;
}
Example #2
1
bool CreateMRFromBMP(const char *psFileName, char *ppbBuffer, int *pdwBufferSize)
{
	// Open the BMP file.
	HANDLE hFile = CreateFile(psFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		// Print error and return.
		printf("ERROR: failed to open file %s!\n", psFileName);
		return false;
	}

	// Get the size of the file.
	int dwFileSize = GetFileSize(hFile, NULL);

	// Allocate a buffer for the BMP file.
	BYTE *pbBmpBuffer = new BYTE[dwFileSize];

	// Read the BMP file into memory.
	DWORD Count = 0;
	ReadFile(hFile, pbBmpBuffer, dwFileSize, &Count, NULL);

	// Close the BMP file.
	CloseHandle(hFile);

	// Parse the BMP header and check if the magic is valid.
	BMPHeader *pBmpHeader = (BMPHeader*)pbBmpBuffer;
	if (pBmpHeader->wMagic != ByteFlip16(BMP_HEADER_MAGIC))
	{
		// Print an error and return.
		printf("ERROR: BMP image has invalid magic!\n");
		delete[] pbBmpBuffer;
		return false;
	}

	// Check the width and height are within range.
	if (pBmpHeader->sInfo.dwWidth > MR_MAX_WIDTH || pBmpHeader->sInfo.dwHeight > MR_MAX_HEIGHT)
	{
		// Print a warning and try to continue.
		printf("WARNING: bmp image has invalid resolution, should be 320x94 or smaller!, continuing anyway...\n");
	}

	// Check to make sure the bmp image is 32bbp.
	if (pBmpHeader->sInfo.wBitsPerPixel != 32)
	{
		printf("ERROR: bmp image should be 32bbp!\n");
		delete[] pbBmpBuffer;
		return false;
	}

	// Allocate a temp working buffer for the MR image.
	BYTE *pbMRTempBuffer = new BYTE[pBmpHeader->sInfo.dwWidth * pBmpHeader->sInfo.dwHeight * 4];
	memset(pbMRTempBuffer, 0, pBmpHeader->sInfo.dwWidth * pBmpHeader->sInfo.dwHeight * 4);

	// Create a MR image header.
	MRHeader *pMRHeader = (MRHeader*)pbMRTempBuffer;
	pMRHeader->wMagic = ByteFlip16(MR_IMAGE_MAGIC);
	pMRHeader->dwWidth = pBmpHeader->sInfo.dwWidth;
	pMRHeader->dwHeight = pBmpHeader->sInfo.dwHeight;

	// Create the color palette.
	int colors = 0;
	PaletteColor *pColorPalette = (PaletteColor*)&pbMRTempBuffer[sizeof(MRHeader)];

	// Create a pixel buffer for the image data.
	BYTE *pbMRPixelData = (BYTE*)&pbMRTempBuffer[sizeof(MRHeader) + (sizeof(PaletteColor) * 128)];
	DWORD *pdwBmpPixelData = (DWORD*)&pbBmpBuffer[pBmpHeader->dwDataOffset];

	// Loop through the pixel buffer and process each one.
	DWORD length = 0;
	for (int pos = 0; pos < pBmpHeader->sInfo.dwImageSize; )
	{
		// Determine the size of the pixel run.
		int run = 1;
		while ((pdwBmpPixelData[pos] == pdwBmpPixelData[pos + run]) && (run < 0x17f) &&
			(pos + run <= pBmpHeader->sInfo.dwImageSize))
		{
			// Pixel n is the same as the current pixel, so increase the run length by 1.
			run++;
		}

		// Check if this color is in the color palette and if not add it.
		int colorIndex = -1;
		for (int i = 0; i < colors; i++)
		{
			// Check if this color matches the current pixel.
			if (pdwBmpPixelData[pos] == pColorPalette[i].Color)
			{
				// Found the color, break the loop.
				colorIndex = i;
				break;
			}
		}

		// Check if we found the color in the color palette.
		if (colorIndex == -1)
		{
			// We did not find the color in the color palette, see if there is room to add it.
			if (colors < 128)
			{
				// Add the color to the palette.
				pColorPalette[colors].Color = pdwBmpPixelData[pos];
				colorIndex = colors++;
			}
			else
			{
				// The color palette is full, print a warning and continue.
				colorIndex = 0;
				printf("WARNING: bmp image should have 128 colors or less! continuing anyway...\n");
			}
		}

		// Check the size of the pixel run and create the block accordingly.
		if (run > 0xFF)
		{
			pbMRPixelData[length++] = 0x82;
			pbMRPixelData[length++] = 0x80 | (run - 0x100);
			pbMRPixelData[length++] = (BYTE)colorIndex;
		}
		else if (run > 0x7F)
		{
			pbMRPixelData[length++] = 0x81;
			pbMRPixelData[length++] = run;
			pbMRPixelData[length++] = (BYTE)colorIndex;
		}
		else if (run > 1)
		{
			pbMRPixelData[length++] = 0x80 | run;
			pbMRPixelData[length++] = (BYTE)colorIndex;
		}
		else
		{
			pbMRPixelData[length++] = (BYTE)colorIndex;
		}

		// Increase the position by the run length.
		pos += run;
	}

	// Check if the length of the MR image will fit in the IP.BIN file.
	if (sizeof(MRHeader) + (sizeof(PaletteColor) * colors) + length > MR_MAX_SIZE)
	{
		// Delete our bmp buffer and temp mr buffer.
		delete[] pbBmpBuffer;
		delete[] pbMRTempBuffer;

		// Print error and return false.
		printf("ERROR: MR image is too large and will corrupt IP.BIN bootstrap!\n");
		return false;
	}

	// Finish creating the MR image header.
	pMRHeader->dwSize = sizeof(MRHeader) + (sizeof(PaletteColor) * colors) + length;
	pMRHeader->dwDataOffset = sizeof(MRHeader) + (colors * sizeof(PaletteColor));
	pMRHeader->dwColors = colors;

	// Move the pixel data to directly after the color palette.
	memmove(&pbMRTempBuffer[pMRHeader->dwDataOffset], pbMRPixelData, length);

	// Check to make sure the output buffer can hold the MR image buffer.
	if (*pdwBufferSize < pMRHeader->dwSize)
	{
		// Delete our bmp buffer and temp mr buffer.
		delete[] pbBmpBuffer;
		delete[] pbMRTempBuffer;

		// Print an error and return false.
		printf("ERROR: MR image is too large for buffer!\n");
		return false;
	}

	// Copy the MR image buffer to our new buffer.
	memcpy(ppbBuffer, pbMRTempBuffer, pMRHeader->dwSize);
	*pdwBufferSize = pMRHeader->dwSize;

	// Delete our bmp buffer and temp mr buffer.
	delete[] pbBmpBuffer;
	delete[] pbMRTempBuffer;

	// Done, return true.
	return true;
}
Example #3
0
static int load(const char *pszImage)
{
#ifdef RT_OS_WINDOWS
    HANDLE hFile = CreateFile(pszImage,
                              GENERIC_READ,
                              FILE_SHARE_READ,
                              NULL /*pSecurityAttributes*/,
                              OPEN_EXISTING,
                              FILE_ATTRIBUTE_NORMAL,
                              NULL /*hTemplateFile*/);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        printf("error: CreateFile('%s',): %d\n", pszImage, GetLastError());
        return 1;
    }

    DWORD cbHigh  = 0;
    DWORD cbLow   = GetFileSize(hFile, &cbHigh);
    size_t cbFile = cbLow != INVALID_FILE_SIZE
                  ? cbHigh == 0
                  ? cbLow
                  : ~(DWORD)0 / 4
                  : 64;

    HANDLE hMap = CreateFileMapping(hFile,
                                    NULL /*pAttributes*/,
                                    PAGE_READONLY | SEC_COMMIT,
                                    0 /*dwMaximumSizeHigh -> file size*/,
                                    0 /*dwMaximumSizeLow  -> file size*/,
                                    NULL /*pName*/);
    if (hMap == INVALID_HANDLE_VALUE)
        printf("error: CreateFile('%s',): %d\n", pszImage, GetLastError());
        CloseHandle(hFile);
    if (hMap == INVALID_HANDLE_VALUE)
        return 1;

    void *pvWhere = MapViewOfFile(hMap,
                                  FILE_MAP_READ,
                                  0 /*dwFileOffsetHigh*/,
                                  0 /*dwFileOffsetLow*/,
                                  0 /*dwNumberOfBytesToMap - file size */);
    if (!pvWhere)
    {
        printf("error: MapViewOfView('%s',): %d\n", pszImage, GetLastError());
        CloseHandle(hMap);
        return 1;
    }

#else
    int fd = open(pszImage, O_RDONLY, 0);
    if (fd < 0)
    {
        printf("error: open('%s',): %d\n", pszImage, errno);
        return 1;
    }

    struct stat st;
    memset(&st, 0, sizeof(st));
    if (fstat(fd, &st))
        st.st_size = 64;
    size_t cbFile = st.st_size < ~(size_t)0
                  ? (size_t)st.st_size
                  : ~(size_t)0 / 4;

    void *pvWhere = mmap(NULL /*addr*/, cbFile, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0 /*offset*/);
    if (pvWhere == MAP_FAILED)
        printf("error: mmap(,%lu,)/'%s': %d\n", (unsigned long)cbFile, pszImage, errno);
    close(fd);
    if (pvWhere == MAP_FAILED)
        return 1;

#endif

    /* Touch the whole image... do a dummy crc to keep the optimizer from begin
       smart with us. */
    unsigned char  *puchFile = (unsigned char *)pvWhere;
    size_t          off      = 0;
    unsigned int    uCrc     = 0;
    while (off < cbFile)
        uCrc += puchFile[off++];
    printf("info: %p/%#lx/%#x - %s\n", pvWhere, (unsigned long)cbFile, (unsigned char)uCrc, pszImage);

    return 0;
}
Example #4
0
BOOL WINAPI LSLog(int nLevel, LPCSTR pszModule, LPCSTR pszMessage)
{
#if defined(LS_COMPAT_LOGGING)
    wchar_t wzLogFile[MAX_PATH] = { 0 };

    int nLogLevel = GetRCIntW(L"LSLogLevel", 2);

    // Should this message be logged?
    if (!pszModule || !pszMessage ||
        (nLevel > nLogLevel) || (nLevel < 1) || (nLevel > 4))
    {
        return FALSE;
    }

    // Has a log file been assigned?
    if (!GetRCStringW(L"LSLogFile", wzLogFile, NULL, MAX_PATH))
    {
        return FALSE;
    }

    // If so, open it
    HANDLE hLogFile = CreateFile(wzLogFile,
        GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    // Did open succeed?
    if (hLogFile == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    // Move to the end of the file
    SetFilePointer(hLogFile, 0, NULL, FILE_END);

    // Get timestamp
    SYSTEMTIME st = { 0 };
    GetLocalTime(&st);

    // Add timestamp and module name to message
    LPCSTR rszLevel[4] = { "Error", "Warning", "Notice", "Debug" };

    CHAR szLine[MAX_LINE_LENGTH] = { 0 };
    size_t cbLine = sizeof(szLine);
    size_t cbRemaining = 0;

    if (SUCCEEDED(StringCbPrintfExA(szLine, cbLine, NULL, &cbRemaining,
        STRSAFE_IGNORE_NULLS, "%02d-%02d-%04d %02d:%02d:%02d - %s - %s: %s\r\n",
        st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond,
        rszLevel[nLevel-1], pszModule, pszMessage)))
    {
        size_t cbToWrite = cbLine - cbRemaining;
        ASSERT(cbToWrite <= MAXDWORD);

        // Write it to the log file
        DWORD dwCount = 0;
        WriteFile(hLogFile, szLine, (DWORD)cbToWrite, &dwCount, NULL);
    }

    // Close the log
    CloseHandle(hLogFile);
#endif // LS_COMPAT_LOGGING

    return TRUE;
}
Example #5
0
int main(void)
{
	int r = 1, wait = 1, prefix_args_len = -1, needs_env_setup = 1,
		is_git_command = 1, full_path = 1, skip_arguments = 0,
		allocate_console = 0, show_console = 0;
	WCHAR exepath[MAX_PATH], exe[MAX_PATH], top_level_path[MAX_PATH];
	LPWSTR cmd = NULL, exep = exe, prefix_args = NULL, basename;
	LPWSTR working_directory = NULL;

	/* Determine MSys2-based Git path. */
	swprintf(msystem_bin, sizeof(msystem_bin),
		L"mingw%d\\bin", (int) sizeof(void *) * 8);
	*top_level_path = L'\0';

	/* get the installation location */
	GetModuleFileName(NULL, exepath, MAX_PATH);
	if (!PathRemoveFileSpec(exepath)) {
		fwprintf(stderr, L"Invalid executable path: %s\n", exepath);
		ExitProcess(1);
	}
	basename = exepath + wcslen(exepath) + 1;
	if (configure_via_resource(basename, exepath, exep,
			&prefix_args, &prefix_args_len,
			&is_git_command, &working_directory,
			&full_path, &skip_arguments, &allocate_console,
			&show_console)) {
		/* do nothing */
	}
	else if (!wcsicmp(basename, L"git-gui.exe")) {
		static WCHAR buffer[BUFSIZE];
		wait = 0;
		allocate_console = 1;
		initialize_top_level_path(top_level_path, exepath, NULL, 1);

		/* set the default exe module */
		wcscpy(exe, top_level_path);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"wish.exe");
		if (_waccess(exe, 0) != -1)
			swprintf(buffer, BUFSIZE,
				L"\"%s\\%.*s\\libexec\\git-core\"",
				exepath, wcslen(msystem_bin) - 4, msystem_bin);
		else {
			wcscpy(exe, top_level_path);
			PathAppend(exe, L"mingw\\bin\\wish.exe");
			swprintf(buffer, BUFSIZE,
				L"\"%s\\mingw\\libexec\\git-core\"",
				top_level_path);
		}
		PathAppend(buffer, L"git-gui");
		prefix_args = buffer;
		prefix_args_len = wcslen(buffer);
	}
	else if (!wcsnicmp(basename, L"git-", 4)) {
		needs_env_setup = 0;

		/* Call a builtin */
		prefix_args = basename + 4;
		prefix_args_len = wcslen(prefix_args);
		if (!wcsicmp(prefix_args + prefix_args_len - 4, L".exe"))
			prefix_args_len -= 4;

		/* set the default exe module */
		wcscpy(exe, exepath);
		PathAppend(exe, L"git.exe");
	}
	else if (!wcsicmp(basename, L"git.exe")) {
		initialize_top_level_path(top_level_path, exepath, NULL, 1);

		/* set the default exe module */
		wcscpy(exe, top_level_path);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"git.exe");
		if (_waccess(exe, 0) == -1) {
			wcscpy(exe, top_level_path);
			PathAppend(exe, L"bin\\git.exe");
		}
	}
	else if (!wcsicmp(basename, L"gitk.exe")) {
		static WCHAR buffer[BUFSIZE];
		allocate_console = 1;
		initialize_top_level_path(top_level_path, exepath, NULL, 1);

		/* set the default exe module */
		wcscpy(exe, top_level_path);
		swprintf(buffer, BUFSIZE, L"\"%s\"", top_level_path);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"wish.exe");
		if (_waccess(exe, 0) != -1)
			PathAppend(buffer, msystem_bin);
		else {
			wcscpy(exe, top_level_path);
			PathAppend(exe, L"mingw\\bin\\wish.exe");
			PathAppend(buffer, L"mingw\\bin");
		}
		PathAppend(buffer, L"gitk");
		prefix_args = buffer;
		prefix_args_len = wcslen(buffer);
	}

	if (needs_env_setup) {
		if (!top_level_path[0])
			initialize_top_level_path(top_level_path, exepath,
					msystem_bin, -4);

		setup_environment(top_level_path, full_path);
	}
	cmd = fixup_commandline(exepath, &exep, &wait,
		prefix_args, prefix_args_len, is_git_command, skip_arguments);

	if (working_directory == (LPWSTR)1) {
		int len = GetEnvironmentVariable(L"HOME", NULL, 0);

		if (len) {
			working_directory = malloc(sizeof(WCHAR) * len);
			GetEnvironmentVariable(L"HOME", working_directory, len);
		}
	}

	{
		STARTUPINFO si;
		PROCESS_INFORMATION pi;
		DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT;
		HANDLE console_handle;
		BOOL br = FALSE;
		ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
		ZeroMemory(&si, sizeof(STARTUPINFO));
		si.cb = sizeof(STARTUPINFO);

		if (allocate_console | show_console)
			creation_flags |= CREATE_NEW_CONSOLE;
		else if ((console_handle = CreateFile(L"CONOUT$", GENERIC_WRITE,
				FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL, NULL)) !=
				INVALID_HANDLE_VALUE)
			CloseHandle(console_handle);
		else {
#define STD_HANDLE(field, id) si.hStd##field = GetStdHandle(STD_##id); if (!si.hStd##field) si.hStd##field = INVALID_HANDLE_VALUE
			STD_HANDLE(Input, INPUT_HANDLE);
			STD_HANDLE(Output, OUTPUT_HANDLE);
			STD_HANDLE(Error, ERROR_HANDLE);
			si.dwFlags = STARTF_USESTDHANDLES;


			creation_flags |= CREATE_NO_WINDOW;
		}
		if (show_console) {
			si.dwFlags |= STARTF_USESHOWWINDOW;
			si.wShowWindow = SW_SHOW;
		}
		br = CreateProcess(/* module: null means use command line */
				exep,
				cmd,  /* modified command line */
				NULL, /* process handle inheritance */
				NULL, /* thread handle inheritance */
					/* handles inheritable? */
				allocate_console ? FALSE : TRUE,
				creation_flags,
				NULL, /* environment: use parent */
				working_directory, /* use parent's */
				&si, &pi);
		if (br) {
			if (wait)
				WaitForSingleObject(pi.hProcess, INFINITE);
			if (!GetExitCodeProcess(pi.hProcess, (DWORD *)&r))
				print_error(L"error reading exit code",
					GetLastError());
			CloseHandle(pi.hProcess);
		}
		else {
			print_error(L"error launching git", GetLastError());
			r = 1;
		}
	}

	free(cmd);

	ExitProcess(r);
}
Example #6
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE TheFile, WaitFile;
    int result = 0;
    char DataBuffer[BUF_SIZE];
    DWORD BytesRead;
    
    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
    
    /* Open the same file that the parent has opened and locked */
    TheFile = CreateFile(FILENAME,     
                         GENERIC_READ|GENERIC_WRITE, 
                         FILE_SHARE_READ|FILE_SHARE_WRITE,
                         NULL,     
                         OPEN_EXISTING,                 
                         FILE_ATTRIBUTE_NORMAL, 
                         NULL);
    
    if (TheFile == INVALID_HANDLE_VALUE) 
    { 
        Trace("ERROR: Could not open file '%s' with CreateFile.",FILENAME); 
        result = 1;
    }
    
    /* Open up the WaitFile that we're using for IPC */
    WaitFile = CreateFile(WAITFILENAME,     
                          GENERIC_READ|GENERIC_WRITE, 
                          FILE_SHARE_READ|FILE_SHARE_WRITE,
                          NULL,                          
                          OPEN_ALWAYS,                 
                          FILE_ATTRIBUTE_NORMAL, 
                          NULL);
    
    if (WaitFile == INVALID_HANDLE_VALUE) 
    { 
        Trace("ERROR: Could not open file '%s' with CreateFile. "
             "GetLastError() returned %d.",WAITFILENAME,GetLastError()); 
        result = 1;
    }
    
    /* Lock the same file that the parent process locked, but the child
       locks bytes 11 through 20
    */

    if(LockFile(TheFile, 11, 0, 10, 0) == 0)
    {
        Trace("ERROR: LockFile failed in the child proccess.  "
              "GetLastError returns %d.",
              GetLastError());
        result = 1;
    }
    
    /* Check to ensure the parent lock is respected */
    if(ReadFile(TheFile, DataBuffer, 10, &BytesRead, NULL) != 0)
    {
        Trace("ERROR: ReadFile returned success when it should "
             "have failed.  Attempted to read the first 10 bytes "
             "of a file which was locked by the parent process.");
        result = 1;
    }

    /* Check to ensure the lock put on by this proccess doesn't restrict
       access
    */

    if(SetFilePointer(TheFile, 11, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
    {
        Trace("ERROR: SetFilePointer was unable to move the file pointer to "
              "the 11th byte in the file, within the child proccess.  "
              "GetLastError() returned %d.",GetLastError());
        result = 1;
    }

    if(ReadFile(TheFile, DataBuffer, 10, &BytesRead, NULL) == 0)
    {
        Trace("ERROR: ReadFile failed when attempting to read a section of "
             "the file which was locked by the current process.  It should "
             "have been able to read this.  GetLastError() returned %d.",
             GetLastError());
        result = 1;
    }

    // Sleep for a bit to give the parent a chance to block before we do.
    Sleep(1000);

    /* Switch back to the parent, so it can check the child's locks */
    SignalAndBusyWait(WaitFile);

    if(UnlockFile(TheFile, 11, 0, 10, 0) == 0)
    {
        Fail("ERROR: Failed to Unlock bytes 11-20 in the file.  "
             "GetLastError returned %d.",GetLastError());
    }
    
    PAL_Terminate();
    return result;
}
Example #7
0
//-------------------------------------------------------------------
// Code for the function MyDecryptFile called by main.
//-------------------------------------------------------------------
// Parameters passed are:
//  pszSource, the name of the input file, an encrypted file.
//  pszDestination, the name of the output, a plaintext file to be 
//   created.
//  pszPassword, either NULL if a password is not to be used or the 
//   string that is the password.
bool MyDecryptFile(
    LPTSTR pszSourceFile, 
    LPTSTR pszDestinationFile, 
    LPTSTR pszPassword)
{ 
    //---------------------------------------------------------------
    // Declare and initialize local variables.
    bool fReturn = false;
    HANDLE hSourceFile = INVALID_HANDLE_VALUE;
    HANDLE hDestinationFile = INVALID_HANDLE_VALUE; 
    HCRYPTKEY hKey = NULL; 
    HCRYPTHASH hHash = NULL; 

    HCRYPTPROV hCryptProv = NULL; 

    DWORD dwCount;
    PBYTE pbBuffer = NULL; 
    DWORD dwBlockLen; 
    DWORD dwBufferLen; 

    //---------------------------------------------------------------
    // Open the source file. 
    hSourceFile = CreateFile(
        pszSourceFile, 
        FILE_READ_DATA,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if(INVALID_HANDLE_VALUE != hSourceFile)
    {
        _tprintf(
            TEXT("The source encrypted file, %s, is open. \n"), 
            pszSourceFile);
    }
    else
    { 
        MyHandleError(
            TEXT("Error opening source plaintext file!\n"), 
            GetLastError());
        goto Exit_MyDecryptFile;
    } 

    //---------------------------------------------------------------
    // Open the destination file. 
    hDestinationFile = CreateFile(
        pszDestinationFile, 
        FILE_WRITE_DATA,
        FILE_SHARE_READ,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if(INVALID_HANDLE_VALUE != hDestinationFile)
    {
         _tprintf(
             TEXT("The destination file, %s, is open. \n"), 
             pszDestinationFile);
    }
    else
    {
        MyHandleError(
            TEXT("Error opening destination file!\n"), 
            GetLastError()); 
        goto Exit_MyDecryptFile;
    }

    //---------------------------------------------------------------
    // Get the handle to the default provider. 
    if(CryptAcquireContext(
        &hCryptProv, 
        NULL, 
        MS_ENH_RSA_AES_PROV, 
        PROV_RSA_AES, 
        0))
    {
        _tprintf(
            TEXT("A cryptographic provider has been acquired. \n"));
    }
    else
    {
        MyHandleError(
            TEXT("Error during CryptAcquireContext!\n"), 
            GetLastError());
        goto Exit_MyDecryptFile;
    }

    //---------------------------------------------------------------
    // Create the session key.
    if(!pszPassword || !pszPassword[0]) 
    { 
        //-----------------------------------------------------------
        // Decrypt the file with the saved session key. 

        DWORD dwKeyBlobLen;
        PBYTE pbKeyBlob = NULL;

        // Read the key BLOB length from the source file. 
        if(!ReadFile(
            hSourceFile, 
            &dwKeyBlobLen, 
            sizeof(DWORD), 
            &dwCount, 
            NULL))
        {
            MyHandleError(
                TEXT("Error reading key BLOB length!\n"), 
                GetLastError());
            goto Exit_MyDecryptFile;
        }

        // Allocate a buffer for the key BLOB.
        if(!(pbKeyBlob = (PBYTE)malloc(dwKeyBlobLen)))
        {
            MyHandleError(
                TEXT("Memory allocation error.\n"), 
                E_OUTOFMEMORY); 
        }

        //-----------------------------------------------------------
        // Read the key BLOB from the source file. 
        if(!ReadFile(
            hSourceFile, 
            pbKeyBlob, 
            dwKeyBlobLen, 
            &dwCount, 
            NULL))
        {
            MyHandleError(
                TEXT("Error reading key BLOB length!\n"), 
                GetLastError());
            goto Exit_MyDecryptFile;
        }

        //-----------------------------------------------------------
        // Import the key BLOB into the CSP. 
        if(!CryptImportKey(
              hCryptProv, 
              pbKeyBlob, 
              dwKeyBlobLen, 
              0, 
              0, 
              &hKey))
        {
            MyHandleError(
                TEXT("Error during CryptImportKey!/n"), 
                GetLastError()); 
            goto Exit_MyDecryptFile;
        }

        if(pbKeyBlob)
        {
            free(pbKeyBlob);
        }
    }
    else
    {
        //-----------------------------------------------------------
        // Decrypt the file with a session key derived from a 
        // password. 

        //-----------------------------------------------------------
        // Create a hash object. 
        if(!CryptCreateHash(
               hCryptProv, 
               CALG_MD5, 
               0, 
               0, 
               &hHash))
        {
            MyHandleError(
                TEXT("Error during CryptCreateHash!\n"), 
                GetLastError());
            goto Exit_MyDecryptFile;
        }
        
        //-----------------------------------------------------------
        // Hash in the password data. 
        if(!CryptHashData(
               hHash, 
               (BYTE *)pszPassword, 
               lstrlen(pszPassword), 
               0)) 
        {
            MyHandleError(
                TEXT("Error during CryptHashData!\n"), 
                GetLastError()); 
            goto Exit_MyDecryptFile;
        }
    
        //-----------------------------------------------------------
        // Derive a session key from the hash object. 
        if(!CryptDeriveKey(
              hCryptProv, 
              ENCRYPT_ALGORITHM, 
              hHash, 
              KEYLENGTH, 
              &hKey))
        { 
            MyHandleError(
                TEXT("Error during CryptDeriveKey!\n"), 
                GetLastError()) ; 
            goto Exit_MyDecryptFile;
        }
    }

    //---------------------------------------------------------------
    // The decryption key is now available, either having been 
    // imported from a BLOB read in from the source file or having 
    // been created by using the password. This point in the program 
    // is not reached if the decryption key is not available.
     
    //---------------------------------------------------------------
    // Determine the number of bytes to decrypt at a time. 
    // This must be a multiple of ENCRYPT_BLOCK_SIZE. 

    dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; 
    dwBufferLen = dwBlockLen; 

    //---------------------------------------------------------------
    // Allocate memory for the file read buffer. 
    if(!(pbBuffer = (PBYTE)malloc(dwBufferLen)))
    {
       MyHandleError(TEXT("Out of memory!\n"), E_OUTOFMEMORY); 
       goto Exit_MyDecryptFile;
    }
    
    //---------------------------------------------------------------
    // Decrypt the source file, and write to the destination file. 
    bool fEOF = false;
    do
    {
        //-----------------------------------------------------------
        // Read up to dwBlockLen bytes from the source file. 
        if(!ReadFile(
            hSourceFile, 
            pbBuffer, 
            dwBlockLen, 
            &dwCount, 
            NULL))
        {
            MyHandleError(
                TEXT("Error reading from source file!\n"), 
                GetLastError());
            goto Exit_MyDecryptFile;
        }

        if(dwCount <= dwBlockLen)
        {
            fEOF = TRUE;
        }

        //-----------------------------------------------------------
        // Decrypt the block of data. 
        if(!CryptDecrypt(
              hKey, 
              0, 
              fEOF, 
              0, 
              pbBuffer, 
              &dwCount))
        {
            MyHandleError(
                TEXT("Error during CryptDecrypt!\n"), 
                GetLastError()); 
            goto Exit_MyDecryptFile;
        }

        //-----------------------------------------------------------
        // Write the decrypted data to the destination file. 
        if(!WriteFile(
            hDestinationFile, 
            pbBuffer, 
            dwCount,
            &dwCount,
            NULL))
        { 
            MyHandleError(
                TEXT("Error writing ciphertext.\n"), 
                GetLastError());
            goto Exit_MyDecryptFile;
        }

        //-----------------------------------------------------------
        // End the do loop when the last block of the source file 
        // has been read, encrypted, and written to the destination 
        // file.
    }while(!fEOF);

    fReturn = true;

Exit_MyDecryptFile:

    //---------------------------------------------------------------
    // Free the file read buffer.
    if(pbBuffer)
    {
        free(pbBuffer);
    }

    //---------------------------------------------------------------
    // Close files.
    if(hSourceFile)
    {
        CloseHandle(hSourceFile);
    }

    if(hDestinationFile)
    {
        CloseHandle(hDestinationFile);
    }

    //-----------------------------------------------------------
    // Release the hash object. 
    if(hHash) 
    {
        if(!(CryptDestroyHash(hHash)))
        {
            MyHandleError(
                TEXT("Error during CryptDestroyHash.\n"), 
                GetLastError()); 
        }

        hHash = NULL;
    }

    //---------------------------------------------------------------
    // Release the session key. 
    if(hKey)
    {
        if(!(CryptDestroyKey(hKey)))
        {
            MyHandleError(
                TEXT("Error during CryptDestroyKey!\n"), 
                GetLastError());
        }
    } 

    //---------------------------------------------------------------
    // Release the provider handle. 
    if(hCryptProv)
    {
        if(!(CryptReleaseContext(hCryptProv, 0)))
        {
            MyHandleError(
                TEXT("Error during CryptReleaseContext!\n"), 
                GetLastError());
        }
    } 

    return fReturn;
}
Example #8
0
void
LoggerImpl::StartLogger(const NMEA_INFO &gps_info,
                    const SETTINGS_COMPUTER &settings,
                    const TCHAR *astrAssetNumber)
{
  HANDLE hFile;
  int i;
  TCHAR path[MAX_PATH];
  TCHAR cAsset[3];
  for (i=0; i < 3; i++) { // chars must be legal in file names
    cAsset[i] = IsAlphaNum(strAssetNumber[i]) ? strAssetNumber[i] : _T('A');
  }

// VENTA3 use logs subdirectory when not in main memory (true for FIVV and PNA)
#if defined(GNAV) || defined(FIVV) || defined(PNA)
  LocalPath(path,TEXT("logs"));
#else
  LocalPath(path);
#endif

  if (task.isTaskModified()) {
    task.SaveDefaultTask();
  }

#ifdef WINDOWSPC
  _stprintf(szLoggerFileName, TEXT("/tmp/tmp.IGC"));
#else
  _stprintf(szLoggerFileName, TEXT("\\tmp.IGC"));
#endif
  DeleteFile(szLoggerFileName);

  LoggerGInit();

  for(i=1;i<99;i++)
    {
      // 2003-12-31-XXX-987-01.IGC
      // long filename form of IGC file.
      // XXX represents manufacturer code

      if (!settings.LoggerShortName) {
        // Long file name
        _stprintf(szFLoggerFileName,
                 TEXT("%s\\%04d-%02d-%02d-XCS-%c%c%c-%02d.IGC"),
                 path,
                 gps_info.Year,
                 gps_info.Month,
                 gps_info.Day,
                 cAsset[0],
                 cAsset[1],
                 cAsset[2],
                 i);

        _stprintf(szFLoggerFileNameRoot,
                 TEXT("%s\\%04d-%02d-%02d-XCS-%c%c%c-%02d.IGC"),
                 TEXT(""), // this creates it in root if MoveFile() fails
                 gps_info.Year,
                 gps_info.Month,
                 gps_info.Day,
                 cAsset[0],
                 cAsset[1],
                 cAsset[2],
                 i);
      } else {
        // Short file name
        TCHAR cyear, cmonth, cday, cflight;
        cyear = NumToIGCChar((int)gps_info.Year % 10);
        cmonth = NumToIGCChar(gps_info.Month);
        cday = NumToIGCChar(gps_info.Day);
        cflight = NumToIGCChar(i);
        _stprintf(szFLoggerFileName,
                 TEXT("%s\\%c%c%cX%c%c%c%c.IGC"),
                 path,
                 cyear,
                 cmonth,
                 cday,
                 cAsset[0],
                 cAsset[1],
                 cAsset[2],
                 cflight);

        _stprintf(szFLoggerFileNameRoot,
                 TEXT("%s\\%c%c%cX%c%c%c%c.IGC"),
                 TEXT(""), // this creates it in root if MoveFile() fails
                 cyear,
                 cmonth,
                 cday,
                 cAsset[0],
                 cAsset[1],
                 cAsset[2],
                 cflight);
      } // end if

      hFile = CreateFile(szFLoggerFileName, GENERIC_WRITE,
			 FILE_SHARE_WRITE, NULL, CREATE_NEW,
			 FILE_ATTRIBUTE_NORMAL, 0);
      if(hFile!=INVALID_HANDLE_VALUE )
	{
          // file already exists
      CloseHandle(hFile);
      DeleteFile(szFLoggerFileName);
      break;
	}
  } // end while

  TCHAR szMessage[MAX_PATH] = TEXT("\0");

  _tcsncpy(szMessage,TEXT("Logger Started: "),MAX_PATH);
  _tcsncat(szMessage,szFLoggerFileName,MAX_PATH);
  _tcsncat(szMessage,TEXT("\r\n"),MAX_PATH);
  StartupStore(szMessage);

  return;
}
Example #9
0
int
main(int argc, char **argv)
{
    char **av = argv;
    struct sockaddr_in host;
    register afs_int32 code;
    extern struct hostent *gethostbyname();
    struct hostent *hp;
    char *hostname;
    char hnamebuf[200];
    struct timeval tv;
    int noAuth = 1;		/* Default is authenticated connections */

    argc--, av++;
    if (argc < 1) {
	printf("usage: pxclient <serverHost>\n");
	exit(1);
    }
    memset((char *)&host, 0, sizeof(struct sockaddr_in));
    host.sin_family = AF_INET;
    host.sin_addr.s_addr = inet_addr(av[0]);
#ifdef STRUCT_SOCKADDR_HAS_SA_LEN
    host.sin_len = sizeof(struct sockaddr_in);
#endif
    if (host.sin_addr.s_addr != -1) {
	strcpy(hnamebuf, av[0]);
	hostname = hnamebuf;
    } else {
	hp = gethostbyname(av[0]);
	if (hp) {
	    host.sin_family = hp->h_addrtype;
	    memcpy((caddr_t) & host.sin_addr, hp->h_addr, hp->h_length);
	    hostname = hp->h_name;
	} else {
	    printf("unknown server host %s\n", av[0]);
	    exit(1);
	}
    }
    if ((code = pxclient_Initialize(noAuth, host.sin_addr.s_addr)) != 0) {
	printf("Couldn't initialize fs library (code=%d).\n", code);
	exit(1);
    }

    code = ubik_Call(RXAFS_GetTime, cstruct, 0, &tv.tv_sec, &tv.tv_usec);
    if (!code)
	printf("AFS_GetTime on %s sec=%ld, usec=%ld\n", av[0], tv.tv_sec,
	       tv.tv_usec);
    else
	printf("return code is %d\n", code);

#ifdef notdef
    while (1) {
	char line[500];
	int nargs;

	printf("fs> ");
	if (fgets(line, 499, stdin) != NULL) {
	    char *oper;
	    register char **argp = args;
	    GetArgs(line, argp, &nargs);
	    oper = &argp[0][0];
	    ++argp, --nargs;
	    if (!strcmp(oper, "probe")) {
		code =
		    ubik_Call(RXAFS_GetTime, cstruct, 0, &tv.tv_sec,
			      &tv.tv_usec);
		printf("return code is %d\n", code);
		if (!code)
		    printf("sec=%d\n", tv.tv_sec);
	    } else if (!strcmp(oper, "fsstats")) {
		struct afsStatistics stats;

		code = ubik_AFS_GetStatistics(cstruct, 0, &stats);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fd")) {
		code = FetchData(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fs")) {
		code = FetchStatus(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fa")) {
		code = FetchACL(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "sd")) {
		code = StoreData(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "ss")) {
		code = StoreStatus(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "sa")) {
		code = StoreACL(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "cf")) {
		code = CreateFile(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rf")) {
		code = RemoveFile(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rn")) {
		code = Rename(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "sl")) {
		code = Symlink(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "hl")) {
		code = HardLink(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "md")) {
		code = MakeDir(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rd")) {
		code = RemoveDir(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rdd")) {
		code = Readdir(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "mm")) {
		code = MakeMountPoint(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rt")) {
		code = ReleaseTokens(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "bs")) {
		code = BulkStatus(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "lk")) {
		code = Lookup(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "gt")) {
		code = GetToken(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "ka")) {
		code = KeepAlive(argp);
		printf("return code is %d\n", code);
	    } else if ((!strcmp(oper, "q")) || !strcmp(oper, "quit"))
		exit(0);
	    else {
		printf("Unknown oper! Available operations: \n\n");
		printf("fd <vnode> <unique> <pos> <len>\n");
		printf("fs <vnode> <unique>\n");
		printf("fa <vnode> <unique>\n");
		printf
		    ("sd <vnode> <unique> <pos> <len> <flen> [<mode>|-1] [<owner>|-1] [<length>|-1] <string>\n");
		printf
		    ("ss <vnode> <unique> [<mode>|-1] [<owner>|-1] [<length>|-1]\n");
		printf("sa <vnode> <unique> <string>\n");
		printf("rf <vnode> <unique> <name>\n");
		printf
		    ("cf <vnode> <unique> <name> [<mode>|-1] [<owner>|-1] [<length>|-1]\n");
		printf
		    ("rn <ovnode> <ounique> <oname> <nvnode> <nunique> <nname>\n");
		printf
		    ("sl <vnode> <unique> <name> <contents> [<mode>|-1] [<owner>|-1] [<length>|-1]\n");
		printf("hl <dvnode> <dunique> <name> <evnode> <eunique>\n");
		printf
		    ("md <vnode> <unique> <name> [<mode>|-1] [<owner>|-1] [<length>|-1]\n");
		printf("rd <vnode> <unique> <name>\n");
		printf("rdd <vnode> <unique> <pos> <len>\n");
		printf("lk <vnode> <unique> <name>\n");
		printf("gt <vnode> <unique> <tokenID>\n");
		printf("ka <vol.l> <vnode> <unique> <isExec> <kaTime>\n");
	    }
	}
    }
#endif
    return 0;
}
HRESULT C[!output Safe_root]::FinalConstruct()
{
   HRESULT hr = S_OK;

   ATLTRACE2("%x: FinalConstruct\n", GetCurrentThreadId());

   m_msgDownloadBatch = RegisterWindowMessage( L"DownloadBatch" );

   if(0 == m_msgDownloadBatch)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgBuy = RegisterWindowMessage( L"Buy" );

   if(0 == m_msgBuy)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgRefreshLicense = RegisterWindowMessage( L"RefreshLicense" );

   if(0 == m_msgRefreshLicense)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgLogin = RegisterWindowMessage( L"Login" );

   if(0 == m_msgLogin)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgAuthenticate = RegisterWindowMessage( L"Authenticate" );

   if(0 == m_msgAuthenticate)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgLogout = RegisterWindowMessage( L"Logout" );

   if(0 == m_msgLogout)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgVerifyPermission = RegisterWindowMessage( L"VerifyPermission" );

   if(0 == m_msgVerifyPermission)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgSendMessage = RegisterWindowMessage( L"SendMessage" );

   if(0 == m_msgSendMessage)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgGetListContents = RegisterWindowMessage( L"GetListContents" );

   if(0 == m_msgGetListContents)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgExitMessageLoop = RegisterWindowMessage( L"ExitMessageLoop" );

   if(0 == m_msgExitMessageLoop)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   hr = this->CreateCredentialsFilePath();

   if(FAILED(hr))
   {
      ATLTRACE2("FinalConstruct: CreateCredentialsFilePath failed. %x\n", hr);
      goto cleanup;
   }

   // Determine whether we have cached credentials.

   HANDLE hInfoFile = INVALID_HANDLE_VALUE;

   hInfoFile = CreateFile(
      g.credentialsFile,
      0,
      0,
      NULL,
      OPEN_EXISTING,
      FILE_ATTRIBUTE_NORMAL,
      NULL);

   if(INVALID_HANDLE_VALUE != hInfoFile)
   {
      // The file exists.
      // We have cached credentials.
      g.haveCachedCredentials = 1;
   }
    
   CloseHandle(hInfoFile);

cleanup:
   return hr;
}
CPushPinBitmapSet::CPushPinBitmapSet(HRESULT *phr, CSource *pFilter)
      : CSourceStream(NAME("Push Source BitmapSet"), phr, pFilter, L"Out"),
        m_FramesWritten(0),
        m_bZeroMemory(0),
        m_iFrameNumber(0),
        m_rtFrameLength(FPS_2), // Display 2 bitmap frames per second
        m_iCurrentBitmap(0),
        m_bFilesLoaded(FALSE)
{
    int nFilesLoaded=0;

    // Initialize member data arrays
    ZeroMemory(&m_cbBitmapInfo, NUM_FILES * sizeof(DWORD));
    ZeroMemory(&m_pBmi,   NUM_FILES * sizeof(BITMAPINFO *));
    ZeroMemory(&m_hFile,  NUM_FILES * sizeof(HANDLE));
    ZeroMemory(&m_pFile,  NUM_FILES * sizeof(BYTE *));
    ZeroMemory(&m_pImage, NUM_FILES * sizeof(BYTE *));

    // The main point of this sample is to demonstrate how to take a DIB
    // in host memory and insert it into a video stream. 
    // We read a set of bitmaps from files and copy one bitmap
    // into every frame that we send downstream.

    // In the filter graph, we connect this filter to the AVI Mux, which creates 
    // the AVI file with the video frames we pass to it. In this case, 
    // the end result is a rotating set of images rendered as a video stream.    

    // Read the current directory and SDK media directory into local strings
    TCHAR szCurrentDir[MAX_PATH], szMediaDir[MAX_PATH];
    GetCurrentDirectory(MAX_PATH-1, szCurrentDir);
    lstrcpyn(szMediaDir, DXUtil_GetDXSDKMediaPath(), MAX_PATH-1);

    for (int i=0; i < NUM_FILES; i++)
    {
        TCHAR szFileCurrent[MAX_PATH], szFileMedia[MAX_PATH];

        // Assume that the bitmap in the application's directory
        wsprintf(szFileCurrent, TEXT("%s\\BitmapSet%d.bmp\0"), szCurrentDir, i);

        m_hFile[i] = CreateFile(szFileCurrent, GENERIC_READ, 0, NULL, OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL, NULL);

        if (m_hFile[i] == INVALID_HANDLE_VALUE)
        {
            // File was not in the application's current directory,
            // so look in the DirectX SDK media path instead.  The path contained
            // in szMediaDir will already have a trailing backslash '\'.
            wsprintf(szFileMedia, TEXT("%sBitmapSet%d.bmp\0"), szMediaDir, i);

            m_hFile[i] = CreateFile(szFileMedia, GENERIC_READ, 0, NULL, OPEN_EXISTING, 
                                    FILE_ATTRIBUTE_NORMAL, NULL);

            if (m_hFile[i] == INVALID_HANDLE_VALUE)
            {
                TCHAR szMsg[2*MAX_PATH + 100];

                wsprintf(szMsg, TEXT("Could not open bitmap source file (#%d of %d) in the application directory:\r\n\r\n\t[%s]\n\n")
                         TEXT("or in the DirectX SDK Media folder:\r\n\r\n\t[%s]\n\n")
                         TEXT("Please copy this file either to the application's folder\r\n")
                         TEXT("or to the DirectX SDK Media folder, then recreate this filter.\r\n")
                         TEXT("Otherwise, you will not be able to render the output pin.\0"),
                         i+1, NUM_FILES, szFileCurrent, szFileMedia);

                OutputDebugString(szMsg);
                MessageBox(NULL, szMsg, TEXT("PushSource filter error"), MB_ICONERROR | MB_OK);
                *phr = HRESULT_FROM_WIN32(GetLastError());
                return;
            }
        }

        DWORD dwFileSize = GetFileSize(m_hFile[i], NULL);
        if (dwFileSize == INVALID_FILE_SIZE)
        {
            DbgLog((LOG_TRACE, 1, TEXT("Invalid file size")));
            *phr = HRESULT_FROM_WIN32(GetLastError());
            return;
        }

        m_pFile[i] = new BYTE[dwFileSize];
        if(!m_pFile[i])
        {
            OutputDebugString(TEXT("Could not allocate m_pImage\n"));
            *phr = E_OUTOFMEMORY;
            return;
        }

        DWORD nBytesRead = 0;
        if(!ReadFile(m_hFile[i], m_pFile[i], dwFileSize, &nBytesRead, NULL))
        {
            *phr = HRESULT_FROM_WIN32(GetLastError());
            OutputDebugString(TEXT("ReadFile failed\n"));
            return;
        }

        // WARNING - This code does not verify the file is a valid bitmap file.
        // In your own filter, you would check this or else generate the bitmaps 
        // yourself in memory.

        int cbFileHeader = sizeof(BITMAPFILEHEADER);

        // Store the size of the BITMAPINFO 
        BITMAPFILEHEADER *pBm = (BITMAPFILEHEADER*)m_pFile[i];
        m_cbBitmapInfo[i] = pBm->bfOffBits - cbFileHeader;

        // Store a pointer to the BITMAPINFO
        m_pBmi[i] = (BITMAPINFO*)(m_pFile[i] + cbFileHeader);

        // Store a pointer to the starting address of the pixel bits
        m_pImage[i] = m_pFile[i] + cbFileHeader + m_cbBitmapInfo[i];

        // Close and invalidate the file handle, since we have copied its bitmap data
        CloseHandle(m_hFile[i]);
        m_hFile[i] = INVALID_HANDLE_VALUE;

        // Count this is a successful file load.  If not all files load
        // properly, then the filter will not operate correctly.
        nFilesLoaded++;
    }

    // Make sure that ALL files were properly loaded
    if (nFilesLoaded != NUM_FILES)
        *phr = E_FAIL;
    else
        m_bFilesLoaded = TRUE;
}
Example #12
0
/* handle_file: Open, get the fileno, seek to the end and update mtime */
int handle_file(int i, int do_fseek, int do_log)
{
    int fd;
    struct stat stat_fd;
    
    /* We must be able to open the file, fseek and get the
     * time of change from it.
     */
    #ifndef WIN32
    logff[i].fp = fopen(logff[i].file, "r");
    if(!logff[i].fp)
    {
        if(do_log == 1)
        {
            merror(FOPEN_ERROR, ARGV0, logff[i].file);
        }
        return(-1);
    }
    /* Getting inode number for fp */
    fd = fileno(logff[i].fp);
    if(fstat(fd, &stat_fd) == -1)
    {
        merror(FILE_ERROR,ARGV0,logff[i].file);
        fclose(logff[i].fp);
        logff[i].fp = NULL;
        return(-1);
    }
    
    logff[i].fd = stat_fd.st_ino;
    logff[i].size =  stat_fd.st_size;
    

    #else
    BY_HANDLE_FILE_INFORMATION lpFileInformation;

    logff[i].fp = NULL;
    logff[i].h = CreateFile(logff[i].file, GENERIC_READ,
                            FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,
                            NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if(logff[i].h == INVALID_HANDLE_VALUE)
    {
        if(do_log == 1)
        {
            merror(FOPEN_ERROR, ARGV0, logff[i].file);
        }
        return(-1);
    }
    fd = _open_osfhandle((long)logff[i].h, 0);
    if(fd == -1)
    {
        merror(FOPEN_ERROR, ARGV0, logff[i].file);
        CloseHandle(logff[i].h);
        return(-1);
    }
    logff[i].fp = _fdopen(fd, "r");
    if(logff[i].fp == NULL)
    {
        merror(FOPEN_ERROR, ARGV0, logff[i].file);
        CloseHandle(logff[i].h);
        return(-1);
    }


    /* On windows, we also need the real inode, which is the combination
     * of the index low + index high numbers.
     */
    if(GetFileInformationByHandle(logff[i].h, &lpFileInformation) == 0)
    {
        merror("%s: Unable to get file information by handle.", ARGV0);
        fclose(logff[i].fp);
        CloseHandle(logff[i].h);
        logff[i].fp = NULL;
        return(-1);
    }

    logff[i].fd = (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh);
    logff[i].size = (lpFileInformation.nFileSizeHigh + lpFileInformation.nFileSizeLow);

    #endif


    /* Only seek the end of the file if set to. */
    if(do_fseek == 1 && S_ISREG(stat_fd.st_mode))
    {
        /* Windows and fseek causes some weird issues.. */
        #ifndef WIN32
        if(fseek(logff[i].fp, 0, SEEK_END) < 0)
        {
            merror(FSEEK_ERROR, ARGV0,logff[i].file);
            fclose(logff[i].fp);
            logff[i].fp = NULL;
            return(-1);
        }
        #endif
    }
    

    /* Setting ignore to zero */
    logff[i].ign = 0;
    return(0);
}
Example #13
0
/** void LogCollectorStart() v0.4
 * Handle file management.
 */
void LogCollectorStart()
{
    int i = 0, r = 0;
    int max_file = 0;
    int f_check = 0;
    int curr_time = 0;
    char keepalive[1024];


    
    /* To check for inode changes */
    struct stat tmp_stat;
    
                
    #ifndef WIN32
    
    int int_error = 0;
    struct timeval fp_timeout;
    
    #else
    
    /* Checking if we are on vista. */
    checkVista();


    /* Reading vista descriptions. */
    if(isVista)
    {
        win_read_vista_sec();
    }
    
    #endif

    debug1("%s: DEBUG: Entering LogCollectorStart().", ARGV0);
    
    
    /* Initializing each file and structure */
    for(i = 0;;i++)
    {
        if(logff[i].file == NULL)
            break;


        /* Removing duplicate entries. */
        for(r = 0; r < i; r++)
        {
            if(logff[r].file && strcmp(logff[i].file, logff[r].file) == 0)
            {
                merror("%s: WARN: Duplicated log file given: '%s'.", 
                       ARGV0, logff[i].file);
                logff[i].file = NULL;
                logff[i].command = NULL;
                logff[i].fp = NULL;

                break;
            }
        }

        if(logff[i].file == NULL)
        {
            /* do nothing, duplicated entry. */
        }
       
        else if(strcmp(logff[i].logformat,"eventlog") == 0)
        {
            #ifdef WIN32
            
            verbose(READING_EVTLOG, ARGV0, logff[i].file);
            win_startel(logff[i].file);
            
            #endif
            logff[i].file = NULL;
            logff[i].command = NULL;
            logff[i].fp = NULL;
        }

        else if(strcmp(logff[i].logformat, "command") == 0)
        {
            logff[i].file = NULL;
            logff[i].fp = NULL;
            logff[i].size = 0;
            if(logff[i].ign == 360)
            {
                logff[i].ign = 3600;
            }

            if(logff[i].command)
            {
                logff[i].read = (void *)read_command;

                verbose("%s: INFO: Monitoring output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command);

                if(!logff[i].alias)
                {
                    os_strdup(logff[i].command, logff[i].alias);
                }
            }
            else
            {
                merror("%s: ERROR: Missing command argument. Ignoring it.", 
                       ARGV0);
            }
        }
        else if(strcmp(logff[i].logformat, "full_command") == 0)
        {
            logff[i].file = NULL;
            logff[i].fp = NULL;
            logff[i].size = 0;
            if(logff[i].command)
            {
                logff[i].read = (void *)read_fullcommand;

                verbose("%s: INFO: Monitoring full output of command(%d): %s", ARGV0, logff[i].ign, logff[i].command);

                if(!logff[i].alias)
                    os_strdup(logff[i].command, logff[i].alias);
            }
            else
            {
                merror("%s: ERROR: Missing command argument. Ignoring it.",
                       ARGV0); 
            }
        }
        
        else
        {
            logff[i].command = NULL;


            /* Initializing the files */    
            if(logff[i].ffile)
            {
                /* Day must be zero for all files to be initialized */
                _cday = 0;
                if(update_fname(i))
                {
                    handle_file(i, 1, 1);
                }
                else
                {
                    ErrorExit(PARSE_ERROR, ARGV0, logff[i].ffile);
                }
                    
            }
            else
            {
                handle_file(i, 1, 1);
            }
            
            verbose(READING_FILE, ARGV0, logff[i].file);
            
            /* Getting the log type */
            if(strcmp("snort-full", logff[i].logformat) == 0)
            {
                logff[i].read = (void *)read_snortfull;
            }
            if(strcmp("ossecalert", logff[i].logformat) == 0)
            {
                logff[i].read = (void *)read_ossecalert;
            }
            else if(strcmp("nmapg", logff[i].logformat) == 0)
            {
                logff[i].read = (void *)read_nmapg;
            }
            else if(strcmp("mysql_log", logff[i].logformat) == 0)
            {
                logff[i].read = (void *)read_mysql_log;
            }
            else if(strcmp("mssql_log", logff[i].logformat) == 0)
            {
                logff[i].read = (void *)read_mssql_log;
            }
            else if(strcmp("postgresql_log", logff[i].logformat) == 0)
            {
                logff[i].read = (void *)read_postgresql_log;
            }
            else if(strcmp("djb-multilog", logff[i].logformat) == 0)
            {
                if(!init_djbmultilog(i))
                {
                    merror(INV_MULTILOG, ARGV0, logff[i].file);
                    if(logff[i].fp)
                    {
                        fclose(logff[i].fp);
                        logff[i].fp = NULL;
                    }
                    logff[i].file = NULL;
                }
                logff[i].read = (void *)read_djbmultilog;
            }
            else if(logff[i].logformat[0] >= '0' && logff[i].logformat[0] <= '9')
            {
                logff[i].read = (void *)read_multiline;
            }
            else
            {
                logff[i].read = (void *)read_syslog;
            }

            /* More tweaks for Windows. For some reason IIS places
             * some wierd characters at the end of the files and getc
             * always returns 0 (even after clearerr).
             */
            #ifdef WIN32
            if(logff[i].fp)
            {
                logff[i].read(i, &r, 1);
            }
            #endif
        }

        if(logff[i].alias)
        {
            int ii = 0;
            while(logff[i].alias[ii] != '\0')
            {
                if(logff[i].alias[ii] == ':')
                {
                    logff[i].alias[ii] = '\\';
                }
                ii++;
            }
        }
    }


    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, (int)getpid());
        
    max_file = i -1;


    /* Cannot be zero */
    if(max_file < 0)
    {
        max_file = 0;
    }
    
    
    /* Daemon loop */
    while(1)
    {
        #ifndef WIN32
        fp_timeout.tv_sec = loop_timeout;
        fp_timeout.tv_usec = 0;

        /* Waiting for the select timeout */ 
        if ((r = select(0, NULL, NULL, NULL, &fp_timeout)) < 0)
        {
            merror(SELECT_ERROR, ARGV0);
            int_error++;

            if(int_error >= 5)
            {
                ErrorExit(SYSTEM_ERROR, ARGV0);
            }
            continue;
        }
        #else
        
        /* Windows don't like select that way */
        sleep(loop_timeout + 2);

        
        /* Check for messages in the event viewer */
        win_readel();
        #endif
        
        f_check++;

        
        /* Checking which file is available */
        for(i = 0; i <= max_file; i++)
        {
            if(!logff[i].fp)
            {
                /* Run the command. */
                if(logff[i].command && (f_check %2))
                {
                    curr_time = time(0);
                    if((curr_time - logff[i].size) >= logff[i].ign)
                    {
                        logff[i].size = curr_time;
                        logff[i].read(i, &r, 0);
                    }
                }
                continue;
            }

            /* Windows with IIS logs is very strange.
             * For some reason it always returns 0 (not EOF)
             * the fgetc. To solve this problem, we always
             * pass it to the function pointer directly.
             */
            #ifndef WIN32
            /* We check for the end of file. If is returns EOF,
             * we don't attempt to read it.
             */
            if((r = fgetc(logff[i].fp)) == EOF)
            {
                clearerr(logff[i].fp);
                continue;
            }


            /* If it is not EOF, we need to return the read character */
            ungetc(r, logff[i].fp);
            #endif


            /* Finally, send to the function pointer to read it */
            logff[i].read(i, &r, 0);


            /* Checking for error */
            if(!ferror(logff[i].fp))
            {
                /* Clearing EOF */
                clearerr(logff[i].fp);

                /* Parsing error */
                if(r != 0)
                {
                    logff[i].ign++;
                }
            }
            /* If ferror is set */
            else
            {
                merror(FREAD_ERROR, ARGV0, logff[i].file);
                #ifndef WIN32
                if(fseek(logff[i].fp, 0, SEEK_END) < 0)
                #else
                if(1)
                #endif
                {

                    #ifndef WIN32
                    merror(FSEEK_ERROR, ARGV0, logff[i].file);
                    #endif

                    /* Closing the file */
                    if(logff[i].fp)
                    {
                        fclose(logff[i].fp);
                        #ifdef WIN32
                        CloseHandle(logff[i].h);
                        #endif
                    }
                    logff[i].fp = NULL;


                    /* Trying to open it again */
                    if(handle_file(i, 1, 1) != 0)
                    {
                        logff[i].ign++;
                        continue;
                    }
                    
                    #ifdef WIN32
                    logff[i].read(i, &r, 1);
                    #endif
                }

                /* Increase the error count  */
                logff[i].ign++;
                clearerr(logff[i].fp);
            }
        }

        
        /* Only check bellow if check > VCHECK_FILES */
        if(f_check <= VCHECK_FILES)
            continue;

            
        /* Send keep alive message */

        rand_keepalive_str(keepalive, 700);
        SendMSG(logr_queue, keepalive, "ossec-keepalive", LOCALFILE_MQ);


        /* Zeroing f_check */    
        f_check = 0;


        /* Checking if any file has been renamed/removed */
        for(i = 0; i <= max_file; i++)
        {
            /* These are the windows logs or ignored files */
            if(!logff[i].file)
                continue;
            
            
            /* Files with date -- check for day change */
            if(logff[i].ffile)
            {
                if(update_fname(i))
                {
                    if(logff[i].fp)
                    {
                        fclose(logff[i].fp);
                        #ifdef WIN32
                        CloseHandle(logff[i].h);
                        #endif
                    }
                    logff[i].fp = NULL;
                    handle_file(i, 0, 1);
                    continue;
                }

                /* Variable file name */
                else if(!logff[i].fp)
                {
                    handle_file(i, 0, 0);
                    continue;
                }
            }
            
            
            /* Check for file change -- if the file is open already */
            if(logff[i].fp)
            {
                #ifndef WIN32
                if(stat(logff[i].file, &tmp_stat) == -1)
                {
                    fclose(logff[i].fp);
                    logff[i].fp = NULL;
                    
                    merror(FILE_ERROR, ARGV0, logff[i].file);
                }

                #else
                BY_HANDLE_FILE_INFORMATION lpFileInformation;
                HANDLE h1;

                h1 = CreateFile(logff[i].file, GENERIC_READ,
                            FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,
                            NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
                if(h1 == INVALID_HANDLE_VALUE)
                {
                    fclose(logff[i].fp);
                    CloseHandle(logff[i].h);
                    logff[i].fp = NULL;
                    merror(FILE_ERROR, ARGV0, logff[i].file);
                }
                else if(GetFileInformationByHandle(h1, &lpFileInformation) == 0)
                {
                    fclose(logff[i].fp);
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
                    logff[i].fp = NULL;
                    merror(FILE_ERROR, ARGV0, logff[i].file);;
                }
                #endif


                #ifdef WIN32
                else if(logff[i].fd != (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh))
                #else
                else if(logff[i].fd != tmp_stat.st_ino)
                #endif
                {
                    char msg_alert[512 +1];

                    snprintf(msg_alert, 512, "ossec: File rotated (inode "
                                             "changed): '%s'.",
                                             logff[i].file);
                     
                    /* Send message about log rotated  */
                    SendMSG(logr_queue, msg_alert, 
                            "ossec-logcollector", LOCALFILE_MQ);
                            
                    debug1("%s: DEBUG: File inode changed. %s",
                            ARGV0, logff[i].file);
                    
                    fclose(logff[i].fp);

                    #ifdef WIN32
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
                    #endif
                    
                    logff[i].fp = NULL;
                    handle_file(i, 0, 1);
                    continue;
                }
                #ifdef WIN32
                else if(logff[i].size > (lpFileInformation.nFileSizeHigh + lpFileInformation.nFileSizeLow))
                #else
                else if(logff[i].size > tmp_stat.st_size)
                #endif
                {
                    char msg_alert[512 +1];

                    snprintf(msg_alert, 512, "ossec: File size reduced "
                                             "(inode remained): '%s'.",
                                             logff[i].file);
                     
                    /* Send message about log rotated  */
                    SendMSG(logr_queue, msg_alert, 
                            "ossec-logcollector", LOCALFILE_MQ);
                            
                    debug1("%s: DEBUG: File size reduced. %s",
                            ARGV0, logff[i].file);


                    /* Fixing size so we don't alert more than once */
                    logff[i].size = tmp_stat.st_size;


                    /* Getting new file. */
                    fclose(logff[i].fp);

                    #ifdef WIN32
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
                    #endif
                    
                    logff[i].fp = NULL;
                    handle_file(i, 1, 1);
                }
                #ifdef WIN32
                else
                {
                    CloseHandle(h1);
                }
                #endif
            }
            
            
            /* Too many errors for the file */ 
            if(logff[i].ign > open_file_attempts)
            {
                /* 999 Maximum ignore */
                if(logff[i].ign == 999)
                {
                    continue;
                }
                
                merror(LOGC_FILE_ERROR, ARGV0, logff[i].file);
                if(logff[i].fp)
                {
                    fclose(logff[i].fp);
                    #ifdef WIN32
                    CloseHandle(logff[i].h);
                    #endif
                }
                    
                logff[i].fp = NULL;


                /* If the file has a variable date, ignore it for
                 * today only.
                 */
                if(!logff[i].ffile)
                {
                    /* Variable log files should always be attempted
                     * to be open...
                     */
                    //logff[i].file = NULL;
                }
                logff[i].ign = 999;
                continue;
            }
           
           
            /* File not opened */ 
            if(!logff[i].fp)
            {
                if(logff[i].ign >= 999)
                    continue;
                else
                {
                    /* Try for a few times to open the file */
                    if(handle_file(i, 1, 1) < 0)
                    {
                        logff[i].ign++;
                    }
                    continue;
                }
            }
        }
    }
}
Example #14
0
static int EnumIpDataLines(const char *pszFileCSV,const char *pszFileOut)
{
	FILE *fp;
	char line[1024],out[512],*pszFrom,*pszTo,*pszTwo,*pszCountry,*buf;
	int i,j;
	DWORD dwOut;
	WORD wOut;
	struct ResizableByteBuffer buffer;

	memset(&buffer, 0, sizeof(buffer));
	fp=fopen(pszFileCSV,"rt");
	if (fp != NULL) {
		OutputDebugStringA("Running IP data convert...\n"); /* all ascii */
		while (!feof(fp)) {
			if (fgets(line,sizeof(line),fp) == NULL) break;
			/* get line data */
			pszFrom=line+1;
			pszTo=strchr(pszFrom,',');
			*(pszTo-1)='\0'; pszTo+=2;
			pszTwo=strchr(pszTo,',');
			*(pszTwo-1)='\0'; pszTwo+=2;
			pszCountry=strchr(pszTwo,',')+1;
			pszCountry=strchr(pszCountry,',')+2;
			buf=strchr(pszCountry,'"');
			*buf=pszTwo[2]='\0';
			/* corrections */
			if (!mir_tstrcmpi(pszCountry,"ANTARCTICA")) continue;
			if (!mir_tstrcmpi(pszCountry,"TIMOR-LESTE")) continue;
			if (!mir_tstrcmpi(pszCountry,"PALESTINIAN TERRITORY, OCCUPIED"))
				mir_tstrcpy(pszCountry,"ISRAEL");
			else if (!mir_tstrcmpi(pszCountry,"UNITED STATES MINOR OUTLYING ISLANDS"))
				mir_tstrcpy(pszCountry,"UNITED STATES");
			else if (!mir_tstrcmpi(pszCountry,"SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS"))
				mir_tstrcpy(pszCountry,"UNITED KINGDOM");
			else if (!mir_tstrcmpi(pszTwo,"JE")) /* map error */
				mir_tstrcpy(pszCountry,"UNITED KINGDOM");
			else if (!mir_tstrcmpi(pszTwo,"AX")) /* Åland Island belongs to Finland */
				mir_tstrcpy(pszCountry,"FINLAND");
			else if (!mir_tstrcmpi(pszTwo,"ME"))
				mir_tstrcpy(pszCountry,"MONTENEGRO");
			else if (!mir_tstrcmpi(pszTwo,"RS") || !mir_tstrcmpi(pszTwo,"CS"))
				mir_tstrcpy(pszCountry,"SERBIA");
			/* convert */
			for(i=0;i<nCountriesCount;i++) {
				/* map different writings */
				for(j=0;j<_countof(differentCountryNames);j++)
					if (!mir_tstrcmpi(countries[i].szName,differentCountryNames[j].szMir)) {
						buf=(char*)differentCountryNames[j].szCSV;
						break;
					}
				if (j == _countof(differentCountryNames))
					buf=(char*)countries[i].szName;
				/* check country */
				if (!mir_strcmpi(pszCountry,buf)) {
					dwOut=(DWORD)atoi(pszFrom);
					AppendToByteBuffer(&buffer,(void*)&dwOut,sizeof(DWORD));
					dwOut=(DWORD)atoi(pszTo);
					AppendToByteBuffer(&buffer,(void*)&dwOut,sizeof(DWORD));
					wOut=(WORD)countries[i].id;
					AppendToByteBuffer(&buffer,(void*)&wOut,sizeof(WORD));
					break;
				}
			}
			/* not in list */
			if (i == nCountriesCount) {
				mir_snprintf(out, _countof(out), "Unknown: %s-%s [%s, %s]\n", pszFrom, pszTo, pszTwo, pszCountry);
				OutputDebugStringA(out); /* all ascii */
			}
		}
		fclose(fp);
		OutputDebugStringA("Done!\n"); /* all ascii */
		if (buffer.buf != NULL) {
			HANDLE hFileOut;
			DWORD cbWritten=0;
			BYTE *compressed;
			DWORD cbCompressed;
			/* compress whole data */
			OutputDebugStringA("Compressing...\n"); /* all ascii */
			compressed=(BYTE*)mir_alloc(buffer.cbAlloced+384);
			if (compressed != NULL) {
				cbCompressed=Huffman_Compress(buffer.buf,compressed,buffer.cbLength);
				OutputDebugStringA("Done!\n"); /* all ascii */
				OutputDebugStringA("Writing to file...\n"); /* all ascii */
				hFileOut=CreateFile(pszFileOut,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
				if (hFileOut != INVALID_HANDLE_VALUE) {
					/* store data length count at beginning */
					dwOut=buffer.cbLength;
					WriteFile(hFileOut,&dwOut,sizeof(DWORD),&cbWritten,NULL);
					/* store compressed data records */
					WriteFile(hFileOut,compressed,cbCompressed,&cbWritten,NULL);
					CloseHandle(hFileOut);
				}
				OutputDebugStringA("Done!\n"); /* all ascii */
				mir_free(compressed);
			}
			mir_free(buffer.buf);
		}
		return 0;
	}
	return 1;
}
Example #15
0
static LONG __stdcall MyCrashHandlerExceptionFilter(EXCEPTION_POINTERS* pEx) 
{
#ifdef _M_IX86 
  if (pEx->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW)   
  { 
    // be sure that we have enought space... 
    static char MyStack[1024*128];   
    // it assumes that DS and SS are the same!!! (this is the case for Win32) 
    // change the stack only if the selectors are the same (this is the case for Win32) 
    //__asm push offset MyStack[1024*128]; 
    //__asm pop esp; 
    __asm mov eax,offset MyStack[1024*128]; 
    __asm mov esp,eax; 
  } 
#endif 
  MyStackWalker sw;
  sw.ShowCallstack(GetCurrentThread(), pEx->ContextRecord);
  Base::Console().Log("*** Unhandled Exception!\n");
  Base::Console().Log("   ExpCode: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionCode);
  Base::Console().Log("   ExpFlags: %d\n", pEx->ExceptionRecord->ExceptionFlags);
  Base::Console().Log("   ExpAddress: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionAddress);

  bool bFailed = true; 
  HANDLE hFile; 
  hFile = CreateFile(s_szMiniDumpFileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 
  if (hFile != INVALID_HANDLE_VALUE) 
  { 
    MINIDUMP_EXCEPTION_INFORMATION stMDEI; 
    stMDEI.ThreadId = GetCurrentThreadId(); 
    stMDEI.ExceptionPointers = pEx; 
    stMDEI.ClientPointers = true; 
    // try to create an miniDump: 
    if (s_pMDWD( 
      GetCurrentProcess(), 
      GetCurrentProcessId(), 
      hFile, 
      s_dumpTyp, 
      &stMDEI, 
      NULL, 
      NULL 
      )) 
    { 
      bFailed = false;  // suceeded 
    } 
    CloseHandle(hFile); 
  } 

  if (bFailed) 
  { 
    return EXCEPTION_CONTINUE_SEARCH; 
  } 

  // Optional display an error message 
  // FatalAppExit(-1, ("Application failed!")); 


  // or return one of the following: 
  // - EXCEPTION_CONTINUE_SEARCH 
  // - EXCEPTION_CONTINUE_EXECUTION 
  // - EXCEPTION_EXECUTE_HANDLER 
  return EXCEPTION_CONTINUE_SEARCH;  // this will trigger the "normal" OS error-dialog 
} 
Example #16
0
/*
 * ======================================================================= *
 * In the startup of this program, we look at our executable name and      *
 * replace the ".EXE" with ".DLL" to find the ISAPI DLL we need to load.   *
 * This means that the executable need only be given the same "name" as    *
 * the DLL to load. There is no recompilation required.                    *
 * ======================================================================= *
*/
BOOL stress_main(const char *filename, 
				const char *arg, 
				const char *postdata,
				const char *matchdata) 
{

	EXTENSION_CONTROL_BLOCK ECB;
	DWORD rc;
	TIsapiContext context;

	// open output and input files
	context.tid = GetCurrentThreadId();
	CString fname;
	fname.Format("%08X.out", context.tid);

	context.out = CreateFile(fname, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
	if (context.out==INVALID_HANDLE_VALUE) {
		printf("failed to open output file %s\n", fname);
		return 0;
	}

	// not using post files
	context.in = INVALID_HANDLE_VALUE;

	//
	// Fill the ECB with the necessary information
	//
	if (!FillExtensionControlBlock(&ECB, &context) ) {
		fprintf(stderr,"Fill Ext Block Failed\n");
		return -1;
	}
	
	// check for command line argument, 
	// first arg = filename
	// this is added for testing php from command line

	context.env.RemoveAll();
	context.env["PATH_TRANSLATED"]= filename;
	context.env["SCRIPT_MAP"]= filename;
	context.env["CONTENT_TYPE"]= "";
	context.env["CONTENT_LENGTH"]= "";
	context.env["QUERY_STRING"]= arg;
	context.env["METHOD"]="GET";
	context.env["PATH_INFO"] = "";
	context.waitEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	char buf[MAX_PATH];
	if (postdata && *postdata !=0) {
		ECB.cbAvailable = strlen(postdata);
		ECB.cbTotalBytes = ECB.cbAvailable;
		ECB.lpbData = (unsigned char *)postdata;
		context.env["METHOD"]="POST";

		_snprintf(buf, sizeof(buf)-1, "%d", ECB.cbTotalBytes);
		context.env["CONTENT_LENGTH"]=buf;

		context.env["CONTENT_TYPE"]="application/x-www-form-urlencoded";
	}
	ECB.lpszMethod = strdup(context.env["METHOD"]);
    ECB.lpszPathTranslated = strdup(filename);
	ECB.lpszQueryString = strdup(arg);
	ECB.lpszPathInfo = strdup(context.env["PATH_INFO"]);


	// Call the DLL
	//
	rc = IsapiHttpExtensionProc(&ECB);
	if (rc == HSE_STATUS_PENDING) {
		// We will exit in ServerSupportFunction
		WaitForSingleObject(context.waitEvent, INFINITE);
	}
	CloseHandle(context.waitEvent);
	//Sleep(75);
	free(ECB.lpszPathTranslated);
	free(ECB.lpszQueryString);
	free(ECB.lpszMethod);
	free(ECB.lpszPathInfo);

	BOOL ok = TRUE;

	if (context.out != INVALID_HANDLE_VALUE) CloseHandle(context.out);

	// compare the output with the EXPECT section
	if (matchdata && *matchdata != 0) {
		ok = CompareFiles(fname, matchdata);
	}

	DeleteFile(fname);

	return ok;
		
}
Example #17
0
bool
Serial::open(QString &err)
{
#ifndef Q_OS_WIN32

    //
    // Linux and Mac OSX use stdio / termio / tcsetattr
    //
    assert(fd < 0);
    fd = ::open(path.toAscii().constData(), O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd < 0) {
        err = QString("open: ") + strerror(errno);
        return false;
    }
    struct termios tty;
    int flags = fcntl(fd, F_GETFL, 0);
    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
        perror("fcntl");
        assert(0);
    }
    if (tcgetattr(fd, &tty) == -1) {
        perror("tcgetattr");
        assert(0);
    }
    tty.c_cflag &= ~CRTSCTS; /* no hardware flow control */
    tty.c_cflag &= ~(PARENB | PARODD); /* no parity */
    tty.c_cflag &= ~CSTOPB; /* 1 stop bit */
    tty.c_cflag &= ~CSIZE; /* clear size bits */
    tty.c_cflag |= CS8; /* 8 bits */
    tty.c_cflag |= CLOCAL | CREAD; /* ignore modem control lines */
    if (cfsetspeed(&tty, B9600) == -1) {
        perror("cfsetspeed");
        assert(0);
    }
    tty.c_iflag = IGNBRK; /* ignore BREAK condition on input */
    tty.c_lflag = 0;
    tty.c_oflag = 0;
    tty.c_cc[VMIN] = 1; /* all reads return at least one character */
    if (tcsetattr(fd, TCSANOW, &tty) == -1) {
        perror("tcsetattr");
        assert(0);
    }
    return true;
#else

    //
    // Windows uses CreateFile / DCB / SetCommState
    //

    DCB deviceSettings;    // serial port settings baud rate et al
    COMMTIMEOUTS timeouts; // timeout settings on serial ports

    // if deviceFilename references a port above COM9
    // then we need to open "\\.\COMX" not "COMX"
	QString portSpec = "\\\\.\\" + path;
    wchar_t deviceFilenameW[32]; // \\.\COM32 needs 9 characters, 32 should be enough?
    MultiByteToWideChar(CP_ACP, 0, portSpec.toAscii(), -1, (LPWSTR)deviceFilenameW,
                    sizeof(deviceFilenameW));

    // win32 commport API
    fd = CreateFile (deviceFilenameW, GENERIC_READ|GENERIC_WRITE,
        FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

    if (fd == INVALID_HANDLE_VALUE) return isOpen = false;

    if (GetCommState (fd, &deviceSettings) == false) return isOpen = false;

    // so we've opened the comm port lets set it up for
    deviceSettings.BaudRate = CBR_9600;
    deviceSettings.fParity = NOPARITY;
    deviceSettings.ByteSize = 8;
    deviceSettings.StopBits = ONESTOPBIT;
    deviceSettings.EofChar = 0x0;
    deviceSettings.ErrorChar = 0x0;
    deviceSettings.EvtChar = 0x0;
    deviceSettings.fBinary = TRUE;
    deviceSettings.fRtsControl = 0x0;
    deviceSettings.fOutxCtsFlow = FALSE;


    if (SetCommState(fd, &deviceSettings) == false) {
        CloseHandle(fd);
        return isOpen = false;
    }

    timeouts.ReadIntervalTimeout = 0;
    timeouts.ReadTotalTimeoutConstant = 5000;
    timeouts.ReadTotalTimeoutMultiplier = 50;
    timeouts.WriteTotalTimeoutConstant = 5000;
    timeouts.WriteTotalTimeoutMultiplier = 0;
    SetCommTimeouts(fd, &timeouts);

    return isOpen = true;
#endif
}
Example #18
0
value setup(value a, value b) {
	const char* portName = val_string(a);
	int baud = val_int(b);
	
	//---------------------------------------------
	#if defined( TARGET_OSX ) || defined( TARGET_LINUX )
	//---------------------------------------------
	int fd = open(portName, O_RDWR | O_NOCTTY | O_NONBLOCK);
	if(fd == -1){
		return alloc_null();
	}

	struct termios options;
	struct termios oldoptions;
	tcgetattr(fd,&oldoptions);
	options = oldoptions;
	switch(baud){
		case 300:
			cfsetispeed(&options,B300);
			cfsetospeed(&options,B300);
			break;
		case 1200:
			cfsetispeed(&options,B1200);
			cfsetospeed(&options,B1200);
			break;
		case 2400:
			cfsetispeed(&options,B2400);
			cfsetospeed(&options,B2400);
			break;
		case 4800:
			cfsetispeed(&options,B4800);
			cfsetospeed(&options,B4800);
			break;
		case 9600:
			cfsetispeed(&options,B9600);
			cfsetospeed(&options,B9600);
			break;
		#ifdef TARGET_OSX
		case 14400:
			cfsetispeed(&options,B14400);
			cfsetospeed(&options,B14400);
			break;
		#endif
		case 19200:
			cfsetispeed(&options,B19200);
			cfsetospeed(&options,B19200);
			break;
		#ifdef TARGET_OSX
		case 28800:
			cfsetispeed(&options,B28800);
			cfsetospeed(&options,B28800);
			break;
		#endif
		case 38400:
			cfsetispeed(&options,B38400);
			cfsetospeed(&options,B38400);
			break;
		case 57600:
			cfsetispeed(&options,B57600);
			cfsetospeed(&options,B57600);
			break;
		case 115200:
			cfsetispeed(&options,B115200);
			cfsetospeed(&options,B115200);
			break;
		default:
			cfsetispeed(&options,B9600);
			cfsetospeed(&options,B9600);
			break;
	}

	options.c_cflag |= (CLOCAL | CREAD);
	options.c_cflag &= ~(PARENB | PARODD);
	options.c_cflag &= ~CSTOPB;
	options.c_cflag &= ~CRTSCTS;
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;

	if (tcsetattr(fd,TCSANOW,&options) != 0)
	{
		return alloc_null();
	}

	return alloc_int(fd);

	//---------------------------------------------
	#endif
	//---------------------------------------------


	//---------------------------------------------
	#ifdef TARGET_WIN32
	//---------------------------------------------

	// open the serial port:
	// "COM4", etc...

	HANDLE hComm = CreateFile(
		portName,
		GENERIC_READ|GENERIC_WRITE,
		0,
		NULL,
		OPEN_EXISTING,
		0,
		NULL
	);

	if(hComm==INVALID_HANDLE_VALUE){
		return alloc_null();
	}

	// now try the settings:
	COMMCONFIG cfg;
	DWORD cfgSize;
	char  buf[80];

	cfgSize=sizeof(cfg);
	GetCommConfig(hComm,&cfg,&cfgSize);
	int bps = baud;
	sprintf(buf,"baud=%d parity=N data=8 stop=1",bps);

	#if (_MSC_VER)       // microsoft visual studio
		// msvc doesn't like BuildCommDCB,
		//so we need to use this version: BuildCommDCBA
		if(!BuildCommDCBA(buf,&cfg.dcb)){
			//ofLog(OF_LOG_ERROR,"ofSerial: unable to build comm dcb; (%s)",buf);
		}
	#else
		if(!BuildCommDCB(buf,&cfg.dcb)){
			//ofLog(OF_LOG_ERROR,"ofSerial: Can't build comm dcb; %s",buf);
		}
	#endif


	// Set baudrate and bits etc.
	// Note that BuildCommDCB() clears XON/XOFF and hardware control by default

	if(!SetCommState(hComm,&cfg.dcb)){
		//ofLog(OF_LOG_ERROR,"ofSerial: Can't set comm state");
	}
	//ofLog(OF_LOG_NOTICE,buf,"bps=%d, xio=%d/%d",cfg.dcb.BaudRate,cfg.dcb.fOutX,cfg.dcb.fInX);

	// Set communication timeouts (NT)
	COMMTIMEOUTS tOut;
	COMMTIMEOUTS oldTimeout;
	GetCommTimeouts(hComm,&oldTimeout);
	tOut = oldTimeout;
	// Make timeout so that:
	// - return immediately with buffered characters
	tOut.ReadIntervalTimeout=MAXDWORD;
	tOut.ReadTotalTimeoutMultiplier=0;
	tOut.ReadTotalTimeoutConstant=0;
	SetCommTimeouts(hComm,&tOut);
	
	return alloc_int((int)hComm);
	//---------------------------------------------
	#endif
	//---------------------------------------------
}
Example #19
0
LRESULT CALLBACK WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static HWND hEdit;

	switch( msg )
	{	
	case WM_CREATE:
		
		hEdit = CreateWindow( "edit", "", 
							WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE,
							10, 10, 500,500, hwnd, (HMENU)1, 0, 0);
		return 0;
	/*
	case WM_LBUTTONDOWN:
		{
			HANDLE hRead, hWrite;
			CreatePipe( & hRead, & hWrite, 0, 1024);
			SetHandleInformation( hWrite, HANDLE_FLAG_INHERIT, 
										  HANDLE_FLAG_INHERIT );

			PROCESS_INFORMATION pi = {0};
			STARTUPINFO si = { 0};
				
			si.cb = sizeof(si );
			si.hStdOutput = hWrite;//쓰기위한 파이프 핸들을 자식의 표준출력으로
			si.dwFlags = STARTF_USESTDHANDLES;

			BOOL b = CreateProcess( 0, "ping.exe www.imbc.com", 0,0, TRUE,
									CREATE_NO_WINDOW, 0, 0, &si, &pi );
			if ( b )
			{
				CloseHandle( hWrite ); // 쓰기위한 핸들은 필요 없다.

				DWORD len;
				while ( 1 )
				{
					char s[4096] = {0};
					BOOL bRet = ReadFile( hRead, s, 4096, &len, 0);

					if ( bRet == FALSE ) break; // 파이프가 닫힌 경우.

					// SetWindowText()를 사용하면 기존의 edit data 가 지워지고
					// 새롭게 추가 된다. - 한줄씩 덧붙이려면!
					SendMessage( hEdit, EM_REPLACESEL, 0, (LPARAM)s);
				}
				CloseHandle( hRead );
				CloseHandle( pi.hProcess);
				CloseHandle( pi.hThread);
			}
		}
		return 0;
	*/





	case WM_LBUTTONDOWN: 
		{
			PROCESS_INFORMATION pi = { 0 } ;
			
			// ping 출력을 redirect 할 파일 생성
			HANDLE hFile = CreateFile( "a.txt", GENERIC_READ | GENERIC_WRITE,
										FILE_SHARE_READ | FILE_SHARE_WRITE,
										0, 
										CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

			// 모든 KO 는 기본적으로 상속 불가능 하다.
			// 특정 KO를 상속가능하게 변경한다.
			SetHandleInformation( hFile, HANDLE_FLAG_INHERIT, // 상속가능여부를
										 HANDLE_FLAG_INHERIT ); // 상속가능하게.
			//===============================================================
			STARTUPINFO si = {0};
			si.cb = sizeof( si );

			si.hStdOutput = hFile;  // ping 의 stdout과 연결할 파일.
			si.dwFlags    = STARTF_USESTDHANDLES;


			BOOL b = CreateProcess( 0, "ping.exe www.imbc.com", 0,0, TRUE,
							CREATE_NO_WINDOW, // flag. console을 만들지말라
									0, 0, &si, &pi);
			if ( b )
			{
				// ping이 종료 될때까지 대기한다.
				WaitForSingleObject( pi.hProcess, INFINITE );

				// a.txt 에서 모든 data를 읽어서 edit에 출력한다.
				char s[4096] = {0};

				SetFilePointer( hFile, 0, 0, FILE_BEGIN); // 화일 포인터를 제일 
														  // 앞으로
				DWORD len;
				ReadFile( hFile, s, 4096, &len, 0);

				SetWindowText( hEdit, s );

				CloseHandle( hFile );
				//===========================================
					
				


				CloseHandle( pi.hProcess );
				CloseHandle( pi.hThread );
			}
		}
		return 0;

	


//레지스트리 찾는법...
//HKEY_CURRENT_USER			\software \ 회사이름 \ 프로그램이름	\ 각종 세팅값.
//HKEY_LOCAL_MACHINE
//regedit.exe


//www.codeproject.com	// 윈도우 개발 관련 소스코드 사이트
//www.catch22.net		//
//www.codeguru.com		// 3개는 전부 외국 사이트..
//www.devia.com			// -한글











	case WM_DESTROY:
		PostQuitMessage(0); 
		return 0;
	}
	return DefWindowProc( hwnd, msg, wParam, lParam);
}
Example #20
0
int CMapFileIO::LoadTileTypesDict(CTileTypesDict& Dict) const
{
	WCHAR* fname = new WCHAR[MAX_PATH];
	wsprintf(fname, L"%s\\tiles\\*", g_ContentPath);
	WIN32_FIND_DATA ffd;

	XML_MANAGER_HANDLE xml = 0;
	HANDLE file = INVALID_HANDLE_VALUE;
	WCHAR* listpath = new WCHAR[MAX_PATH];
	WCHAR* imgpath = new WCHAR[MAX_PATH];
	CTileType *t;

	HANDLE search = FindFirstFile(fname, &ffd);
	do
	{
		if((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && ffd.cFileName[0] != '.')
		{
			wsprintf(listpath, L"%s\\tiles\\%s\\tiles.xml", g_ContentPath, ffd.cFileName);
			file = INVALID_HANDLE_VALUE;
			file = CreateFile(listpath, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
			if(file == INVALID_HANDLE_VALUE)
				return 1;   
			xml = 0;
			xml = CreateWorker();
			if(!xml)
				return 1;
			DWORD res = ReadFromFileHandle(xml, file);
			if(res != ERROR_SUCCESS) 
				return 1;
			CloseHandle(file);
			XML_NODE_HANDLE node = RetrieveNode(xml, 0, L"tile");
			while(node)
			{
				//name
				LPWSTR name = GetNodeAttr(xml, node, L"name");
				XML_NODE_HANDLE hImg = RetrieveNode(xml, node, L"img");
				XML_NODE_HANDLE hSt = RetrieveNode(xml, node, L"stats");
				XML_NODE_HANDLE hMov = RetrieveNode(xml, node, L"movement");
				//img
				LPWSTR img = GetNodeAttr(xml, hImg, L"path");
				//hp
				LPWSTR hpt = GetNodeAttr(xml, hSt, L"hp");
				int hp = _wtoi(hpt);
				//hrd
				LPWSTR hrdt = GetNodeAttr(xml, hSt, L"hardness");
				int hrd = _wtoi(hrdt);
				LPWSTR rgnt = GetNodeAttr(xml, hSt, L"regenspeed");
				float regenval = (float)_wtof(rgnt);

				LPWSTR blok = GetNodeAttr(xml, hMov, L"blocks");
				bool block = _wcsicmp(blok, L"YES") == 0;

				t = Dict.Give(name);
				t->SetHardness(hrd);
				t->SetMaxHP(hp);
				t->SetRegen(regenval);
				wsprintf(imgpath, L"tiles\\%s\\%s", ffd.cFileName, img);
				t->SetImageFile(imgpath);
				t->SetType(ffd.cFileName);

				ReleaseNode(hImg);
				ReleaseNode(hSt);
				ReleaseNode(hMov);

				ReleaseTextString(name);
				ReleaseTextString(img);
				ReleaseTextString(hrdt);
				ReleaseTextString(hpt);
				ReleaseTextString(blok);

				node = GetNextNode(xml, node);
			}
		} 
	}while(FindNextFile(search, &ffd) != 0);
	ReleaseWorker(xml);
	FindClose(search);
	delete[] imgpath;
	delete[] fname;
	delete[] listpath;
	return 0;
}
Example #21
0
int __cdecl main(int argc, char **argv)
{
    DWORD TheResult;
    HANDLE TheFile;
    WCHAR FileName[MAX_PATH];
    
    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }
    
    /* Make a wide character string for the file name */
    
    MultiByteToWideChar(CP_ACP,
                        0,
                        "test_file",
                        -1,
                        FileName,
                        MAX_PATH);
    
    
    /* Try to set the file to Read-only */

    TheResult = SetFileAttributes(FileName,FILE_ATTRIBUTE_READONLY);
    
    if(TheResult == 0)
    {
        Fail("ERROR: SetFileAttributes returned 0, failure, when trying "
               "to set the FILE_ATTRIBUTE_READONLY attribute.");
    }

    /* Attempt to open this READONLY file with WRITE access,
       The open should fail and the HANDLE should be invalid.
    */

    TheFile = CreateFile(
        FileName,                         // file name
        GENERIC_READ|GENERIC_WRITE,       // access mode
        0,                                // share mode
        NULL,                             // SD
        OPEN_ALWAYS,                      // how to create
        FILE_ATTRIBUTE_NORMAL,            // file attributes
        NULL                              // handle to template file
        );

    if(TheFile != INVALID_HANDLE_VALUE) 
    {
        Fail("ERROR: Tried to open a file that was created as "
               "READONLY with the GENERIC_WRITE access mode.  This should"
               " cause CreateFile to return an INVALID_HANDLE_VALUE.");
    }

    /* Try to open the file with READ access, this should be ok.
       The HANDLE will be valid.
    */

    TheFile = CreateFile(
        FileName,                         // file name
        GENERIC_READ,                     // access mode
        0,                                // share mode
        NULL,                             // SD
        OPEN_ALWAYS,                      // how to create
        FILE_ATTRIBUTE_NORMAL,            // file attributes
        NULL                              // handle to template file
        );

    if(TheFile == INVALID_HANDLE_VALUE) 
    {
        Fail("ERROR: Tried to open a file that was created as "
               "READONLY with the GENERIC_READ access mode.  This should"
               " cause CreateFile to return an valid handle, but "
               "INVALID_HANDLE_VALUE was returned!.");
    }
    
    /* Close that HANDLE */

    TheResult = CloseHandle(TheFile);

    if(TheResult == 0) 
    {
        Fail("ERROR: CloseHandle failed.  This tests relies upon it "
               "working properly.");
    }

    /* Set the file to NORMAL */

    TheResult = SetFileAttributes(FileName,FILE_ATTRIBUTE_NORMAL);
     
    if(TheResult == 0)
    {
        Fail("ERROR: SetFileAttributes returned 0, failure, when trying "
               "to set the FILE_ATTRIBUTE_NORMAL attribute.");
    }

    /* To ensure that the set worked correctly, try to open the file
       with WRITE access again -- this time it should succeed.
    */

    TheFile = CreateFile(
        FileName,                         // file name
        GENERIC_READ|GENERIC_WRITE,       // access mode
        0,                                // share mode
        NULL,                             // SD
        OPEN_ALWAYS,                      // how to create
        FILE_ATTRIBUTE_NORMAL,            // file attributes
        NULL                              // handle to template file
        );
     
    if(TheFile == INVALID_HANDLE_VALUE) 
    {
        Fail("ERROR: Tried to open a file that was created as "
               "NORMAL with the GENERIC_WRITE access mode.  This should"
               " cause CreateFile to return an valid handle, but "
               "INVALID_HANDLE_VALUE was returned!.");
    }

    
    PAL_Terminate();
    return PASS;
}
Example #22
0
void handleAttach()
{
#if defined(os_bg_test)
   return;
#elif !defined(os_windows_test)
   char ch = 'T';
   struct timeval start_time;
   if (!useAttach) return;
   if (write(pfd, &ch, sizeof(char)) != sizeof(char)) {
      output->log(STDERR, "*ERROR*: Writing to pipe\n");
      exit(-1);
   }
   close(pfd);

   logstatus("mutatee %d: Waiting for mutator to attach...\n", getpid());
   gettimeofday(&start_time, NULL);

#else
   char ch = 'T';
   LPCTSTR pipeName = "\\\\.\\pipe\\mutatee_signal_pipe";
   DWORD bytes_written = 0;
   BOOL wrote_ok = FALSE;
   HANDLE signalPipe;

  
   if (!useAttach) return;

   signalPipe = CreateFile(pipeName,
                           GENERIC_WRITE,
                           0,
                           NULL,
                           OPEN_EXISTING,
                           0,
                           NULL);
   if(signalPipe == INVALID_HANDLE) 
   {
      if(GetLastError() != ERROR_PIPE_BUSY)
      {

         output->log(STDERR, "*ERROR*: Couldn't open pipe\n");
         exit(-1);
      }
      if(!WaitNamedPipe(pipeName, 2000))
      {

		  output->log(STDERR, "*ERROR*: Couldn't open pipe\n");
         exit(-1);
      }
   }
   wrote_ok = WriteFile(signalPipe,
                        &ch,
                        1,
                        &bytes_written,
                        NULL);
   if(!wrote_ok ||(bytes_written != 1))
   {

      output->log(STDERR, "*ERROR*: Couldn't write to pipe\n");
      exit(-1);
   }
   CloseHandle(signalPipe);

   logstatus("mutatee: Waiting for mutator to attach...\n");
#endif
 
   setUseAttach(TRUE);

   flushOutputLog();

   while (!checkIfAttached()) {
#if !defined(os_windows_test) && !defined(os_bg_test)
      struct timeval present_time;
      gettimeofday(&present_time, NULL);
      if (present_time.tv_sec > (start_time.tv_sec + 30))
      {
         if (checkIfAttached())
            break;
         logstatus("mutatee: mutator attach problem, failing...\n");
         exit(-1);
      }
#endif
      /* Do nothing */
   }
   fflush(stderr);

   logstatus("Mutator attached.  Mutatee continuing.\n");
}
Example #23
0
//------------------------------------------------------------------------------
HANDLE DNAUSB::openDevice( const int vid, const int pid, const char* vendor, char* product )
{
	HANDLE handle = INVALID_HANDLE_VALUE;

	// from DDK
	const GUID GUID_DEVINTERFACE_HID = { 0x4D1E55B2L, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } };

	for( int tries = 0; (tries < 10) && (handle == INVALID_HANDLE_VALUE) ; tries++ )
	{
		HANDLE deviceSet = SetupDiGetClassDevs( &GUID_DEVINTERFACE_HID, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE );

		if ( deviceSet == INVALID_HANDLE_VALUE )    
		{
			break;
		}    

		SP_INTERFACE_DEVICE_DATA interfaceInfo;    
		SP_DEVINFO_DATA deviceInfoData;
		interfaceInfo.cbSize = sizeof( interfaceInfo );
		deviceInfoData.cbSize = sizeof( SP_DEVINFO_DATA );
		BYTE buf[1024];
		DWORD size;

		int i=0;
		if( SetupDiEnumDeviceInfo(deviceSet, i++, &deviceInfoData) )
		{
			DWORD interfaceNumber = 0;
			while ( SetupDiEnumDeviceInterfaces( deviceSet,
												 0, 
												 &GUID_DEVINTERFACE_HID,
												 interfaceNumber++,
												 &interfaceInfo) )
			{
				SP_DEVICE_INTERFACE_DETAIL_DATA *details = (SP_DEVICE_INTERFACE_DETAIL_DATA *)buf;
				details->cbSize = sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA);

				size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + 256;

				if ( !SetupDiGetDeviceInterfaceDetail( deviceSet, 
													   &interfaceInfo,
													   details,
													   size,
													   0,
													   0 ) )
				{
					Log( "SetupDiGetDeviceInterfaceDetail failed [%d]", GetLastError() );
					continue;
				}

				Cstr temp;
				temp.toChar( details->DevicePath );
				temp.toLower();
				Log( "Considering [%s]", temp.c_str() );

				const char* vidStr = strstr( temp.c_str(), "vid" );
				if ( !vidStr )
				{
					Log( "vid not found [%s]", temp.c_str() );
					continue;
				}
				vidStr += 3;

				for( ; *vidStr && !isxdigit(*vidStr); vidStr++ );

				if ( !vidStr )
				{
					Log( "could not find valid vid [%s]", temp.c_str() );
					continue;
				}

				if ( strtol(vidStr, 0, 16) != vid )
				{
					continue;
				}

				const char* pidStr = strstr( temp.c_str(), "pid" );
				if ( !pidStr )
				{
					Log( "pid not found [%s]", temp.c_str() );
					continue;
				}
				pidStr += 3;

				for( ; *pidStr && !isxdigit(*pidStr); pidStr++ );

				if ( !pidStr )
				{
					Log( "could not find valid pid [%s]", temp.c_str() );
					continue;
				}

				if ( strtol(pidStr, 0, 16) != pid )
				{
					continue;
				}

				int openFlag = 0;  // may be FILE_FLAG_OVERLAPPED
				handle = CreateFile( details->DevicePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, openFlag, NULL );
				if ( handle == INVALID_HANDLE_VALUE )
				{
					Log( "could not open device" );
					continue;
				}

				if( !HidD_GetManufacturerString(handle, buf, 1024) )
				{
					CloseHandle( handle );
					handle = INVALID_HANDLE_VALUE;
					Log( "could not fetch manufacturer string" );
					continue;
				}

				temp.toChar( (wchar_t*)buf );
				Log( "manufacturer [%s]", temp.c_str() );

				if ( !temp.isMatch(vendor, false) )
				{
					CloseHandle( handle );
					handle = INVALID_HANDLE_VALUE;
					continue;
				}

				Sleep(10);

				if ( product )
				{
					HidD_GetProductString( handle, buf, 1024 );
					temp.toChar( (wchar_t*)buf );
					strcpy( product, temp.c_str() );
				}

				break;
			}
		}

		SetupDiDestroyDeviceInfoList( deviceSet );

		if ( handle == INVALID_HANDLE_VALUE )
		{
			Arch::sleep( 2000 );
		}
	}

	return handle;
}
Example #24
0
BOOL CTxtDropTarget::OnDrop(CWnd* pWnd, COleDataObject* pDataObject,
                           DROPEFFECT dropEffect, CPoint point)
{
	try{
	CString strMsg;
	//
    HGLOBAL hData=pDataObject->GetGlobalData(CF_TEXT);
    if (hData)
	{
		LPCSTR lpcszData=(LPCSTR)GlobalLock(hData);
		GlobalUnlock(hData);

		//if it is a link
		HGLOBAL hLinkData=pDataObject->GetGlobalData(RegisterClipboardFormat("FileGroupDescriptor"));
		LPCSTR lpcszLink;
		if(hLinkData)
		{
			lpcszLink=((LPCSTR)GlobalLock(hLinkData)) + 76;
			strMsg = lpcszLink;
			strMsg = strMsg.Left(strMsg.GetLength()-4);//cut .url of abc.url
			strMsg += " => ";
			strMsg += lpcszData;
			GlobalUnlock(hLinkData);
		}
		else
			strMsg += lpcszData;
		strMsg += "\r\n";
		SaveText(strMsg, 0);
	}
	else
	{
		hData=pDataObject->GetGlobalData(CF_HDROP);
		if (!hData) 
		{
			TRACE("Fail in getting data\n");
			MSGBOX(IDS_NOT_DROP_IMG);
			return FALSE;
		}

		HDROP hdrop =(HDROP)GlobalLock(hData);
		DragQueryFile(hdrop, 0, g_szFile, 1024);
		GlobalUnlock(hData);

		CString filename, rfile;
		filename = g_szFile;
		int l = filename.ReverseFind('\\');
		filename = filename.Mid(l+1);
		//fix filename, remove [x]
		l = filename.ReverseFind('[');
		int i = filename.ReverseFind(']');
		CString ext = filename.Mid(i+1);
		filename = filename.Left(l);
		//?
		CString imgPath = ((CVeryIEApp*)AfxGetApp())->m_strImagePath;
		if(pmf->m_bImgCateWithSite)
		{
			CString site;
			CChildFrame* tcf = (CChildFrame*)pmf->MDIGetActive();
			site = tcf->m_pView->m_lpszUrl;
			pmf->GetSiteName(site);
			imgPath = imgPath + site + "\\";
		}
		//create dir
		_CreateFullDir(imgPath);
		filename = imgPath + filename;
		//compare file size
		DWORD sz1=0, sz2=0;
		HANDLE hfile = INVALID_HANDLE_VALUE;
		hfile = CreateFile(g_szFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if(hfile != INVALID_HANDLE_VALUE)
			sz1 = GetFileSize(hfile, NULL);
		CloseHandle(hfile);
		hfile = INVALID_HANDLE_VALUE;
		hfile = CreateFile(filename+ext, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if(hfile != INVALID_HANDLE_VALUE)
			sz2 = GetFileSize(hfile, NULL);
		CloseHandle(hfile);

		rfile = filename + ext;
		if (sz1==0)//img not show
		{
			MSGBOX(IDS_SAVEIMAGEFAIL);
			return TRUE;
		}
		else if (sz1==sz2)//exist the same file
		{
			LOADSTR(strMsg ,IDS_IMG_EXISTED);
			strMsg += rfile;
			pmf->SetMessageText(strMsg);//SaveText(strMsg,13);
			return TRUE;
		}
		else if(sz1!=sz2 && sz2!=0)
		{
			char tmp[4];
			l = 0;
			HFILE hf; OFSTRUCT of;
			hf = OpenFile(rfile, &of, OF_EXIST);
			while(hf!=HFILE_ERROR)
			{
				l++;
				rfile = filename;
				rfile += '[';
				itoa(l, tmp, 10);
				rfile += tmp;
				rfile += ']';
				rfile += ext;
				hf = OpenFile(rfile, &of, OF_EXIST);
			}
		}
		
		//copy files
		if(!CopyFile(g_szFile, rfile, FALSE))
		{
			DWORD dwError = GetLastError();
			if(dwError == ERROR_PATH_NOT_FOUND)
				MSGBOX(IDS_SAVEIMAGEFAIL);
		}
		else
		{
			LOADSTR(strMsg ,IDS_IMG_SAVE_TO);
			strMsg += rfile;
			//
			CChildFrame* tcf = (CChildFrame*)pmf->MDIGetActive();
			strMsg += " <= ";
			strMsg += tcf->m_pView->m_lpszUrl;
			//
			SaveText(strMsg,13);
		}
	}

	}catch(...){}

    return TRUE;
}
Example #25
0
bool SaveMRToBMP(const char *pbBuffer, int dwBufferSize, const char *psFileName)
{
	// Check if the buffer size is valid.
	if (dwBufferSize <= sizeof(MRHeader))
	{
		// Print error and return false.
		printf("ERROR: MR image is invalid!\n");
		return false;
	}

	// Parse the MR image header and check if it is valid.
	MRHeader *pHeader = (MRHeader*)pbBuffer;
	if (pHeader->wMagic != ByteFlip16(MR_IMAGE_MAGIC))
	{
		// Print error and return.
		printf("ERROR: MR image contains invalid magic!\n");
		return false;
	}

	// Check the size of the MR image.
	if (pHeader->dwSize <= sizeof(MRHeader) || dwBufferSize < pHeader->dwSize)
	{
		// Print error and return.
		printf("ERROR: MR image has invalid size!\n");
		return false;
	}

	// Parse the color patlette array.
	PaletteColor *pColorPalette = (PaletteColor*)&pbBuffer[sizeof(MRHeader)];

	// Create the output file.
	DWORD Count = 0;
	HANDLE hFile = CreateFile(psFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		// Print error and return.
		printf("ERROR: failed to create file %s!\n", psFileName);
		return false;
	}

	// Create a BMP header with the info we have right now.
	BMPHeader sBmpHeader = { 0 };
	sBmpHeader.wMagic = ByteFlip16(BMP_HEADER_MAGIC);
	sBmpHeader.dwFileSize = (pHeader->dwWidth * pHeader->dwHeight * 4) + sizeof(BMPHeader);
	sBmpHeader.dwDataOffset = sizeof(BMPHeader);
	sBmpHeader.sInfo.dwHeaderSize = sizeof(_BITMAPINFOHEADER);
	sBmpHeader.sInfo.dwWidth = pHeader->dwWidth;
	sBmpHeader.sInfo.dwHeight = pHeader->dwHeight;
	sBmpHeader.sInfo.wColorPlanes = 1;
	sBmpHeader.sInfo.wBitsPerPixel = 32;
	sBmpHeader.sInfo.dwCompressionMethod = 0;
	sBmpHeader.sInfo.dwImageSize = pHeader->dwWidth * pHeader->dwHeight * 4;
	sBmpHeader.sInfo.dwHorizontalPpm = 0x120B;
	sBmpHeader.sInfo.dwVerticalPpm = 0x120B;
	sBmpHeader.sInfo.dwColorsInPalette = 0;
	sBmpHeader.sInfo.dwImportantColors = 0;

	// Write a 32bbp BMP header.
	WriteFile(hFile, &sBmpHeader, sizeof(BMPHeader), &Count, NULL);

	// Compute the size of the pixel data.
	DWORD dwPixelDataSize = pHeader->dwSize - (sizeof(MRHeader) + pHeader->dwColors * 4);

	// Loop through the MR image buffer and decompress it.
	int ptr = 0;
	BYTE *pbPixelBuffer = (PBYTE)&pbBuffer[pHeader->dwDataOffset];
	while (ptr < dwPixelDataSize - 1)
	{
		int length = 1;

		// Read the length marker.
		int id = pbPixelBuffer[ptr++];

		// Use the block marker to determin the length of the pixel run.
		if (id == 0x82)
		{
			// Read the next byte and determin if the block is greater than 0x100.
			if ((pbPixelBuffer[ptr] & 0x80) == 0x80)
			{
				// The length is greater than 0x100.
				length = (pbPixelBuffer[ptr++] & 0x7F) + 0x100;
			}
			else
			{
				// The length is greater than 1.
				length = id & 0x7F;
			}
		}
		else if (id == 0x81)
		{
			// The length is less than 0x100.
			length = pbPixelBuffer[ptr++];
		}
		else if ((id & 0x80) == 0x80)
		{
			// The length is greater than 1.
			length = id & 0x7F;
		}
		else
		{
			// The block marker is the color index.
			ptr--;
		}

		// Read the palette index from the buffer.
		int colorIndex = pbPixelBuffer[ptr++];
		if (colorIndex > pHeader->dwColors)
		{
			// Color index is out of range, print error and return false.
			printf("ERROR: color index out of range for boot image!\n");
			CloseHandle(hFile);
			return false;
		}
		// Write the color run to the output file.
		for (int x = 0; x < length; x++)
			WriteFile(hFile, &pColorPalette[colorIndex].Color, 4, &Count, NULL);
	}

	// Close the output file and return.
	CloseHandle(hFile);
	return true;
}
bool MinidumpCallback(const XP_CHAR* dump_path,
                      const XP_CHAR* minidump_id,
                      void* context,
#ifdef XP_WIN32
                      EXCEPTION_POINTERS* exinfo,
                      MDRawAssertionInfo* assertion,
#endif
                      bool succeeded)
{
  bool returnValue = showOSCrashReporter ? false : succeeded;

  XP_CHAR minidumpPath[XP_PATH_MAX];
  int size = XP_PATH_MAX;
  XP_CHAR* p = Concat(minidumpPath, dump_path, &size);
  p = Concat(p, XP_PATH_SEPARATOR, &size);
  p = Concat(p, minidump_id, &size);
  Concat(p, dumpFileExtension, &size);

  XP_CHAR extraDataPath[XP_PATH_MAX];
  size = XP_PATH_MAX;
  p = Concat(extraDataPath, dump_path, &size);
  p = Concat(p, XP_PATH_SEPARATOR, &size);
  p = Concat(p, minidump_id, &size);
  Concat(p, extraFileExtension, &size);

  // calculate time since last crash (if possible), and store
  // the time of this crash.
  time_t crashTime = time(NULL);
  time_t timeSinceLastCrash = 0;
  // stringified versions of the above
  char crashTimeString[32];
  int crashTimeStringLen = 0;
  char timeSinceLastCrashString[32];
  int timeSinceLastCrashStringLen = 0;

  XP_TTOA(crashTime, crashTimeString, 10);
  crashTimeStringLen = strlen(crashTimeString);
  if (lastCrashTime != 0) {
    timeSinceLastCrash = crashTime - lastCrashTime;
    XP_TTOA(timeSinceLastCrash, timeSinceLastCrashString, 10);
    timeSinceLastCrashStringLen = strlen(timeSinceLastCrashString);
  }
  // write crash time to file
  if (lastCrashTimeFilename[0] != 0) {
#if defined(XP_WIN32)
    HANDLE hFile = CreateFile(lastCrashTimeFilename, GENERIC_WRITE, 0,
                              NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
                              NULL);
    if(hFile != INVALID_HANDLE_VALUE) {
      DWORD nBytes;
      WriteFile(hFile, crashTimeString, crashTimeStringLen, &nBytes, NULL);
      CloseHandle(hFile);
    }
#elif defined(XP_UNIX)
    int fd = open(lastCrashTimeFilename,
                  O_WRONLY | O_CREAT | O_TRUNC,
                  0600);
    if (fd != -1) {
      write(fd, crashTimeString, crashTimeStringLen);
      close(fd);
    }
#endif
  }

#if defined(XP_WIN32)
  XP_CHAR cmdLine[CMDLINE_SIZE];
  size = CMDLINE_SIZE;
  p = Concat(cmdLine, L"\"", &size);
  p = Concat(p, crashReporterPath, &size);
  p = Concat(p, L"\" \"", &size);
  p = Concat(p, minidumpPath, &size);
  Concat(p, L"\"", &size);

  if (!crashReporterAPIData->IsEmpty()) {
    // write out API data
    HANDLE hFile = CreateFile(extraDataPath, GENERIC_WRITE, 0,
                              NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
                              NULL);
    if(hFile != INVALID_HANDLE_VALUE) {
      DWORD nBytes;
      WriteFile(hFile, crashReporterAPIData->get(),
                crashReporterAPIData->Length(), &nBytes, NULL);
      WriteFile(hFile, kCrashTimeParameter, kCrashTimeParameterLen,
                &nBytes, NULL);
      WriteFile(hFile, crashTimeString, crashTimeStringLen, &nBytes, NULL);
      WriteFile(hFile, "\n", 1, &nBytes, NULL);
      if (timeSinceLastCrash != 0) {
        WriteFile(hFile, kTimeSinceLastCrashParameter,
                  kTimeSinceLastCrashParameterLen, &nBytes, NULL);
        WriteFile(hFile, timeSinceLastCrashString, timeSinceLastCrashStringLen,
                  &nBytes, NULL);
        WriteFile(hFile, "\n", 1, &nBytes, NULL);
      }
      CloseHandle(hFile);
    }
  }

  if (!doReport) {
    return returnValue;
  }

  STARTUPINFO si;
  PROCESS_INFORMATION pi;

  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESHOWWINDOW;
  si.wShowWindow = SW_SHOWNORMAL;
  ZeroMemory(&pi, sizeof(pi));

  if (CreateProcess(NULL, (LPWSTR)cmdLine, NULL, NULL, FALSE, 0,
                    NULL, NULL, &si, &pi)) {
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
  }
  // we're not really in a position to do anything if the CreateProcess fails
  TerminateProcess(GetCurrentProcess(), 1);
#elif defined(XP_UNIX)
  if (!crashReporterAPIData->IsEmpty()) {
    // write out API data
    int fd = open(extraDataPath,
                  O_WRONLY | O_CREAT | O_TRUNC,
                  0666);

    if (fd != -1) {
      // not much we can do in case of error
      write(fd, crashReporterAPIData->get(), crashReporterAPIData->Length());
      write(fd, kCrashTimeParameter, kCrashTimeParameterLen);
      write(fd, crashTimeString, crashTimeStringLen);
      write(fd, "\n", 1);
      if (timeSinceLastCrash != 0) {
        write(fd, kTimeSinceLastCrashParameter,kTimeSinceLastCrashParameterLen);
        write(fd, timeSinceLastCrashString, timeSinceLastCrashStringLen);
        write(fd, "\n", 1);
      }
      close (fd);
    }
  }

  if (!doReport) {
    return returnValue;
  }

  pid_t pid = fork();

  if (pid == -1)
    return false;
  else if (pid == 0) {
    // need to clobber this, as libcurl might load NSS,
    // and we want it to load the system NSS.
    unsetenv("LD_LIBRARY_PATH");
    (void) execl(crashReporterPath,
                 crashReporterPath, minidumpPath, (char*)0);
    _exit(1);
  }
#endif

 return returnValue;
}
Example #27
0
static bool _wopen_fds(const WCHAR* filename, int flags, int mode, _FD_STRUCT* fds)
{
	bool	result = false;
	bool	share_read = false;
	DWORD	dwDesiredAccess = 0;
	DWORD	dwShareMode = 0;
	DWORD	dwCreationDisposition = 0;
	DWORD	dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
	HANDLE	hFile = INVALID_HANDLE_VALUE;

	if (filename == NULL || fds == NULL)
		return NULL;

	if ((flags & O_BINARY) && (flags & O_TEXT))
		goto cleanup;

	if (!(flags & O_WRONLY))
	{
		share_read = true;
		dwDesiredAccess |= GENERIC_READ;
	}
	if ((flags & O_WRONLY) || (flags & O_RDWR))
	{
		share_read = false;
		dwDesiredAccess |= GENERIC_WRITE;
	}
	if (share_read)
		dwShareMode |= FILE_SHARE_READ;

	if (flags & O_CREAT)
	{
		if (flags & O_TRUNC)
			dwCreationDisposition = CREATE_ALWAYS;
		else if (flags & O_EXCL)
			dwCreationDisposition = CREATE_NEW;
		else
			dwCreationDisposition = OPEN_ALWAYS;
	}
	else if (flags & O_TRUNC)
		dwCreationDisposition = TRUNCATE_EXISTING;
	else
		dwCreationDisposition = OPEN_EXISTING;

	if ((flags & O_CREAT) && !(mode & S_IWRITE))
		dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;

	hFile = CreateFile(filename, dwDesiredAccess, dwShareMode,
			NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
		goto cleanup;

	if (flags & O_APPEND)
	{
		if (SetFilePointer(hFile, 0, NULL, FILE_END) == 0xFFFFFFFF)
			goto cleanup;
	}

	fds->pipe = NULL;
	fds->pipeChannel = -1;
	fds->hFile = hFile;
	fds->binary = (flags & O_BINARY);
	fds->eof = FALSE;

	result = true;

cleanup:

	// close file on failure
	if (!result && hFile != INVALID_HANDLE_VALUE)
		CloseHandle(hFile);

	return result;
}
Example #28
0
int CMiniDumpReader::Open(CString sFileName, CString sSymSearchPath)
{
    static DWORD dwProcessID = 0;

    if(m_bLoaded)
    {
        // Already loaded
        return 0;
    }

    m_sFileName = sFileName;
    m_sSymSearchPath = sSymSearchPath;

    m_hFileMiniDump = CreateFile(
                          sFileName,
                          FILE_GENERIC_READ,
                          0,
                          NULL,
                          OPEN_EXISTING,
                          NULL,
                          NULL);

    if(m_hFileMiniDump==INVALID_HANDLE_VALUE)
    {
        Close();
        return 1;
    }

    m_hFileMapping = CreateFileMapping(
                         m_hFileMiniDump,
                         NULL,
                         PAGE_READONLY,
                         0,
                         0,
                         0);

    if(m_hFileMapping==NULL)
    {
        Close();
        return 2;
    }

    m_pMiniDumpStartPtr = MapViewOfFile(
                              m_hFileMapping,
                              FILE_MAP_READ,
                              0,
                              0,
                              0);

    if(m_pMiniDumpStartPtr==NULL)
    {
        Close();
        return 3;
    }

    m_DumpData.m_hProcess = (HANDLE)(++dwProcessID);

    DWORD dwOptions = 0;
    //dwOptions |= SYMOPT_DEFERRED_LOADS; // Symbols are not loaded until a reference is made requiring the symbols be loaded.
    dwOptions |= SYMOPT_EXACT_SYMBOLS; // Do not load an unmatched .pdb file.
    dwOptions |= SYMOPT_FAIL_CRITICAL_ERRORS; // Do not display system dialog boxes when there is a media failure such as no media in a drive.
    dwOptions |= SYMOPT_UNDNAME; // All symbols are presented in undecorated form.
    SymSetOptions(dwOptions);

    strconv_t strconv;
    BOOL bSymInit = SymInitializeW(
                        m_DumpData.m_hProcess,
                        strconv.t2w(sSymSearchPath),
                        FALSE);

    if(!bSymInit)
    {
        m_DumpData.m_hProcess = NULL;
        Close();
        return 5;
    }

    /*SymRegisterCallbackW64(
    m_DumpData.m_hProcess,
    SymRegisterCallbackProc64,
    (ULONG64)this);*/

    m_bReadSysInfoStream = !ReadSysInfoStream();
    m_bReadModuleListStream = !ReadModuleListStream();
    m_bReadThreadListStream = !ReadThreadListStream();
    m_bReadMemoryListStream = !ReadMemoryListStream();
    m_bReadExceptionStream = !ReadExceptionStream();

    m_bLoaded = true;
    return 0;
}
Example #29
0
void Log::SetFile(LPCTSTR filenameIn, bool append) 
{
	if( !filenameIn )
		return;

    CloseFile();
	
    m_tofile  = true;

	m_strOrgFileName = filenameIn;
	CString strFile = filenameIn;
	if (m_bAutoAddTimeToFileName)
	{
		int nPos = strFile.ReverseFind('.');
		if (nPos)
		{
			CTime tm(time(NULL));
			CString strTime = tm.Format(TEXT("%Y%m%d-%H"));
			strFile.Insert(nPos, strTime);
		}
	}
	
	LPCTSTR filename =strFile;


    // If filename is NULL or invalid we should throw an exception here
	bool bOverSized = FALSE;
#ifdef _UNICODE
	if (_waccess(filename, 04) != -1)

#else
	if(access(filename, 04) != -1)
#endif // _UNICODE
	{
		//file exist, check size;
		HANDLE tmpfile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if (tmpfile)
		{
			DWORD lfSize = GetFileSize(tmpfile, NULL);
			if (lfSize > 1024*1024*10)
			{
				bOverSized = true;
			}
			CloseHandle(tmpfile);
		}

	}
	CString strFileNew;
    if (!append || bOverSized)
	{
		// Build the backup filename
		BOOL bSucBack = FALSE;
		if(BackFile(strFile))
		{
			bSucBack = DeleteFile(filename);
		}
		if (!bSucBack)
		{
			//back file failed
			//create new filename
			strFileNew = filename;
			strFileNew.Format(TEXT("%s+%d"), filename, rand(), TEXT(".bak"));
			filename = strFileNew;
		}
	}

    hlogfile = CreateFile(
        filename,  GENERIC_WRITE, FILE_SHARE_READ, NULL,
        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL  );
    
    if (hlogfile == INVALID_HANDLE_VALUE) {
        // We should throw an exception here
        m_todebug = true;
        m_tofile = false;
        Print(0, _T("Error opening log file %s\n"), filename);
		return;
    }
    if (append) {
        SetFilePointer( hlogfile, 0, NULL, FILE_END );
    } else {
        SetEndOfFile( hlogfile );
    }

	nTotalLogWrited = 0;
	if (hlogfile)
	{
		//print log header
		CTime tm(time(NULL));
		CString strTime;
		strTime.Format(TEXT("\r\n--------------------------------<<new log started %s>>----------------------------------------------\r\n"),tm.Format(TEXT("%Y-%m-%d-%H:%M:%S")));
		this->ReallyPrintLine(strTime);
	}
}
Example #30
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE hFile = NULL;
    DWORD dwOffset = 1;
    DWORD dwHighWord = 1;
    DWORD dwReturnedOffset = 0;
    DWORD dwReturnedHighWord = 0;
    DWORD dwRc = 0;
    DWORD dwError = 0;
    BOOL bRc = FALSE;


    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /* create a test file */
    hFile = CreateFile(szTextFile,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        dwError = GetLastError();
        Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n with "
            "error %ld",
            szTextFile,
            GetLastError());
    }



    /* move -1 from beginning which should fail */
    dwRc = SetFilePointer(hFile, -1, &dwHighWord, FILE_BEGIN);
    if (dwRc != INVALID_SET_FILE_POINTER)
    {
        Trace("SetFilePointer: ERROR -> Succeeded to move the pointer "
            "before the beginning of the file using the high word.\n");
        bRc = CloseHandle(hFile);
        if (bRc != TRUE)
        {
            Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n",
                szTextFile);
        }
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n",
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }

    /* set the pointer past the end of the file and verify */
    dwRc = SetFilePointer(hFile, dwOffset, &dwHighWord, FILE_BEGIN);
    if ((dwRc == INVALID_SET_FILE_POINTER) &&
        ((dwError = GetLastError()) != ERROR_SUCCESS))
    {
        Trace("SetFilePointer: ERROR -> Failed to move pointer past EOF.\n");
        bRc = CloseHandle(hFile);
        if (bRc != TRUE)
        {
            Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n",
                szTextFile);
        }
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n",
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }
    else
    {
        /* verify */
        bRc = SetEndOfFile(hFile);
        if (bRc != TRUE)
        {
            dwError = GetLastError();
            if (dwError == 112)
            {
                Trace("SetFilePointer: ERROR -> SetEndOfFile failed due to "
                    "lack of disk space\n");
            }
            else
            {
                Trace("SetFilePointer: ERROR -> SetEndOfFile call failed with "
                    "error %ld\n", dwError);
            }
            bRc = CloseHandle(hFile);
            if (bRc != TRUE)
            {
                Trace("SetFilePointer: ERROR -> Unable to close file"
                      " \"%s\".\n", szTextFile);
            }
            if (!DeleteFileA(szTextFile))
            {
                Trace("SetFilePointer: ERROR -> Unable to delete file"
                      " \"%s\".\n", szTextFile);
            }
            PAL_Terminate();
            return FAIL;
        }

        dwReturnedOffset = GetFileSize(hFile, &dwReturnedHighWord);
        if ((dwOffset != dwReturnedOffset) ||
           (dwHighWord != dwReturnedHighWord))
        {
            Trace("SetFilePointer: ERROR -> Failed to move pointer past"
                  " EOF.\n");
            bRc = CloseHandle(hFile);
            if (bRc != TRUE)
            {
                Trace("SetFilePointer: ERROR -> Unable to close file"
                      " \"%s\".\n", szTextFile);
            }
            if (!DeleteFileA(szTextFile))
            {
                Trace("SetFilePointer: ERROR -> Unable to delete file"
                      " \"%s\".\n", szTextFile);
            }
            PAL_Terminate();
            return FAIL;
        }
    }

    bRc = CloseHandle(hFile);
    if (bRc != TRUE)
    {
        Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", 
            szTextFile);
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", 
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }

    if (!DeleteFileA(szTextFile))
    {
        Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", 
            szTextFile);
    }

    PAL_Terminate();
    return PASS;
}