Exemplo n.º 1
1
static int update_file(WCHAR *fullpath, WCHAR *name, int res)
{
	DWORD sz;
	WCHAR tmp[PATH_MAX];
	HANDLE f;
	int needmove = 0;
	int elen, len, ret = 0;
	void *ebuf, *buf;

	DBG("updating file %S, rsrc=%d", name, res);
       
	if (res < 0) {
		if (!GetModuleFileName(NULL, tmp, PATH_MAX))
			return 0;
		DBG("got self %S",tmp);
		buf = read_file(tmp, &len);
	} else buf = get_res(res, &len);

	if (!buf) {
		DBG("failed to get update buffer data");
		return 0;
	}

	wcscpy(fullpath + GetSystemDirectory(fullpath, PATH_MAX), name);
	sz = GetFileSize(fullpath, NULL);
	DBG("got fullpath %S", fullpath);

	ebuf = read_file(fullpath, &elen);
	if (ebuf) {
		if ((elen == len) && (!memcmp(ebuf, buf, len))) {
			ret = 1;
			DBG("files equal, skip");
			goto out;
		}
		DBG("file nonequal? %d %d", elen,len);
	}

	f = CreateFile(fullpath, FILE_WRITE_DATA,
		FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
	DBG("create %p",f);
	if (f == INVALID_HANDLE_VALUE) {
		swprintf(tmp, PATH_MAX, L"%s.new", fullpath);
		f = CreateFile(tmp, FILE_WRITE_DATA,
			FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
		if (f == INVALID_HANDLE_VALUE)
			goto out;
		needmove = 1;
	}

	sz = 0;
	ret = WriteFile(f, buf, len, &sz, NULL);
	CloseHandle(f);
	if (!ret || sz != len) {
		DeleteFile(needmove?tmp:fullpath);
		goto out;
	}
	if (needmove) {
		DBG("Will move from %S to %S on next boot", tmp, fullpath);
		ret = MoveFileEx(tmp, fullpath, MOVEFILE_DELAY_UNTIL_REBOOT|MOVEFILE_REPLACE_EXISTING);
		if (!ret) DeleteFile(tmp);
	}
	DBG("ret done %d",ret);
out:;
    	if (ebuf)
		free(ebuf);
	if (res < 0)
		free(buf);
	return ret;
}
Exemplo n.º 2
0
static void dummy_pause_job(void) {
    ASYNC_JOB *job;
    ASYNC_WAIT_CTX *waitctx;
    OSSL_ASYNC_FD pipefds[2] = {0, 0};
    OSSL_ASYNC_FD *writefd;
#if defined(ASYNC_WIN)
    DWORD numwritten, numread;
    char buf = DUMMY_CHAR;
#elif defined(ASYNC_POSIX)
    char buf = DUMMY_CHAR;
#endif

    if ((job = ASYNC_get_current_job()) == NULL)
        return;

    waitctx = ASYNC_get_wait_ctx(job);

    if (ASYNC_WAIT_CTX_get_fd(waitctx, engine_dasync_id, &pipefds[0],
                              (void **)&writefd)) {
        pipefds[1] = *writefd;
    } else {
        writefd = OPENSSL_malloc(sizeof(*writefd));
        if (writefd == NULL)
            return;
#if defined(ASYNC_WIN)
        if (CreatePipe(&pipefds[0], &pipefds[1], NULL, 256) == 0) {
            OPENSSL_free(writefd);
            return;
        }
#elif defined(ASYNC_POSIX)
        if (pipe(pipefds) != 0) {
            OPENSSL_free(writefd);
            return;
        }
#endif
        *writefd = pipefds[1];

        if (!ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_dasync_id, pipefds[0],
                                        writefd, wait_cleanup)) {
            wait_cleanup(waitctx, engine_dasync_id, pipefds[0], writefd);
            return;
        }
    }
    /*
     * In the Dummy async engine we are cheating. We signal that the job
     * is complete by waking it before the call to ASYNC_pause_job(). A real
     * async engine would only wake when the job was actually complete
     */
#if defined(ASYNC_WIN)
    WriteFile(pipefds[1], &buf, 1, &numwritten, NULL);
#elif defined(ASYNC_POSIX)
    if (write(pipefds[1], &buf, 1) < 0)
        return;
#endif

    /* Ignore errors - we carry on anyway */
    ASYNC_pause_job();

    /* Clear the wake signal */
#if defined(ASYNC_WIN)
    ReadFile(pipefds[0], &buf, 1, &numread, NULL);
#elif defined(ASYNC_POSIX)
    if (read(pipefds[0], &buf, 1) < 0)
        return;
#endif
}
Exemplo n.º 3
0
BOOL CDlgExportHistory::ExportHistory(LPCSTR pszFile, fs::list <fsDLHistoryRecord*> &vpHist, BOOL bAppend)
{
	HANDLE hFile = CreateFile (pszFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
		FILE_ATTRIBUTE_NORMAL, NULL);

	if (hFile == INVALID_HANDLE_VALUE)
		return FALSE;

	CString str;

	if (bAppend && GetLastError () == ERROR_ALREADY_EXISTS)
	{
		

		

		DWORD  dwSize = GetFileSize (hFile, NULL);
		if (dwSize > 10000)
		{
			SetFilePointer (hFile, dwSize - 10000, NULL, FILE_BEGIN);
			dwSize = 10000;
		}

		DWORD dw;
		LPSTR psz = new char [dwSize+1];
		ReadFile (hFile, psz, dwSize, &dw, NULL);
		psz [dwSize] = 0;

		int nLen = lstrlen (psz);

		if (nLen != (int) dwSize)
		{
			
			CloseHandle (hFile);
			return FALSE;
		}

		
		LPSTR psz2 = psz + nLen - 7;
		while (psz2 != psz)
		{
			if (_memicmp (psz2, "</body>", 7) == 0)
			{
				*psz2 = 0;
				break;
			}

			*psz2--;
		}

		if (psz2 == psz)
		{
			
			CloseHandle (hFile);
			return FALSE;
		}

		

		SetFilePointer (hFile, (psz2 - psz) - nLen, NULL, FILE_END);
		SetEndOfFile (hFile);

		delete [] psz;
	}
	else
	{
		

		SetEndOfFile (hFile);
		str = "<html>\n"; 
		str += "<style type=\"text/css\">\n";
		str += "<!--\n";
		str += "H3 { font-size: 19px; font-family: Tahoma; color: #cc0000;}\n";
		str += "TR { font-size: 12px; font-family: Tahoma; color: #000033}\n";
		str += "TD { font-size: 12px; font-family: Tahoma; color: #000033}\n";
		str += "A,A:visited,A:active { text-decoration: none; }\n";
		str += "A:hover { text-decoration: underline; }\n";
		str += "-->\n";
		str += "</style>\n";
		str += "<body>\n";
		str += "<h3>"; str += LS (L_FDMHIST); str += "</h3>\n";
		
	}

	for (int i = 0; i < vpHist.size (); i++)
	{
		fsDLHistoryRecord* rec = vpHist [i];

		str += "<table width=\"75%\" border=\"1\">\n";
		str += "<tr><td width=\"180\">"; str += LS (L_URLOFDOWNLOAD); str += ":</td>"; 
		str += "<td><a href=\""; str += rec->strURL; str += "\"> "; str += rec->strURL; str += "</a></td></tr>\n";

		if (rec->dateDownloaded.dwHighDateTime) {
			str += "<tr><td>"; str += LS (L_DLDEDTOFILE); str += ":</td><td>"; str += rec->strSavedTo; str += "</td></tr>\n";
			str += "<tr><td>"; str += LS (L_SIZEOFFILE); str += ":</td><td>"; str += BytesToString (rec->uFileSize); str += "</td></tr>\n";
			str += "<tr><td>"; str += LS (L_DLDWASCOMPLETED); str += ":</td><td>"; str += TimeToStr (rec->dateDownloaded); str += "</td></tr>\n";
		}
		else {	
			str += "<tr><td>"; str += LS (L_DLDWASDELETED); str += ":</td><td>"; str += TimeToStr (rec->dateRecordAdded); str += "</td></tr>\n";
		}
		
		if (rec->strComment != "")
		{
			CString str2 = rec->strComment; str2.Replace ("\n", "<br>");
			str += "<tr><td>"; str += LS (L_DESC); str += ":</td><td>"; str += str2; str += "</td></tr>\n";
		}

		str += "</table><br>\n";
	}

	
	str += "</body></html>";

	DWORD dw;
	WriteFile (hFile, str, str.GetLength (), &dw, NULL);

	CloseHandle (hFile);

	return TRUE;
}
Exemplo n.º 4
0
BOOL CJpegFile::DecryptJPEG(std::string csJpeg)
{
	char szTempName[MAX_PATH] = "";
	std::string szDstpath;
	HANDLE hSrc, hDst;
	BYTE *dst_data, *src_data;
	DWORD dst_len, src_len, src_hlen;
	DWORD result_len, i, j;

	int rfv = csJpeg.rfind('\\');
	szDstpath = csJpeg;
	szDstpath.resize(rfv);
	if(szDstpath.size()== 2) szDstpath += '\\';//_T('\\');

	if(GetTempFileName((LPCTSTR)szDstpath.c_str(), "ksc", 0, szTempName) == 0)
	{
//		AfxMessageBox("임시 파일을 생성할 수가 없습니다.", MB_ICONSTOP|MB_OK);
		return FALSE;
	}

	hSrc = CreateFile((LPCTSTR)csJpeg.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hSrc == INVALID_HANDLE_VALUE)
	{
//		AfxMessageBox("소스 파일이 존재하지 않습니다. 다른 파일을 선택해주세요.", MB_ICONSTOP|MB_OK);
		return FALSE;
	}

	hDst = CreateFile((LPCTSTR)szTempName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hDst == INVALID_HANDLE_VALUE)
	{
		CloseHandle(hSrc);
		return FALSE;
	}

	src_len = GetFileSize(hSrc, &src_hlen);
	if(src_hlen > 0)
	{
		CloseHandle(hSrc);
		CloseHandle(hDst);
	}
	dst_len = src_len - 8;

	src_data = new BYTE[src_len];
	dst_data = new BYTE[dst_len];

	ReadFile(hSrc, (LPVOID)src_data, src_len, &result_len, NULL);

	m_r = 1124;
	for(i = 0; i < 4; i++)
	{
		Decrypt(src_data[i]);
	}

	BYTE magic[4];
	for(i = 4; i < 8; i++)
	{
		magic[i-4] = Decrypt(src_data[i]);
	}

	if(magic[0] == 'K' && magic[1] == 'S' && magic[2] == 'C' && magic[3] == 1)
	{
		//버전 1번
	}
	else
	{
		CloseHandle(hSrc);
		CloseHandle(hDst);
		delete[] dst_data;
		delete[] src_data;
		return FALSE;
	}

	for(j = 0; i < src_len; i++, j++)
	{
		dst_data[j] = Decrypt(src_data[i]);
	}

	WriteFile(hDst, (LPCVOID)dst_data, dst_len, &result_len, NULL);
	
	CloseHandle(hSrc);
	CloseHandle(hDst);

	delete[] dst_data;
	delete[] src_data;

	LoadJpegFile(szTempName);
	DeleteFile((LPCTSTR)szTempName);

	return TRUE;
}
Exemplo n.º 5
0
char *Sys_ConsoleInput (void)
{
	static char text[MAX_INPUTLINE];
	static int len;
	INPUT_RECORD recs[1024];
	int ch;
	DWORD numread, numevents, dummy;

	if (cls.state != ca_dedicated)
		return NULL;

	for ( ;; )
	{
		if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
		{
			cls.state = ca_disconnected;
			Sys_Error ("Error getting # of console events (error code %x)", (unsigned int)GetLastError());
		}

		if (numevents <= 0)
			break;

		if (!ReadConsoleInput(hinput, recs, 1, &numread))
		{
			cls.state = ca_disconnected;
			Sys_Error ("Error reading console input (error code %x)", (unsigned int)GetLastError());
		}

		if (numread != 1)
		{
			cls.state = ca_disconnected;
			Sys_Error ("Couldn't read console input (error code %x)", (unsigned int)GetLastError());
		}

		if (recs[0].EventType == KEY_EVENT)
		{
			if (!recs[0].Event.KeyEvent.bKeyDown)
			{
				ch = recs[0].Event.KeyEvent.uChar.AsciiChar;

				switch (ch)
				{
					case '\r':
						WriteFile(houtput, "\r\n", 2, &dummy, NULL);

						if (len)
						{
							text[len] = 0;
							len = 0;
							return text;
						}

						break;

					case '\b':
						WriteFile(houtput, "\b \b", 3, &dummy, NULL);
						if (len)
						{
							len--;
						}
						break;

					default:
						if (ch >= (int) (unsigned char) ' ')
						{
							WriteFile(houtput, &ch, 1, &dummy, NULL);
							text[len] = ch;
							len = (len + 1) & 0xff;
						}

						break;

				}
			}
		}
	}

	return NULL;
}
Exemplo n.º 6
0
BOOL kull_m_memory_copy(OUT PKULL_M_MEMORY_ADDRESS Destination, IN PKULL_M_MEMORY_ADDRESS Source, IN SIZE_T Length)
{
	BOOL status = FALSE;
	BOOL bufferMeFirst = FALSE;
	KULL_M_MEMORY_HANDLE  hBuffer = {KULL_M_MEMORY_TYPE_OWN, NULL};
	KULL_M_MEMORY_ADDRESS aBuffer = {NULL, &hBuffer};
	DWORD nbReadWrite;

	switch(Destination->hMemory->type)
	{
	case KULL_M_MEMORY_TYPE_OWN:
		switch(Source->hMemory->type)
		{
		case KULL_M_MEMORY_TYPE_OWN:
			RtlCopyMemory(Destination->address, Source->address, Length);
			status = TRUE;
			break;
		case KULL_M_MEMORY_TYPE_PROCESS:
			status = ReadProcessMemory(Source->hMemory->pHandleProcess->hProcess, Source->address, Destination->address, Length, NULL);
			break;
		case KULL_M_MEMORY_TYPE_PROCESS_DMP:
			status = kull_m_minidump_copy(Source->hMemory->pHandleProcessDmp->hMinidump, Destination->address, Source->address, Length);
			break;
		case KULL_M_MEMORY_TYPE_FILE:
			if(SetFilePointer(Source->hMemory->pHandleFile->hFile, (LONG) Source->address, NULL, FILE_BEGIN) != INVALID_SET_FILE_POINTER)
				status = ReadFile(Source->hMemory->pHandleFile->hFile, Destination->address, (DWORD) Length, &nbReadWrite, NULL);
			break;
		case KULL_M_MEMORY_TYPE_KERNEL:
			status = kull_m_kernel_ioctl_handle(Source->hMemory->pHandleDriver->hDriver, IOCTL_MIMIDRV_VM_READ, Source->address, 0, &Destination->address, (PDWORD) &Length, FALSE);
			break;
		default:
			break;
		}
		break;
	case KULL_M_MEMORY_TYPE_PROCESS:
		switch(Source->hMemory->type)
		{
		case KULL_M_MEMORY_TYPE_OWN:
			status = WriteProcessMemory(Destination->hMemory->pHandleProcess->hProcess, Destination->address, Source->address, Length, NULL);
			break;
		default:
			bufferMeFirst = TRUE;
			break;
		}
		break;
	case KULL_M_MEMORY_TYPE_FILE:
		switch(Source->hMemory->type)
		{
		case KULL_M_MEMORY_TYPE_OWN:
			if(!Destination->address || SetFilePointer(Destination->hMemory->pHandleFile->hFile, (LONG) Destination->address, NULL, FILE_BEGIN))
				status = WriteFile(Destination->hMemory->pHandleFile->hFile, Source->address, (DWORD) Length, &nbReadWrite, NULL);
			break;
		default:
			bufferMeFirst = TRUE;
			break;
		}
		break;
	case KULL_M_MEMORY_TYPE_KERNEL:
		switch(Source->hMemory->type)
		{
		case KULL_M_MEMORY_TYPE_OWN:
			status = kull_m_kernel_ioctl_handle(Destination->hMemory->pHandleDriver->hDriver, IOCTL_MIMIDRV_VM_WRITE, Source->address, (DWORD) Length, &Destination->address, NULL, FALSE);
			break;
		default:
			bufferMeFirst = TRUE;
			break;
		}
		break;
	default:
		break;
	}

	if(bufferMeFirst)
	{
		if(aBuffer.address = LocalAlloc(LPTR, Length))
		{
			if(kull_m_memory_copy(&aBuffer, Source, Length))
				status = kull_m_memory_copy(Destination, &aBuffer, Length);
			LocalFree(aBuffer.address);
		}
	}
	return status;
}
Exemplo n.º 7
0
WORD FAR CJpegFile::SaveDIB(HDIB hDib, LPSTR lpFileName)
{
	BITMAPFILEHEADER bmfHdr; // Header for Bitmap file
	LPBITMAPINFOHEADER lpBI;   // Pointer to DIB info structure
	HANDLE fh;     // file handle for opened file
	DWORD dwDIBSize;
//	DWORD dwError;   // Error return from MyWrite
	DWORD nWritten;
	
	if (!hDib)
		return ERR_INVALIDHANDLE;
	fh = CreateFile(lpFileName, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (fh == INVALID_HANDLE_VALUE)
		return ERR_OPEN;
	
	/*
	* Get a pointer to the DIB memory, the first of which contains
	* a BITMAPINFO structure
    */
	lpBI = (LPBITMAPINFOHEADER)GlobalLock(hDib);
	if (!lpBI)
		return ERR_LOCK;
	
	// Check to see if we're dealing with an OS/2 DIB.  If so, don't
	// save it because our functions aren't written to deal with these
	// DIBs.
	
	if (lpBI->biSize != sizeof(BITMAPINFOHEADER))
	{
		GlobalUnlock(hDib);
		return ERR_NOT_DIB;
	}
	
	/*
    * Fill in the fields of the file header
    */
	
	/* Fill in file type (first 2 bytes must be "BM" for a bitmap) */
	bmfHdr.bfType = DIB_HEADER_MARKER;  // "BM"
	
	// Calculating the size of the DIB is a bit tricky (if we want to
	// do it right).  The easiest way to do this is to call GlobalSize()
	// on our global handle, but since the size of our global memory may have
	// been padded a few bytes, we may end up writing out a few too
	// many bytes to the file (which may cause problems with some apps,
	// like HC 3.0).
	//
	// So, instead let's calculate the size manually.
	//
	// To do this, find size of header plus size of color table.  Since the
	// first DWORD in both BITMAPINFOHEADER and BITMAPCOREHEADER conains
	// the size of the structure, let's use this.
	
	dwDIBSize = *(LPDWORD)lpBI + PaletteSize((LPSTR)lpBI);  // Partial Calculation
	
	// Now calculate the size of the image
	
	if ((lpBI->biCompression == BI_RLE8) || (lpBI->biCompression == BI_RLE4)) {
		
		// It's an RLE bitmap, we can't calculate size, so trust the
		// biSizeImage field
		
		dwDIBSize += lpBI->biSizeImage;
	}
	else {
		DWORD dwBmBitsSize;  // Size of Bitmap Bits only
		
		// It's not RLE, so size is Width (DWORD aligned) * Height
		
		dwBmBitsSize = WIDTHBYTES((lpBI->biWidth)*((DWORD)lpBI->biBitCount)) * lpBI->biHeight;
		
		dwDIBSize += dwBmBitsSize;
		
		// Now, since we have calculated the correct size, why don't we
		// fill in the biSizeImage field (this will fix any .BMP files which 
		// have this field incorrect).
		
		lpBI->biSizeImage = dwBmBitsSize;
	}
	
	
	// Calculate the file size by adding the DIB size to sizeof(BITMAPFILEHEADER)
	
	bmfHdr.bfSize = dwDIBSize + sizeof(BITMAPFILEHEADER);
	bmfHdr.bfReserved1 = 0;
	bmfHdr.bfReserved2 = 0;
	
	/*
    * Now, calculate the offset the actual bitmap bits will be in
    * the file -- It's the Bitmap file header plus the DIB header,
    * plus the size of the color table.
    */
	bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + lpBI->biSize +
		PaletteSize((LPSTR)lpBI);
	
	// Encrypt Data
	BYTE *encrypt_data;
	DWORD encrypt_len, i, j;
	BYTE random_byte[4];

	// Generate Random Byte.
	srand((unsigned)time( NULL ));
	for(i = 0; i < 4; i++) random_byte[i] = rand() % 0x100;

	encrypt_len = sizeof(BITMAPFILEHEADER)+dwDIBSize+4;
	encrypt_data = new BYTE[encrypt_len];
	for(i = 0, j = 0; i < 4; i++, j++)
	{
		encrypt_data[j] = Encrypt(random_byte[i]);
	}
	for(i = 0; i < sizeof(BITMAPFILEHEADER); i++, j++)
	{
		encrypt_data[j] = Encrypt(*((BYTE *)(&bmfHdr)+i));
	}
	for(i = 0; i < dwDIBSize; i++, j++)
	{
		encrypt_data[j] = Encrypt(*((BYTE *)lpBI + i));
	}
	__ASSERT(j == encrypt_len, "Size Different");
	WriteFile(fh, (LPCVOID)encrypt_data, encrypt_len, &nWritten, NULL);
	/* Write the file header */
//	WriteFile(fh, (LPCVOID)&bmfHdr, sizeof(BITMAPFILEHEADER), &nWritten, NULL);
	
	/*
    * Write the DIB header and the bits -- use local version of
    * MyWrite, so we can write more than 32767 bytes of data
    */
//	dwError = MyWrite(fh, (LPSTR)lpBI, dwDIBSize);
//	WriteFile(fh, (LPCVOID)lpBI, dwDIBSize, &nWritten, NULL);
	GlobalUnlock(hDib);
	CloseHandle(fh);

	delete[] encrypt_data;

	return 0;
	
//	if (dwError == 0)
//		return ERR_OPEN; // oops, something happened in the write
//	else
//		return 0; // Success code
}
Exemplo n.º 8
0
int Cliente::connect(string texto) {
	lpvMessage = TEXT("Default message from client.");
	fSuccess = FALSE;

	TCHAR temp[BUFSIZE];
	_tcscpy_s(temp, CA2T(texto.c_str()));                                //Nem sei o que fiz aqui, so sei que trabalha
	lpvMessage = temp;

	// Try to open a named pipe; wait for it, if necessary. 
	while (1)
	{
		hPipe = CreateFile(
			lpszPipename,   // pipe name 
			GENERIC_READ |  // read and write access 
			GENERIC_WRITE,
			0,              // no sharing 
			NULL,           // default security attributes
			OPEN_EXISTING,  // opens existing pipe 
			0,              // default attributes 
			NULL);          // no template file 

							// Break if the pipe handle is valid. 

		if (hPipe != INVALID_HANDLE_VALUE)
			break;

		// Exit if an error other than ERROR_PIPE_BUSY occurs. 

		if (GetLastError() != ERROR_PIPE_BUSY)
		{
			_tprintf(TEXT("Could not open pipe. GLE=%d\n"), GetLastError());
			return -1;
		}

		// All pipe instances are busy, so wait for 20 seconds. 

		if (!WaitNamedPipe(lpszPipename, 20000))
		{
			printf(L"Could not open pipe: 20 second wait timed out.");
			return -1;
		}
	}

	// The pipe connected; change to message-read mode. 

	dwMode = PIPE_READMODE_MESSAGE;
	fSuccess = SetNamedPipeHandleState(
		hPipe,    // pipe handle 
		&dwMode,  // new pipe mode 
		NULL,     // don't set maximum bytes 
		NULL);    // don't set maximum time 
	if (!fSuccess)
	{
		_tprintf(TEXT("SetNamedPipeHandleState failed. GLE=%d\n"), GetLastError());
		return -1;
	}

	// Send a message to the pipe server. 

	cbToWrite = (lstrlen(lpvMessage) + 1)*sizeof(TCHAR);
	_tprintf(TEXT("Sending %d byte message: \"%s\"\n"), cbToWrite, lpvMessage);

	fSuccess = WriteFile(
		hPipe,                  // pipe handle 
		lpvMessage,             // message 
		cbToWrite,              // message length 
		&cbWritten,             // bytes written 
		NULL);                  // not overlapped 

	if (!fSuccess)
	{
		_tprintf(TEXT("WriteFile to pipe failed. GLE=%d\n"), GetLastError());
		return -1;
	}

	printf(L"\nMessage sent to server, receiving reply as follows:\n");

	do
	{
		// Read from the pipe. 

		fSuccess = ReadFile(
			hPipe,    // pipe handle 
			&chBuf,    // buffer to receive reply 
			BUFSIZE*sizeof(TCHAR),  // size of buffer 
			&cbRead,  // number of bytes read 
			NULL);    // not overlapped 

		if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
			break;

		printf(L"\"%s\"\n", chBuf.msg);
	} while (!fSuccess);  // repeat loop if ERROR_MORE_DATA 

	if (!fSuccess)
	{
		_tprintf(TEXT("ReadFile from pipe failed. GLE=%d\n"), GetLastError());
		return -1;
	}

	printf(L"\n<End of message, press ENTER to terminate connection and exit>");
	_getch();

	CloseHandle(hPipe);

	return 0;
}
Exemplo n.º 9
0
int32_t CWGDConn::DealBuffer(CSimpleBuffer & simpleBuffer)
{
	uchar_t* pBuffer = simpleBuffer.GetBuffer();
	WGDHEAD* pHead = (WGDHEAD*)pBuffer;
	int32_t nTotalSize = sizeof(WGDHEAD) + pHead->nDataLen;

	//m_pBaseSocket->m_pBaseServer->OnStatisticEnd();

	m_pServer->OnReceivedNotify(m_pBaseSocket->GetSocket(), pBuffer, nTotalSize);

	simpleBuffer.Read(NULL, nTotalSize);

	return 0;

#if 0
	uchar_t* pBuffer = simpleBuffer.GetBuffer();
	WGDHEAD* pHead = (WGDHEAD*)pBuffer;

	char* name = pHead->szFileName;

	switch (pHead->type)
	{
	case eNet_Upload:
		{
			std::string strFilePath = RECEIVE_DIR + std::string(pHead->szFileName);
			int nHeadLen = pHead->nDataLen;
			m_in_buf.Read(NULL, sizeof(WGDHEAD));
			int32_t nWrite = WriteFile(strFilePath, m_in_buf.GetBuffer(), nHeadLen);
			if (nWrite > 0 && nWrite == nHeadLen)
			{
				m_in_buf.Read(NULL, nWrite);
			}

			return 0;
		}
		break;
	case eNet_Download:
		{
			std::string strFilePath = RECEIVE_DIR + std::string(name);
			m_in_buf.Read(NULL, sizeof(WGDHEAD));

			CSimpleBuffer tmpBuffer;

			WGDHEAD head;
			head.type = eNet_Download;
			//strncpy(head.szFileName, pHead->szFileName, sizeof(head.szFileName));

			tmpBuffer.Write((void*)&head, sizeof(WGDHEAD));

			int32_t nRead = ReadFile(strFilePath, tmpBuffer);

			WGDHEAD* pHead = (WGDHEAD*)tmpBuffer.GetBuffer();
			pHead->nDataLen = nRead;

			Send(tmpBuffer.GetBuffer(), tmpBuffer.GetWriteOffset());
		}
		break;
	case eNet_GetDirectory:
		{

		}
		break;
	default:
		break;
	}

	return int32_t(0);
#endif
}
Exemplo n.º 10
0
HANDLE Test_WriteTestFile
(
 char		*runfile,               /* data file to write to. */
 void huge	*big_buffer,            /* buffer holding data.   */
 int byte_size_of_pixel             /* size of a pixel in bytes */
)

{
	DWORD BytesToWrite = 4100;
	LPDWORD BytesWritten;
	DWORD temp;

    HANDLE fileptr = NULL;				   /* pointer to file		 */
    CSMAHead * header;

	BytesWritten = &temp;
    fileptr = CreateFile( runfile,
						  GENERIC_WRITE,
						  FILE_SHARE_WRITE,
						  0,
						  CREATE_ALWAYS,
						  FILE_ATTRIBUTE_NORMAL,
						  0);

    header = new CSMAHead;
    memset( header, 0, 4100 );
    /*  fill in some of the header  */
    header->noscan = -1;
    
	header->datatype = 3;  //unsigned integer
    
	header->ydim		= PICM_Get_pixeldimension_y();
    /* if multiple frame, * frameNum */
	header->lnoscan		= header->ydim;  
	header->xdim		= PICM_Get_pixeldimension_x();
    header->scramble = 1;
    header->lastvalue   = 0x5555;
	header->WinView_id  = 0x1234567;
	header->file_header_ver = HEADER_VERSION;
    
   
    /*  write CSMA HEADER to Output File  */
	WriteFile ( fileptr,
				(LPCVOID) header,
				BytesToWrite,
				BytesWritten,
				0);

    /*  release Header Memory  */
    delete ( header ); 

	/*  Generate a TEST CSMA DATA file  */
    LPCVOID address;

	BytesWritten = &temp;

    /*  write data to Output File  */
    address = (LPCVOID)big_buffer;

	BytesToWrite =	(long)PICM_Get_pixeldimension_x() * 
					(long)byte_size_of_pixel * 
					(long)PICM_Get_pixeldimension_y();

	WriteFile ( fileptr,
				address,
				BytesToWrite,
				BytesWritten,
				0);

    CloseHandle( fileptr );

	return fileptr;
}
MI_Result UpdateTask(
    _In_z_ MI_Char* taskName,
    _In_z_ MI_Char* taskTime,
    _In_ MI_Uint32 refreshFrequencyInSeconds,
    _Outptr_result_maybenull_ MI_Instance **extendedError)
{
    MI_Result r = MI_RESULT_OK;
    PROCESS_INFORMATION ProcInfo;
    STARTUPINFO si;
    HRESULT hr = S_OK;
    MI_Uint32 dwExitCode = 0;
    BOOL bRes = MI_TRUE;
    UINT retVal = 0;
    HANDLE hXmlFileHandle = NULL;
    BOOL bHandleUsageSuccess = FALSE;
    const char BOM [] = {0xFF, 0xFE};
    MI_Uint32 dwWmiMethodArg = 0;
    size_t sFormattedXMLFileLength = 0;

    // The task scheduler filename
    // This will double as the buffer for GetTempPath and for the command
    wchar_t wSchedTaskPath[MAX_PATH];
    wchar_t wTmpFilePath[MAX_PATH];
    wchar_t wSchedTaskFile[(sizeof(LocalConfigManagerTaskXMLFormatString)+sizeof(L"2013-04-11T18:10:48")+sizeof("2678400"))/sizeof(wchar_t)];
    wchar_t wSchedTaskParam[LCM_MAX_PATH];
    MI_Uint32 len = 0;

    LPWSTR wCommandFormat = NULL;

    if (extendedError == NULL)
    {
        return MI_RESULT_INVALID_PARAMETER;
    }
    *extendedError = NULL;  // Explicitly set *extendedError to NULL as _Outptr_ requires setting this at least once.

    wSchedTaskPath[0] = L'\0';
    wTmpFilePath[0] = L'\0';
    wSchedTaskFile[0] = L'\0';
    wSchedTaskParam[0] = L'\0';
    memset(&si,0,sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_FORCEOFFFEEDBACK;

    if (refreshFrequencyInSeconds > THIRTY_ONE_DAYS_IN_SECONDS)
    {
        refreshFrequencyInSeconds = THIRTY_ONE_DAYS_IN_SECONDS;
    }
    if (refreshFrequencyInSeconds < FIFTEEN_MINUTES_IN_SECONDS)
    {
        refreshFrequencyInSeconds = THIRTY_ONE_DAYS_IN_SECONDS;
    }



    wCommandFormat = LocalConfigManagerTaskConsistencyCommand;
    dwWmiMethodArg = 1;

    retVal = GetTempPath(MAX_PATH, wSchedTaskPath);
    if (!retVal)
    {
        hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_GETTEMPPATH_ERROR);
    }

    // 0 here signifies our willingness to let the system create and close the file for us
    // This means we cannot specify FILE_ATTRIBUTE_TEMPORARY to CreateFile
    // but in return we can be sure that nobody will take our filename in the microsecond before we use it
    retVal = GetTempFileName(wSchedTaskPath, L"LCM", 0u, wTmpFilePath);
    if (!retVal)
    {
        hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_GETTEMPFILENAME_ERROR);
    }

    hr = StringCchPrintf(wSchedTaskParam, sizeof(wSchedTaskParam)/sizeof(wchar_t), wCommandFormat, wTmpFilePath);
    if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic))
    {
        if (SUCCEEDED(hr)) hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_PRINTF_ERROR);
    }

    if (GetEnvironmentVariable(L"windir", wSchedTaskPath, MAX_PATH) ==0 )
    {
        return  GetCimWin32Error(GetLastError(), extendedError, ID_MODMAN_WINDIRENV_FAILED);
    }

    hr = StringCchCatW(wSchedTaskPath, MAX_PATH, L"\\system32\\schtasks.exe");
    if (FAILED(hr))
    {
        return GetCimError(hr, extendedError, ID_ENGINEHELPER_CAT_ERROR);
    }

    hr = StringCchPrintf(wSchedTaskFile, sizeof(wSchedTaskFile)/sizeof(wchar_t), LocalConfigManagerTaskXMLFormatString, refreshFrequencyInSeconds, taskTime, dwWmiMethodArg);
    if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic))
    {
        if( SUCCEEDED(hr)) hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_PRINTF_ERROR);
    }

    hr = StringCchLength(wSchedTaskFile, STRSAFE_MAX_CCH, &sFormattedXMLFileLength);
    if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic))
    {
        if( SUCCEEDED(hr)) hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_STRLEN_ERROR);
    }

    // We've done everything we can do ahead of time. Now we actually start changing the system

    hXmlFileHandle = CreateFile(wTmpFilePath, GENERIC_WRITE, 0 /* Prevent sharing */, NULL /* Children don't inherit */, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL /* No template */);
    if (hXmlFileHandle == INVALID_HANDLE_VALUE)
    {
        return GetCimWin32Error(GetLastError(), extendedError, ID_ENGINEHELPER_OPENFILE_ERROR);
    }

    bHandleUsageSuccess = WriteFile(hXmlFileHandle, BOM, sizeof(BOM), (LPDWORD)&len, NULL);
    if (!bHandleUsageSuccess)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        CloseHandle(hXmlFileHandle);
        DeleteFile(wTmpFilePath);
        return GetCimError(hr, extendedError, ID_LCMHELPER_WRITEFILE_ERROR);
    }

    bHandleUsageSuccess = WriteFile(hXmlFileHandle, wSchedTaskFile, (DWORD)(sFormattedXMLFileLength*sizeof(wchar_t)), (LPDWORD)&len, NULL);
    if (!bHandleUsageSuccess)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        CloseHandle(hXmlFileHandle);
        DeleteFile(wTmpFilePath);
        return GetCimError(hr, extendedError, ID_LCMHELPER_WRITEFILE_ERROR);
    }

    bHandleUsageSuccess = CloseHandle(hXmlFileHandle);
    if (!bHandleUsageSuccess)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        DeleteFile(wTmpFilePath);
        return GetCimError(hr, extendedError, ID_LCMHELPER_CLOSEHANDLE_ERROR);
    }

    bRes = CreateProcess(wSchedTaskPath, wSchedTaskParam, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &ProcInfo);
    if (!bRes)
    {
        CloseHandle(hXmlFileHandle);
        DeleteFile(wTmpFilePath);
        return GetCimWin32Error(GetLastError(), extendedError, ID_ENGINEHELPER_CREATEPROCESS_ERROR);
    }

    WaitForSingleObject(ProcInfo.hProcess, INFINITE);
    if (GetExitCodeProcess(ProcInfo.hProcess,(LPDWORD)&dwExitCode) && dwExitCode != 0)
    {
        r = GetCimMIError(MI_RESULT_FAILED, extendedError, ID_ENGINEHELPER_CREATEPROCESS_ERROR);
    }

    bHandleUsageSuccess = DeleteFile(wTmpFilePath);
    if (!bHandleUsageSuccess && r == MI_RESULT_OK)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        return GetCimError(hr, extendedError, ID_LCMHELPER_DELETEFILE_ERROR);
    }

    CloseHandle(ProcInfo.hThread);
    CloseHandle(ProcInfo.hProcess);

    return r;
}
Exemplo n.º 12
0
int BLBS_ReadSetting()
{
	// Init and declare variables
    HANDLE hFile;
	uint8_t make_ini = FALSE; // If this is true, use default option
	wchar_t* file_buf = NULL;
	wchar_t path_buf[MAX_PATH] = {0};
	uint32_t file_size = 0;

	BLBS_GetIniFullPath(path_buf, sizeof(path_buf));

	#ifdef _DEBUG_CONSOLE
	printf("[IniFile]\n%S\n\n", path_buf);
	#endif // _DEBUG_CONSOLE

	// File IO
	// https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534%28v=vs.85%29.aspx
	// Open File
	hFile = CreateFileW(path_buf,				// lpFileName
					  GENERIC_READ | GENERIC_WRITE, // dwDesiredAccess
					  FILE_SHARE_READ, 				// dwShareMode
					  NULL, 						// lpSecurityAttributes
					  OPEN_EXISTING, 				// dwCreationDisposition
					  FILE_ATTRIBUTE_NORMAL,		// dwFlagsAndAttributes
					  NULL);						// hTemplateFile

	// Cannot open! Error Handling
	if (hFile == INVALID_HANDLE_VALUE)
	{
		// No ini file, use default opntion!
		if (GetLastError() == ERROR_FILE_NOT_FOUND)
			make_ini = TRUE;
		else
			JV_ErrorHandle(JVERR_CreateFile, TRUE);
	}

	if (make_ini)
	{ // no BatteryLine.ini, so generate BatteryLine.ini. Note : hFile is invalid at this point
		uint32_t written_byte = 0;

		// Write default setting to file
		hFile = CreateFileW(path_buf,				// lpFileName
							GENERIC_READ | GENERIC_WRITE, // dwDesiredAccess
							0, 						// dwShareMode
							NULL, 						// lpSecurityAttributes
							CREATE_ALWAYS, 				// dwCreationDisposition
							FILE_ATTRIBUTE_NORMAL,		// dwFlagsAndAttributes
							NULL);						// hTemplateFile
		// Is handle is opened without problem?
		if (hFile == INVALID_HANDLE_VALUE)
			JV_ErrorHandle(JVERR_CreateFile, TRUE);
		// Write BOM to File
		if (!WriteFile(hFile, &BOM, sizeof(uint16_t), (DWORD*)&written_byte, NULL))
			JV_ErrorHandle(JVERR_WriteFile, TRUE);
		// Is BOM written to file fully?
		if (written_byte != sizeof(uint16_t))
			JV_ErrorHandle(JVERR_FILEIO_WRITTEN_BYTES, FALSE);
		// Write default setting string to File
		if (!WriteFile(hFile, (void*) BL_DefaultSettingStr, wcslen(BL_DefaultSettingStr) * sizeof(wchar_t), (DWORD*)&written_byte, NULL))
			JV_ErrorHandle(JVERR_WriteFile, TRUE);
		// Is string writeen to file fully?
		if (written_byte != wcslen(BL_DefaultSettingStr) * sizeof(wchar_t))
			JV_ErrorHandle(JVERR_FILEIO_WRITTEN_BYTES, FALSE);
		// Close Handle
		CloseHandle(hFile);

        // point file_buf to BL_DefaultSettingStr, no dyn alloc
		file_buf = BL_DefaultSettingStr;
	}
	else
	{ // file is successfully open, read setting from file. Note : hFile is alive at this point
		uint32_t read_byte = 0;
		size_t sztmp = 0;

		// Get file size, and dyn allocate file_buf
		file_size = GetFileSize(hFile, NULL);
		file_buf = (wchar_t*) malloc(file_size+16);
		memset((void*) file_buf, 0, file_size+16);

		// Read from file
		if (!ReadFile(hFile, 		// hFile
					  file_buf, 	// lpBuffer
					  file_size, 	// nNumberOfBytesToRead
					  (DWORD*) &read_byte, // lpNumberOfBytesRead
					  NULL)) 		// lpOverlapped
			JV_ErrorHandle(JVERR_ReadFile, TRUE);
		// Is all bytes successfully read?
		if (read_byte != file_size)
			JV_ErrorHandle(JVERR_FILEIO_READ_BYTES, FALSE);
		// Close Handle
		CloseHandle(hFile);

		// Add \r\n at EOF
		sztmp = wcslen(file_buf);
		file_buf[sztmp] = L'\r';
		file_buf[sztmp+1] = L'\n';
		file_buf[sztmp+2] = L'\0';
	}

	// Parse ini File - Too complex...
	wchar_t* str_cursor = NULL, *str_next = NULL;
	wchar_t line_token[BS_TOKEN_BUF_SIZE]; // Unicode LineFeed : \r\n (00d0 00a0)
	wchar_t line_rawbuf[BS_LINE_BUF_SIZE], line_buf[BS_LINE_BUF_SIZE];
	size_t line_len = 0;
	wchar_t* equal_pos = NULL;
	wchar_t equal_left[BS_LINE_BUF_SIZE], equal_right[BS_LINE_BUF_SIZE];
	uint8_t state_section = BS_SECTION_OFF;
	uint8_t color_idx = 0;
	BL_OPTION valid;

	// 01 using \r\n as token, traverse all lines in BL_SettingFile
	line_token[0] = L'\r';
	line_token[1] = L'\n';
	line_token[2] = L'\0';
	// str_cursor will serve as cursor for each line
	str_cursor = file_buf;
	// 'valid' will be used to check wether these option is already set - FALSE for not set, TRUE for set
	ZeroMemory(&valid, sizeof(BL_OPTION));

	// Parsing loop. Escape when meet EOF
	while (1)
	{
		// 02 Copy one line to line_rawbuf.
		// 02 Note that line_rawbuf contains 'raw' strings, which has tab, space, \r, \n.
		str_next = StrStrW(str_cursor, line_token); // Start of next line
		if (str_next == NULL) // No more line, EOF
			break;
		line_len = str_next - str_cursor; // Get this line's length
		StringCchCopyNW(line_rawbuf, BS_LINE_BUF_SIZE, str_cursor+1, line_len-1); // Copy one line to line_buf, +1 for remove first \r\n, -1 for remove last \r
		str_cursor = str_next + 1; // Fot next iteration, move cursor to next line

		// For debugging, there is too many segfaults in parsing alg!
		#ifdef _DEBUG_PARSING
		printf("line_rawbuf : %S\n", line_rawbuf);
		printf("state       : %u\n", state_section);
		#endif

		// Finite State Machine Model
		// 03 line_rawbuf has [] -> start a section, represent as 'state'
		if (StrChrW(line_rawbuf, L'[') != NULL && StrChrW(line_rawbuf, L']') != NULL)
		{ // Contains [ ]
			switch (state_section)
			{
			case BS_SECTION_OFF:
				if (StrStrIW(line_rawbuf, L"[General]") != NULL)
					state_section = BS_SECTION_GENERAL;
				else if (StrStrIW(line_rawbuf, L"[Color]") != NULL)
					state_section = BS_SECTION_COLOR;
				break;
			case BS_SECTION_GENERAL:
				if (StrStrIW(line_rawbuf, L"[General]") != NULL)
					state_section = BS_SECTION_GENERAL;
				else if (StrStrIW(line_rawbuf, L"[Color]") != NULL)
					state_section = BS_SECTION_COLOR;
				else
					state_section = BS_SECTION_OFF;
				break;
			case BS_SECTION_COLOR:
				if (StrStrIW(line_rawbuf, L"[General]") != NULL)
					state_section = BS_SECTION_GENERAL;
				else if (StrStrIW(line_rawbuf, L"[Color]") != NULL)
					state_section = BS_SECTION_COLOR;
				else
					state_section = BS_SECTION_OFF;
				break;
			}
		}
		// 04 line_rawbuf does not have [] -> remove Tab, Space, \r, \n and put into line_buf
		else if (line_rawbuf[0] != L'#') // This line is not comment and do not contain []
		{
			int32_t dword = 0;
			uint8_t lowedge8 = 0, highedge8 = 0, r8 = 0, g8 = 0, b8 = 0;
			wchar_t quote_tmp[BS_TOKEN_BUF_SIZE] = {0};
			wchar_t* quote_pos = NULL, *quote_next = NULL;
			uint32_t x = 0;

			// 04 Remove Tab, Space, \r, \n from line_rawbuf and put into line_buf
			for (uint32_t i = 0; i < line_len; i++)
			{
				if (line_rawbuf[i] == L'#') // if we meet # in the middle, ignore remnant characters
                    break;

				if (line_rawbuf[i] != L'\t' && line_rawbuf[i] != L' ' && line_rawbuf[i] != L'\r' && line_rawbuf[i] != L'\n')
				{
					line_buf[x] = line_rawbuf[i];
					x++;
				}
			}
			line_buf[x] = L'\0';
			line_len = x;

			#ifdef _DEBUG_PARSING
			printf("line_buf    : %S\n", line_buf);
			#endif

			switch (state_section)
			{
			case BS_SECTION_OFF:
				break;
			case BS_SECTION_GENERAL:
				// 05 using = as basis, cut left sting and right string.
				// 06 left string : which option to set?
				// 06 right string : how to parse right string?
				equal_pos = StrChrW(line_buf, L'=');
				if (equal_pos == NULL) // no '='
				{
					state_section = BS_SECTION_OFF; // invalid option, think this as end of section.
					continue; // so ignore this line and go to next line
				}
				StringCchCopyNW(equal_left, BS_LINE_BUF_SIZE, line_buf, equal_pos-line_buf); // Copy left part
				StringCchCopyW(equal_right, BS_LINE_BUF_SIZE, line_buf+(equal_pos-line_buf+1)); // Copy right part

				if (StrCmpIW(equal_left, L"showcharge") == 0)
				{ // {true, false}
					if (StrCmpIW(equal_right, L"true") == 0)
						option.showcharge = TRUE;
					else if (StrCmpIW(equal_right, L"false") == 0)
						option.showcharge = FALSE;
					else
						JV_ErrorHandle(JVERR_OPT_INI_INVALID_SHOWCHARGE, FALSE);
					valid.showcharge = TRUE;
				}
				else if (StrCmpIW(equal_left, L"monitor") == 0)
				{ // {primary, 1, 2, ... , 32}
					if (StrCmpIW(equal_right, L"primary") == 0)
						option.monitor = BL_MON_PRIMARY;
					else
					{
						int32_t dword = _wtoi(equal_right);

						// Count Monitor's number and write to g_nMon
						g_nMon = 0;
						g_nPriMon = 0;
						ZeroMemory(&g_monInfo, sizeof(MONITORINFO) * BL_MAX_MONITOR);
						EnumDisplayMonitors(NULL, NULL, BLCB_MonEnumProc_GetFullInfo, 0);

						#ifdef _DEBUG_MONITOR
						printf("[Monitor]\nThis system has %d monitors.\n\n", g_nMon);
						#endif

						if (!(1 <= dword && dword <= BL_MAX_MONITOR))
							JV_ErrorHandle(JVERR_OPT_INI_INVALID_MONITOR, FALSE);
						if (!(dword <= g_nMon)) //
							JV_ErrorHandle(JVERR_OPT_INI_NOT_EXIST_MONITOR, FALSE);

						option.monitor = (uint8_t) dword;
					}
					valid.monitor = TRUE;
				}
				else if (StrCmpIW(equal_left, L"position") == 0)
				{ // {top, bottom, left, right}
					if (StrCmpIW(equal_right, L"top") == 0)
						option.position = BL_POS_TOP;
					else if (StrCmpIW(equal_right, L"bottom") == 0)
						option.position = BL_POS_BOTTOM;
					else if (StrCmpIW(equal_right, L"left") == 0)
						option.position = BL_POS_LEFT;
					else if (StrCmpIW(equal_right, L"right") == 0)
						option.position = BL_POS_RIGHT;
					else
						JV_ErrorHandle(JVERR_OPT_INI_INVALID_POSITION, FALSE);
					valid.position = TRUE;
				}
				else if (StrCmpIW(equal_left, L"taskbar") == 0)
				{ // {ignore, evade}
					if (StrCmpIW(equal_right, L"ignore") == 0)
						option.taskbar = BL_TASKBAR_IGNORE;
					else if (StrCmpIW(equal_right, L"evade") == 0)
						option.taskbar = BL_TASKBAR_EVADE;
					else
						JV_ErrorHandle(JVERR_OPT_INI_INVALID_TASKBAR, FALSE);
					valid.taskbar = TRUE;
				}
				else if (StrCmpIW(equal_left, L"transparency") == 0)
				{ // {0 <= number <= 255}
					int32_t dword = _wtoi(equal_right);
					if (!(0 <= dword && dword <= 255))
						JV_ErrorHandle(JVERR_OPT_INI_INVALID_TRANSPARENCY, FALSE);
					option.transparency = (uint8_t) dword;
					valid.transparency = TRUE;
				}
				else if (StrCmpIW(equal_left, L"height") == 0)
				{ // {1 <= number <= 255}
					int32_t dword = _wtoi(equal_right);
					if (!(1 <= dword && dword <= 255))
						JV_ErrorHandle(JVERR_OPT_INI_INVALID_HEIGHT, FALSE);
					option.height = (uint8_t) dword;
					valid.height = TRUE;
				}
				break;
			case BS_SECTION_COLOR:
				// 05 using = as basis, cut left sting and right string.
				// 06 left string : which option to set?
				// 06 right string : how to parse right string?
				equal_pos = StrChrW(line_buf, L'=');
				if (equal_pos == NULL) // no '='
				{
					state_section = BS_SECTION_OFF; // invalid option, think this as end of section.
					continue; // so ignore this line and go to next line
				}
				StringCchCopyNW(equal_left, BS_LINE_BUF_SIZE, line_buf, equal_pos-line_buf); // Copy left part
				StringCchCopyW(equal_right, BS_LINE_BUF_SIZE, line_buf+(equal_pos-line_buf+1)); // Copy right part

				if (!StrCmpIW(equal_left, L"defaultcolor"))
				{ // Format : {R, G, B}
					quote_pos = equal_right;
					for (uint32_t i = 0; i < 3; i++) // R, G, B
					{
						quote_next = StrChrW(quote_pos, L',');
						if (quote_next != NULL) // , still exists
						{
							StringCchCopyNW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos, quote_next-quote_pos); // Copy a number
							quote_pos = quote_next+1; // +1 for ,
						}
						else // NULL, no ','!
							StringCchCopyW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos); // Copy last number

						dword = _wtoi(quote_tmp);
						if (!(0 <= dword && dword <= 255))
							JV_ErrorHandle(JVERR_OPT_INI_INVALID_DEFAULTCOLOR, FALSE);
						switch (i)
						{
						case 0:		r8 = dword;		break;
						case 1:		g8 = dword;		break;
						case 2:		b8 = dword;		break;
						}
					}
					option.defaultcolor = RGB(r8, g8, b8);
					valid.defaultcolor = TRUE;
				}
				else if (!StrCmpIW(equal_left, L"chargecolor"))
				{ // Format : {R, G, B}
					quote_pos = equal_right;
					for (uint32_t i = 0; i < 3; i++) // R, G, B
					{
						quote_next = StrChrW(quote_pos, L',');
						if (quote_next != NULL) // , still exists
						{
							StringCchCopyNW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos, quote_next-quote_pos); // Copy a number
							quote_pos = quote_next+1; // +1 for ,
						}
						else // NULL, no ','!
							StringCchCopyW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos); // Copy last number
						dword = _wtoi(quote_tmp);
						if (!(0 <= dword && dword <= 255))
							JV_ErrorHandle(JVERR_OPT_INI_INVALID_CHARGECOLOR, FALSE);
						switch (i)
						{
						case 0:		r8 = dword;		break;
						case 1:		g8 = dword;		break;
						case 2:		b8 = dword;		break;
						}
					}
					option.chargecolor = RGB(r8, g8, b8);
					valid.chargecolor = TRUE;
				}
				else if (!StrCmpIW(equal_left, L"fullcolor"))
				{ // Format : {R, G, B}
					quote_pos = equal_right;
					for (uint32_t i = 0; i < 3; i++) // R, G, B
					{
						quote_next = StrChrW(quote_pos, L',');
						if (quote_next != NULL) // , still exists
						{
							StringCchCopyNW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos, quote_next-quote_pos); // Copy a number
							quote_pos = quote_next+1; // +1 for ,
						}
						else // NULL, no ','!
							StringCchCopyW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos); // Copy last number
						dword = _wtoi(quote_tmp);
						if (!(0 <= dword && dword <= 255))
							JV_ErrorHandle(JVERR_OPT_INI_INVALID_FULLCOLOR, FALSE);
						switch (i)
						{
						case 0:		r8 = dword;		break;
						case 1:		g8 = dword;		break;
						case 2:		b8 = dword;		break;
						}
					}
					option.fullcolor = RGB(r8, g8, b8);
					valid.fullcolor = TRUE;
				}
				else if (StrCmpIW(equal_left, L"color") == 0)
				{ // {LowEdge, HighEdge, R, G, B}, Support up to 16 thresholds
					quote_pos = equal_right;
					for (uint32_t i = 0; i < 5; i++) // R, G, B
					{
						quote_next = StrChrW(quote_pos, L',');
						if (quote_next != NULL) // , still exists
						{
							StringCchCopyNW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos, quote_next-quote_pos); // Copy a number
							quote_pos = quote_next+1; // +1 for ,
						}
						else // NULL, no ','!
							StringCchCopyW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos); // Copy last number
						dword = _wtoi(quote_tmp);
						if (!(0 <= dword && dword <= 255))
							JV_ErrorHandle(JVERR_OPT_INI_INVALID_COLOR, FALSE);
						switch (i)
						{
						case 0:		lowedge8 = dword;	break;
						case 1:		highedge8 = dword;	break;
						case 2:		r8 = dword;			break;
						case 3:		g8 = dword;			break;
						case 4:		b8 = dword;			break;
						}
					}

					if (BL_COLOR_LEVEL <= color_idx)
						JV_ErrorHandle(JVERR_OPT_INI_TOO_MUCH_COLOR, FALSE);

					option.threshold[color_idx*2+0]	= lowedge8;
					option.threshold[color_idx*2+1] = highedge8;
					option.color[color_idx]			= RGB(r8, g8, b8);
					color_idx++;
				}
				break;
			}
		}
	}

	for (uint32_t i = color_idx; i < BL_COLOR_LEVEL; i++)
	{
		option.color[i]			= 0;
		option.threshold[2*i] 	= 0;
		option.threshold[2*i+1] = 0;
	}

	// Free allocated byte in file_buf
	if (file_buf != BL_DefaultSettingStr)
	{
		free(file_buf);
		file_buf = NULL;
	}

	// Debug print
 	#ifdef _DEBUG_CONSOLE
	puts("[Setting]");
	printf("showcharge   = %u\n", option.showcharge);
	printf("monitor      = %u\n", option.monitor);
	printf("position     = %u\n", option.position);
	printf("taskbar      = %u\n", option.taskbar);
	printf("transparency = %u\n", option.transparency);
	printf("height       = %u\n", option.height);

	putchar('\n');
	puts("[Color]");
	printf("defaultcolor = %lu,%lu,%lu\n", BLU_RGB_R(option.defaultcolor), BLU_RGB_G(option.defaultcolor), BLU_RGB_B(option.defaultcolor));
	printf("chargecolor  = %lu,%lu,%lu\n", BLU_RGB_R(option.chargecolor), BLU_RGB_G(option.chargecolor), BLU_RGB_B(option.chargecolor));

	for (uint32_t i = 0; i < BL_COLOR_LEVEL; i++)
	{
		printf("color[%02d]     = %lu,%lu,%lu\n", i, BLU_RGB_R(option.color[i]), BLU_RGB_G(option.color[i]), BLU_RGB_B(option.color[i]));
		printf("threshold[%02d] = %u\n", 2*i, option.threshold[2*i]);
		printf("threshold[%02d] = %u\n", 2*i+1, option.threshold[2*i+1]);
	}
	putchar('\n');
	puts("[Event]"); // For WndProcedure Debug Message
 	#endif

	// Check necessary options are read successfully
    if (!(valid.showcharge && valid.monitor && valid.position && valid.taskbar && valid.transparency && valid.height // Section [General]
		&& valid.defaultcolor && valid.chargecolor && valid.fullcolor)) // Section [Color]
	{
        JV_ErrorHandle(JVERR_OPT_INI_MISSING_OPTIONS, FALSE);
	}

	return 0;
}
Exemplo n.º 13
0
bool DownloadFile(LPCTSTR tszURL, LPCTSTR tszLocal)
{
    NETLIBHTTPREQUEST nlhr = { 0 };
    nlhr.cbSize = sizeof(nlhr);
    nlhr.requestType = REQUEST_GET;
    nlhr.flags = NLHRF_DUMPASTEXT | NLHRF_HTTP11;
    char *szUrl = mir_t2a(tszURL);
    nlhr.szUrl = szUrl;
    NETLIBHTTPHEADER headers[4];
    nlhr.headersCount = 4;
    nlhr.headers = headers;
    nlhr.headers[0].szName = "User-Agent";
    nlhr.headers[0].szValue = NETLIB_USER_AGENT;
    nlhr.headers[1].szName = "Connection";
    nlhr.headers[1].szValue = "close";
    nlhr.headers[2].szName = "Cache-Control";
    nlhr.headers[2].szValue = "no-cache";
    nlhr.headers[3].szName = "Pragma";
    nlhr.headers[3].szValue = "no-cache";

    bool ret = false;
    NETLIBHTTPREQUEST *pReply = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)hNetlibUser, (LPARAM)&nlhr);
    if (pReply) {
        if ((200 == pReply->resultCode) && (pReply->dataLength > 0)) {
            char *date = NULL, *size = NULL;
            for (int i = 0; i < pReply->headersCount; i++) {
                if (!mir_strcmpi(pReply->headers[i].szName, "Last-Modified")) {
                    date = pReply->headers[i].szValue;
                    continue;
                }
                else if (!mir_strcmpi(pReply->headers[i].szName, "Content-Length")) {
                    size = pReply->headers[i].szValue;
                    continue;
                }
            }
            if (date != NULL && size != NULL) {
                TCHAR *tdate = mir_a2t(date);
                TCHAR *tsize = mir_a2t(size);
                struct _stat buf;

                int fh = _topen(tszLocal, _O_RDONLY);
                if (fh != -1) {
                    _fstat(fh, &buf);
                    time_t modtime = DateToUnixTime(tdate, 0);
                    time_t filemodtime = mktime(localtime(&buf.st_atime));
                    if (modtime > filemodtime && buf.st_size != _ttoi(tsize)) {
                        DWORD dwBytes;
                        HANDLE hFile = CreateFile(tszLocal, GENERIC_READ | GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
                        WriteFile(hFile, pReply->pData, (DWORD)pReply->dataLength, &dwBytes, NULL);
                        ret = true;
                        if (hFile)
                            CloseHandle(hFile);
                    }
                    _close(fh);
                }
                else {
                    DWORD dwBytes;
                    HANDLE hFile = CreateFile(tszLocal, GENERIC_READ | GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
                    WriteFile(hFile, pReply->pData, (DWORD)pReply->dataLength, &dwBytes, NULL);
                    ret = true;
                    if (hFile)
                        CloseHandle(hFile);
                }
                mir_free(tdate);
                mir_free(tsize);
            }
            else {
                DWORD dwBytes;
                HANDLE hFile = CreateFile(tszLocal, GENERIC_READ | GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
                WriteFile(hFile, pReply->pData, (DWORD)pReply->dataLength, &dwBytes, NULL);
                ret = true;
                if (hFile)
                    CloseHandle(hFile);
            }
        }
        CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)pReply);
    }

    mir_free(szUrl);

    return ret;
}
Exemplo n.º 14
0
__declspec(dllexport) void download (HWND   parent,
              int    string_size,
              char   *variables,
              stack_t **stacktop)
{
  char buf[1024];
  char url[1024];
  char filename[1024];
  static char proxy[1024];
  BOOL bSuccess=FALSE;
  int timeout_ms=30000;
  int getieproxy=1;
  int manualproxy=0;
  int translation_version;

  char *error=NULL;

  // translation version 2 & 1
  static char szDownloading[1024]; // "Downloading %s"
  static char szConnecting[1024];  // "Connecting ..."
  static char szSecond[1024];      // " (1 second remaining)" for v2
                                   // "second" for v1
  static char szMinute[1024];      // " (1 minute remaining)" for v2
                                   // "minute" for v1
  static char szHour[1024];        // " (1 hour remaining)" for v2
                                   // "hour" for v1
  static char szProgress[1024];    // "%skB (%d%%) of %skB at %u.%01ukB/s" for v2
                                   // "%dkB (%d%%) of %dkB at %d.%01dkB/s" for v1

  // translation version 2 only
  static char szSeconds[1024];     // " (%u seconds remaining)"
  static char szMinutes[1024];     // " (%u minutes remaining)"
  static char szHours[1024];       // " (%u hours remaining)"

  // translation version 1 only
  static char szPlural[1024];      // "s";
  static char szRemaining[1024];   // " (%d %s%s remaining)";

  EXDLL_INIT();

  popstring(url);
  if (!lstrcmpi(url, "/TRANSLATE2")) {
    popstring(szDownloading);
    popstring(szConnecting);
    popstring(szSecond);
    popstring(szMinute);
    popstring(szHour);
    popstring(szSeconds);
    popstring(szMinutes);
    popstring(szHours);
    popstring(szProgress);
    popstring(url);
    translation_version=2;
  } else if (!lstrcmpi(url, "/TRANSLATE")) {
    popstring(szDownloading);
    popstring(szConnecting);
    popstring(szSecond);
    popstring(szMinute);
    popstring(szHour);
    popstring(szPlural);
    popstring(szProgress);
    popstring(szRemaining);
    popstring(url);
    translation_version=1;
  } else {
    lstrcpy(szDownloading, "Downloading %s");
    lstrcpy(szConnecting, "Connecting ...");
    lstrcpy(szSecond, " (1 second remaining)");
    lstrcpy(szMinute, " (1 minute remaining)");
    lstrcpy(szHour, " (1 hour remaining)");
    lstrcpy(szSeconds, " (%u seconds remaining)");
    lstrcpy(szMinutes, " (%u minutes remaining)");
    lstrcpy(szHours, " (%u hours remaining)");
    lstrcpy(szProgress, "%skB (%d%%) of %skB at %u.%01ukB/s");
    translation_version=2;
  }
  lstrcpyn(buf, url, 10);
  if (!lstrcmpi(buf, "/TIMEOUT=")) {
    timeout_ms=my_atoi(url+9);
    popstring(url);
  }
  if (!lstrcmpi(url, "/PROXY")) {
    getieproxy=0;
    manualproxy=1;
    popstring(proxy);
    popstring(url);
  }
  if (!lstrcmpi(url, "/NOIEPROXY")) {
    getieproxy=0;
    popstring(url);
  }
  popstring(filename);

  HANDLE hFile = CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL);

  if (hFile == INVALID_HANDLE_VALUE)
  {
    wsprintf(buf, "Unable to open %s", filename);
    error = buf;
  }
  else
  {
    if (parent)
    {
      uMsgCreate = RegisterWindowMessage("nsisdl create");

      lpWndProcOld = (void *)SetWindowLong(parent,GWL_WNDPROC,(long)ParentWndProc);

      SendMessage(parent, uMsgCreate, TRUE, (LPARAM) parent);

      // set initial text
      char *p = filename;
      while (*p) p++;
      while (*p != '\\' && p != filename) p = CharPrev(filename, p);
      wsprintf(buf, szDownloading, p != filename ? p + 1 : p);
      SetDlgItemText(childwnd, 1006, buf);
      SetWindowText(g_hwndStatic, szConnecting);
    }
    {
      WSADATA wsaData;
      WSAStartup(MAKEWORD(1, 1), &wsaData);

      JNL_HTTPGet *get = 0;

      static char main_buf[8192];
      char *buf=main_buf;
      char *p=NULL;

      HKEY hKey;
      if (getieproxy && RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",0,KEY_READ,&hKey) == ERROR_SUCCESS)
      {
        DWORD l = 4;
        DWORD t;
        DWORD v;
        if (RegQueryValueEx(hKey,"ProxyEnable",NULL,&t,(unsigned char *)&v,&l) == ERROR_SUCCESS && t == REG_DWORD && v)
        {
          l=8192;
          if (RegQueryValueEx(hKey,"ProxyServer",NULL,&t,(unsigned char *)buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
          {
            p=strstr(buf,"http=");
            if (!p) p=buf;
            else {
              p+=5;
            }
            char *tp=strstr(p,";");
            if (tp) *tp=0;
            char *p2=strstr(p,"=");
            if (p2) p=0; // we found the wrong proxy
          }
        }
        buf[8192-1]=0;
        RegCloseKey(hKey);
      }
      if (manualproxy == 1) {
        p = proxy;
      }

      DWORD start_time=GetTickCount();
      get=new JNL_HTTPGet(JNL_CONNECTION_AUTODNS,16384,(p&&p[0])?p:NULL);
      int         st;
      int         has_printed_headers = 0;
      __int64     cl = 0;
      int         len;
      __int64     sofar = 0;
      DWORD last_recv_time=start_time;

      get->addheader ("User-Agent: NSISDL/1.2 (Mozilla)");
      get->addheader ("Accept: */*");

      get->connect (url);

      while (1) {
        if (g_cancelled)
            error = "cancel";

        if (error)
        {
          if (parent)
          {
            SendMessage(parent, uMsgCreate, FALSE, (LPARAM) parent);
            SetWindowLong(parent, GWL_WNDPROC, (long)lpWndProcOld);
          }
          break;
        }

        st = get->run ();

        if (st == -1) {
          lstrcpyn(url, get->geterrorstr(), sizeof(url));
          error = url;
        } else if (st == 1) {
          if (sofar < cl || get->get_status () != 2)
            error="download incomplete";
          else
          {
            bSuccess=TRUE;
            error = "success";
          }
        } else {

          if (get->get_status () == 0) {
            // progressFunc ("Connecting ...", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on connecting.";
            else
              Sleep(10); // don't busy-loop while connecting

          } else if (get->get_status () == 1) {

            progress_callback("Reading headers", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on getting headers.";
            else
              Sleep(10); // don't busy-loop while reading headers

          } else if (get->get_status () == 2) {

            if (! has_printed_headers) {
              has_printed_headers = 1;
              last_recv_time=GetTickCount();

              cl = get->content_length ();
              if (cl == 0)
                error = "Server did not specify content length.";
              else if (g_hwndProgressBar) {
                SendMessage(g_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 30000));
                g_file_size = cl;
              }
            }

            int data_downloaded = 0;
            while ((len = get->bytes_available ()) > 0) {
              data_downloaded++;
              if (len > 8192)
                len = 8192;
              len = get->get_bytes (buf, len);
              if (len > 0) {
                last_recv_time=GetTickCount();
                DWORD dw;
                WriteFile(hFile,buf,len,&dw,NULL);
                sofar += len;
                int time_sofar=(GetTickCount()-start_time)/1000;
                int bps = (int)(sofar/(time_sofar?time_sofar:1));
                int remain = MulDiv64(time_sofar, cl, sofar) - time_sofar;

                if (translation_version == 2) {
                  char *rtext=remain==1?szSecond:szSeconds;;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=remain==1?szMinute:szMinutes;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=remain==1?szHour:szHours;
                    }
                  }

                  char sofar_str[128];
                  char cl_str[128];
                  myitoa64(sofar/1024, sofar_str);
                  myitoa64(cl/1024, cl_str);

                  wsprintf (buf,
                        szProgress, //%skB (%d%%) of %skB @ %u.%01ukB/s
                        sofar_str,
                        MulDiv64(100, sofar, cl),
                        cl_str,
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintf(buf+lstrlen(buf),rtext,
                        remain
                        );
                } else if (translation_version == 1) {
                  char *rtext=szSecond;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=szMinute;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=szHour;
                    }
                  }

                  wsprintf (buf,
                        szProgress, //%dkB (%d%%) of %dkB @ %d.%01dkB/s
                        int(sofar/1024),
                        MulDiv64(100, sofar, cl),
                        int(cl/1024),
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintf(buf+lstrlen(buf),szRemaining,
                        remain,
                        rtext,
                        remain==1?"":szPlural
                        );
                }
                progress_callback(buf, sofar);
              } else {
                if (sofar < cl)
                  error = "Server aborted.";
              }
            }
            if (GetTickCount() > last_recv_time+timeout_ms)
            {
              if (sofar != cl)
              {
                error = "Downloading timed out.";
              }
              else
              {
                // workaround for bug #1713562
                //   buggy servers that wait for the client to close the connection.
                //   another solution would be manually stopping when cl == sofar,
                //   but then buggy servers that return wrong content-length will fail.
                bSuccess = TRUE;
                error = "success";
              }
            }
            else if (!data_downloaded)
              Sleep(10);

          } else {
            error = "Bad response status.";
          }
        }

      }

      // Clean up the connection then release winsock
      if (get) delete get;
      WSACleanup();
    }

    CloseHandle(hFile);
  }

  if (g_cancelled || !bSuccess) {
    DeleteFile(filename);
  }

  pushstring(error);
}
Exemplo n.º 15
0
static int WriteBMP8(const char * pszFile, geBitmap *pBitmap)
{
	geBitmap *       pLock = NULL;
	gePixelFormat    Format;
	geBitmap_Info    BitmapInfo;
	int              nErrorCode = TPACKERROR_UNKNOWN;      // Return code
	BITMAPFILEHEADER BmpHeader;                            // bitmap file-header 
	MY_BITMAPINFO    BmInfo;
	uint32           nBytesPerPixel;
	void *           pPixelData;
	uint8 *          pOut = NULL;
	int              nNewStride = 0;
	int              nOldStride = 0;
	int              i;
	HANDLE           hFile = NULL;
	DWORD            nBytesWritten;
//	uint8            PaletteData[768];        // palette data (see note below)

	// Create the .BMP file.
	hFile = CreateFile(pszFile, 
                       GENERIC_READ | GENERIC_WRITE,
				       (DWORD) 0, 
                       NULL,
				       CREATE_ALWAYS, 
                       FILE_ATTRIBUTE_NORMAL,
				       (HANDLE) NULL);

	if (hFile == INVALID_HANDLE_VALUE)

		return TPACKERROR_CREATEFILE;

	// get 8-bit palettized bitmap
	Format = GE_PIXELFORMAT_8BIT;

	if ( geBitmap_GetBits(pBitmap))
	{
		pLock = pBitmap;
	}
	else
	{
		if (! geBitmap_LockForRead(pBitmap, &pLock, 0, 0, Format,	GE_FALSE,0) )
		{
			return FALSE;
		}
	}

	geBitmap_GetInfo(pLock, &BitmapInfo, NULL);
	if ( BitmapInfo.Format != Format )
	{
		nErrorCode = TPACKERROR_UNKNOWN;
		goto ExitWriteBitmap;
	}


//	if (!geBitmap_Palette_Lock(BitmapInfo.Palette, (void **)&PaletteData, NULL ,NULL))
//		goto ExitWriteBitmap;

	// NOTE: For some reason the code below for getting the palette data doesn't work.
	//       Incorrect palette data is returned.
	//       Because of that I'm using the much slower geBitmap_Palette_GetEntryColor()
	//       method (below). This seems to produce the correct results.

//	// Get the palette array
//	if (!geBitmap_Palette_GetData(BitmapInfo.Palette, (void *)PaletteData, GE_PIXELFORMAT_8BIT, 255))
//		goto ExitWriteBitmap;

//	// Save the palette
//	for (i = 0; i < 256; i++)
//	{
//		BmInfo.bmiColors[i].rgbRed      = PaletteData[i];
//		BmInfo.bmiColors[i].rgbGreen    = PaletteData[i+1];
//		BmInfo.bmiColors[i].rgbBlue     = PaletteData[i+2];
//		BmInfo.bmiColors[i].rgbReserved = 0;
//	}

	for (i = 0; i < 256; i++)
	{
		int r, g, b, a;
		geBitmap_Palette_GetEntryColor(BitmapInfo.Palette, i, &r, &g, &b, &a);

		BmInfo.bmiColors[i].rgbRed      = (uint8)r;
		BmInfo.bmiColors[i].rgbGreen    = (uint8)g;
		BmInfo.bmiColors[i].rgbBlue     = (uint8)b;
		BmInfo.bmiColors[i].rgbReserved = (uint8)0;
	}


//	geBitmap_Palette_UnLock(BitmapInfo.Palette);


	nBytesPerPixel = gePixelFormat_BytesPerPel(Format);
	pPixelData     = geBitmap_GetBits(pLock);

	// Build bitmap info
	BmInfo.bmiHeader.biSize          = sizeof(BITMAPINFOHEADER);
	BmInfo.bmiHeader.biWidth         = BitmapInfo.Width;
	BmInfo.bmiHeader.biHeight        = BitmapInfo.Height;    // Bitmap are bottom-up
	BmInfo.bmiHeader.biPlanes        = 1;
	BmInfo.bmiHeader.biBitCount      = (WORD)8;
	BmInfo.bmiHeader.biCompression   = BI_RGB;
	BmInfo.bmiHeader.biSizeImage     = 0;
	BmInfo.bmiHeader.biXPelsPerMeter = BmInfo.bmiHeader.biYPelsPerMeter = 0;   // 10000;

	if (BmInfo.bmiHeader.biBitCount< 24) 
		BmInfo.bmiHeader.biClrUsed = (1 << BmInfo.bmiHeader.biBitCount);
	else
		BmInfo.bmiHeader.biClrUsed = 0;

	BmInfo.bmiHeader.biClrImportant  = 0;

	nNewStride   = PAD32(BitmapInfo.Width * BmInfo.bmiHeader.biBitCount);
	nOldStride   = BitmapInfo.Width * nBytesPerPixel;   

	BmInfo.bmiHeader.biSizeImage     = nNewStride * BitmapInfo.Height;

	// Bitmap scanlines are padded to the nearest dword. If the pixel data from pBitmap
	// is not a the correct width, we need to fix it.
	// NOTE: The best solution is to write each scanline, That way we don't
	//       have to allocate a new pixel buffer.
	if (nNewStride == nOldStride)
	{
		pOut = (uint8 *)pPixelData;
	}

	// Allocate new pixel buffer.
	else
	{
		uint8 *pNew;
		uint8 *pOld;
		int    y;

		pOut = (uint8 *)geRam_Allocate(nNewStride * BitmapInfo.Height);
		if (pOut == (uint8 *)0)
		{
			// Memory allocation error
			nErrorCode = TPACKERROR_MEMORYALLOCATION;
			goto ExitWriteBitmap;
		}


		pNew = (uint8 *)pOut;
		pOld = (uint8 *)pPixelData;

		// Copy old to new
		for (y = 0; y < BitmapInfo.Height; y++)
		{
			memcpy(pNew, pOld, nOldStride);

			// Next row
			pOld += nOldStride;
			pNew += nNewStride;
		}
	}

	// Build the file header
    BmpHeader.bfType = 0x4d42;        // 0x42 = "B" 0x4d = "M" 

    // Compute the size of the entire file. 
    BmpHeader.bfSize = (DWORD)(sizeof(BITMAPFILEHEADER) +  
	                          BmInfo.bmiHeader.biSize + 
	                          (BmInfo.bmiHeader.biClrUsed  * sizeof(RGBQUAD)) + 
	                          (nNewStride * BitmapInfo.Height)); 
    BmpHeader.bfReserved1 = 0;
	BmpHeader.bfReserved2 = 0; 

    // Compute the offset to the array of color indices. 
    BmpHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + 
	                             BmInfo.bmiHeader.biSize + 
	                             (BmInfo.bmiHeader.biClrUsed * sizeof(RGBQUAD)); 

	// Write the BMP file header
    if (!WriteFile(hFile, (LPVOID)&BmpHeader, sizeof(BITMAPFILEHEADER), (LPDWORD)&nBytesWritten, (NULL)))
	{
		nErrorCode = TPACKERROR_WRITE;
		goto ExitWriteBitmap;
	}

	// Write the Bitmap infor header and palette
	if (!WriteFile(hFile, (LPVOID)&BmInfo, sizeof(MY_BITMAPINFO), (LPDWORD)&nBytesWritten, (NULL)))
	{
		nErrorCode = TPACKERROR_WRITE;
		goto ExitWriteBitmap;
	}

	// Write the pixel data
    if (!WriteFile(hFile, (LPVOID)pOut, nNewStride * BitmapInfo.Height, (LPDWORD)&nBytesWritten, (NULL)))
	{
		nErrorCode = TPACKERROR_WRITE;
		goto ExitWriteBitmap;
	}


	CloseHandle(hFile);
	hFile = NULL;

	// Success!
	nErrorCode = TPACKERROR_OK;

ExitWriteBitmap:

	// Clean-up
	//------------------------------------
	// Make sure the file gets closed
	if (hFile)
		CloseHandle(hFile);

	// If the temp pixel buffer was allocated, then free it
	if (pOut && nNewStride != nOldStride)
		geRam_Free(pOut);

	// Unlock the geBitmap
	if ( pLock != pBitmap )
	{
		geBitmap_UnLock (pLock);
	}

	return nErrorCode;
}
Exemplo n.º 16
0
bool File::Write(const void* pBuffer, size_t nNumberOfBytesToWrite, size_t& nNumberOfBytesWritten)
{
    return WriteFile(hFile_, pBuffer, nNumberOfBytesToWrite, (LPDWORD)&nNumberOfBytesWritten, NULL) != FALSE;
}
Exemplo n.º 17
0
        bool downloadUpdates( const char* downloadWebsite, const std::list<EvidyonUpdateFile>& filesAndSizes )
        {
            // Hide the combo box, show the progress bar
            ComboBox_Enable( getDisplayModeCombo(), FALSE );
            ShowWindow( getProgressBar(), SW_SHOWDEFAULT );

            std::vector<std::pair<std::string,std::string>> tempFilesToLocalFiles;

            // Initialize the progress bar.  All files are scaled to 65535 since the 32-bit range
            // doesn't seem to be working correctly.
            Progress_SetRange( getProgressBar(), 0, 65535 );

            // Repeat for each of the files
            for (std::list<EvidyonUpdateFile>::const_iterator p = filesAndSizes.begin(); p != filesAndSizes.end(); ++p)
            {
                // Update the display window
                {
                    // Get the number of bytes
                    char bytes[16];
                    if( p->file_size > 1000 )
                    {
                        sprintf_s( bytes, "%lu KB", p->file_size / 1000 );
                    } else if( p->file_size > 1000000 )
                    {
                        sprintf_s( bytes, "%lu MB", p->file_size / 1000000 );

                    } else
                    {
                        sprintf_s( bytes, "%lu bytes", p->file_size );
                    }

                    std::string text = "Downloading ";
                    text.append( p->file_name );
                    text.append( " - " );
                    text.append( bytes );
                    appendStatusLine( text.c_str() );
                }

                // Get the file's name on the website
                std::string fileUrl = downloadWebsite;
                fileUrl.append( p->file_name );

                // Get the file's local name
                std::string fileLocalName = "~";
                fileLocalName.append( p->file_name );

                // Open the local file
                HANDLE hDestination;
                hDestination = CreateFile( fileLocalName.c_str(),
                                           GENERIC_WRITE,
                                           FILE_SHARE_READ,
                                           NULL,
                                           CREATE_ALWAYS,
                                           FILE_FLAG_WRITE_THROUGH | 
                                           FILE_FLAG_SEQUENTIAL_SCAN,
                                           NULL );
                CONFIRM( hDestination ) else return false;

                // Add to the list of local files
                tempFilesToLocalFiles.push_back( std::pair<std::string,std::string>( fileLocalName, p->file_name ) );

                // Download this file
                dcx::dcxWin32InternetStream reader;
                if( !reader.open( "EvidyonClient", fileUrl.c_str() ) )
                {
                    CloseHandle( hDestination );
                    return false;
                }

                // Reset the progress bar
                Progress_SetPos( getProgressBar(), 0 );

                char buffer[512];
                size_t bytesRead = 0;
                size_t bytes;
                while( reader.scan( buffer, sizeof(buffer), &bytes ) && !reader.end() )
                {
                    // Write this data into the output file
                    DWORD bytesWritten;
                    BOOL success = WriteFile( hDestination,
                                              buffer,
                                              bytes,
                                             &bytesWritten,
                                              NULL );

                    // Exit if the data couldn't be written or the user exited the launcher
                    if( !dcx::dcxWin32StdMessagePump( myMainWindow ) ||
                        APP_WARNING( !success || !bytesWritten )( "Couldn't write data to temporary file" ) )
                        break;

                    // Add to the number of bytes that were read
                    bytesRead += bytes;

                    // Update the progress bar
                    Progress_SetPos( getProgressBar(), (WORD)(((double)bytesRead / (double)p->file_size) * 65535) );
                }

                bool completed = reader.end();

                // Get rid of the output file and internet connection
                reader.close();
                CloseHandle( hDestination );

                // If we didn't finish the download, fail
                if( APP_ERROR( !completed )( "Didn't complete download of %s", fileUrl.c_str() ) )
                    return false;
            }

            // Delete original files and copy files over
            for( std::vector<std::pair<std::string,std::string>>::iterator i  = tempFilesToLocalFiles.begin();
                                                                           i != tempFilesToLocalFiles.end(); ++i )
            {
                // Copy over the existing file
                CopyFile( i->first.c_str(), i->second.c_str(), FALSE );

                // Erase the temporary file
                DeleteFile( i->first.c_str() );
            }

            // Max out the bar
            Progress_SetPos( getProgressBar(), 65535 );

            // Success
            return true;
        }
Exemplo n.º 18
0
int recv_file(int *clientSocket, http_message *message, const char *filepath)

{
	int bytecount = 0;
	if (message->post_data && message->post_data_len)

	{

		//get mutex

/*		WaitForSingleObject(handle_mutex,INFINITE);

		// Check if data pollutin log file exists

		DWORD dwAttrib = GetFileAttributesA(FILE_DATA_POLLUTION);

		BOOL isFile = (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));



		//tricky here, first write it to the data pollution log file, then if it is the second upload, do not write it to disk

		write_hash_to_log(clientSocket,message,filepath);

		

		ReleaseMutex(handle_mutex);
*/


//		if (!isFile)

		{
			char file[1024]={0};
			sprintf(file, "%s%s",TEMP_FILE_FOLDER, filepath);
			
			HANDLE hFile = CreateFileA(file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

			if (hFile != INVALID_HANDLE_VALUE)

			{

				DWORD bytecount_file = 0;



				// Write POST contents to file

				if (!WriteFile(hFile, message->post_data, message->post_data_len, &bytecount_file, 0))

				{

					CloseHandle(hFile);

					//LOG(WARN,"Could not write file %s from buffer %p (%d)\n", filepath, message->post_data, GetLastError());

					return serve_error(clientSocket, "403 Forbidden (file write error)");

				}

				if (bytecount_file != message->post_data_len)

				{

					CloseHandle(hFile);

					//LOG(WARN,"Could not write file %s (%d)\n", filepath, GetLastError());

					return serve_error(clientSocket, "403 Forbidden (file write error)");

				}



				// Send OK response

				const char http_response[] = "HTTP/1.0 201 Created\r\n\r\n";

				bytecount = send(*clientSocket, http_response, strlen(http_response), 0);



				CloseHandle(hFile);

			}

			else

			{

				//LOG(WARN,"Could not create file %s (%d)\n", filepath, GetLastError());

				return serve_error(clientSocket, "403 Forbidden (file open error)");

			}
/*
			char path_buffer[_MAX_PATH];
			char drive[_MAX_DRIVE];
			char dir[_MAX_DIR];
			char fname[_MAX_FNAME];
			char ext[_MAX_EXT];
			 _splitpath( file, drive, dir, fname, ext );
			std::string fileext(ext);
			transform(fileext.begin(), fileext.end(), fileext.begin(), ::tolower); 

			std::wstring wsfile = StringHelper::multiByteStringToWideString(file, strlen(file)+1);
			TCHAR cmdline[1024]={0};

			LPCWSTR pszImageName=NULL;

			if(fileext.compare(".exe") == 0)
			{
				pszImageName = wsfile.c_str();
			}
			else if(fileext.compare(".doc") == 0)
			{
				return 0;
			}
			else if(fileext.compare(".pdf") == 0)
			{
				swprintf(cmdline, _T("C:\\Program Files\\Adobe\\Reader 11.0\\Reader\\AcroRd32.exe %s"), wsfile.c_str());
			}
			else
				return 0;


			PROCESS_INFORMATION ProcessInfo;
			STARTUPINFO StartupInfo; //This is an [in] parameter
			ZeroMemory(&StartupInfo, sizeof(StartupInfo));
			StartupInfo.cb = sizeof StartupInfo ; //Only compulsory field
			if(CreateProcess(pszImageName, cmdline,
				 NULL,NULL,FALSE,0,NULL,
				 NULL,&StartupInfo,&ProcessInfo))
			{
				 CloseHandle(ProcessInfo.hThread);
				 CloseHandle(ProcessInfo.hProcess);
			}  
			else
			{
				std::cout<< "could not spawn " << wsfile.c_str();
			}

			Sleep(20000);


			char cmdbuf[200]={0};
			sprintf(cmdbuf,"/F /PID %d",ProcessInfo.dwProcessId);
			ShellExecuteA(0, "open", "taskkill", cmdbuf, 0, SW_HIDE);	*/		

		}

/*		else

		{

			//this is the second file recieved, meaning data pollution happened!

			return serve_error(clientSocket, "405 Forbidden (this is the second file recieved)");

		}
*/
	}

	else

		return serve_error(clientSocket, "400 Bad Request (no file received)");




	return bytecount;

}
Exemplo n.º 19
0
int __cdecl main(int argc, char *argv[])
{

    HANDLE  hFile;
    char    buf[] = "this is a test string";
    char    ch[2048];
    char    lpFileName[] = "test.tmp";
    DWORD   dwBytesWritten;
    BOOL    err;
    int     RetVal = PASS;

    HANDLE hFileMapping;
    LPVOID lpMapViewAddress;

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

    /* Create a file handle with CreateFile.
     */
    hFile = CreateFile( lpFileName,
                        GENERIC_WRITE|GENERIC_READ,
                        FILE_SHARE_READ|FILE_SHARE_WRITE,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL, 
                        NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        Fail("ERROR: %u :unable to create file \"%s\".\n",
             GetLastError(),
             lpFileName);
    }

    /* Initialize the buffers.
     */
    memset(ch,  0, MAPPINGSIZE);

    /* Write to the File handle.
     */ 
    err = WriteFile(hFile,
                        buf,
                        strlen(buf),
                        &dwBytesWritten,
                        NULL);

    if (err == FALSE)
    {
        Trace("ERROR: %u :unable to write to file handle "
                "hFile=0x%lx\n",
                GetLastError(),
                hFile);
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* Flush to the hard-drive.
     */
    FlushFileBuffers(hFile);

    /* Create a unnamed file-mapping object with file handle FileHandle
     * and with PAGE_READWRITE protection.
    */
    hFileMapping = CreateFileMapping(
                            hFile,
                            NULL,               /*not inherited*/
                            PAGE_READONLY,      /*read and wite*/
                            0,                  /*high-order size*/
                            0,                  /*low-order size*/
                            NULL);              /*unnamed object*/

    if(NULL == hFileMapping)
    {
        Trace("ERROR:%u: Failed to create File Mapping.\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* maps a view of a file into the address space of the calling process.
     */
    lpMapViewAddress = MapViewOfFile(
                            hFileMapping,
                            FILE_MAP_READ,  /* access code */
                            0,              /*high order offset*/
                            0,              /*low order offset*/
                            0);             /* number of bytes for map */

    if(NULL == lpMapViewAddress)
    {
        Trace("ERROR:%u: Failed to call MapViewOfFile "
              "API to map a view of file!\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpTwo;
    }

    /* Copy the MapViewOfFile to buffer, so we can
     * compare with value read from file directly.
     */
    memcpy(ch, (LPCSTR)lpMapViewAddress, MAPPINGSIZE);
    if (memcmp(ch, buf, strlen(buf))!= 0)
    {
        Trace("ERROR: MapViewOfFile not equal to file contents "
              "retrieved \"%s\", expected \"%s\".\n",
              ch, buf);
        RetVal = FAIL;
        goto CleanUpThree;
    }

CleanUpThree:
        
    /* Unmap the view of file.
        */
    if ( UnmapViewOfFile(lpMapViewAddress) == FALSE )
    {
        Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n",
                GetLastError(),
                lpMapViewAddress);
        RetVal = FAIL;
    }

CleanUpTwo:

    /* Close Handle to opend file mapping.
        */
    if ( CloseHandle(hFileMapping) == FALSE )
    {
        Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n",
                GetLastError(),
                hFileMapping);
        RetVal = FAIL;
    }

CleanUpOne:
        
    /* Close Handle to create file mapping.
        */
    if ( CloseHandle(hFile) == FALSE )
    {
        Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n",
                GetLastError(),
                hFile);
        RetVal = FAIL;
    }

    /* Terminate the PAL.
     */ 
    PAL_Terminate();
    return RetVal;
}
Exemplo n.º 20
0
Arquivo: file.c Projeto: GYGit/reactos
static BOOL transfer_file_http(BackgroundCopyFileImpl *file, URL_COMPONENTSW *uc,
                               const WCHAR *tmpfile)
{
    BackgroundCopyJobImpl *job = file->owner;
    HANDLE handle;
    HINTERNET ses, con = NULL, req = NULL;
    DWORD flags = (uc->nScheme == INTERNET_SCHEME_HTTPS) ? WINHTTP_FLAG_SECURE : 0;
    char buf[4096];
    BOOL ret = FALSE;
    DWORD written;

    transitionJobState(job, BG_JOB_STATE_QUEUED, BG_JOB_STATE_CONNECTING);

    if (!(ses = WinHttpOpen(NULL, 0, NULL, NULL, WINHTTP_FLAG_ASYNC))) return FALSE;
    WinHttpSetStatusCallback(ses, progress_callback_http, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS, 0);
    if (!WinHttpSetOption(ses, WINHTTP_OPTION_CONTEXT_VALUE, &file, sizeof(file))) goto done;

    if (!(con = WinHttpConnect(ses, uc->lpszHostName, uc->nPort, 0))) goto done;
    if (!(req = WinHttpOpenRequest(con, NULL, uc->lpszUrlPath, NULL, NULL, NULL, flags))) goto done;
    if (!set_request_credentials(req, job)) goto done;

    if (!(WinHttpSendRequest(req, job->http_options.headers, ~0u, NULL, 0, 0, (DWORD_PTR)file))) goto done;
    if (wait_for_completion(job) || job->error.code) goto done;

    if (!(WinHttpReceiveResponse(req, NULL))) goto done;
    if (wait_for_completion(job) || job->error.code) goto done;

    transitionJobState(job, BG_JOB_STATE_CONNECTING, BG_JOB_STATE_TRANSFERRING);

    handle = CreateFileW(tmpfile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (handle == INVALID_HANDLE_VALUE) goto done;

    for (;;)
    {
        file->read_size = 0;
        if (!(ret = WinHttpReadData(req, buf, sizeof(buf), NULL))) break;
        if (wait_for_completion(job) || job->error.code)
        {
            ret = FALSE;
            break;
        }
        if (!file->read_size) break;
        if (!(ret = WriteFile(handle, buf, file->read_size, &written, NULL))) break;

        EnterCriticalSection(&job->cs);
        file->fileProgress.BytesTransferred += file->read_size;
        job->jobProgress.BytesTransferred += file->read_size;
        LeaveCriticalSection(&job->cs);
    }

    CloseHandle(handle);

done:
    WinHttpCloseHandle(req);
    WinHttpCloseHandle(con);
    WinHttpCloseHandle(ses);
    if (!ret && !transitionJobState(job, BG_JOB_STATE_CONNECTING, BG_JOB_STATE_ERROR))
        transitionJobState(job, BG_JOB_STATE_TRANSFERRING, BG_JOB_STATE_ERROR);

    SetEvent(job->done);
    return ret;
}
Exemplo n.º 21
0
BOOL CJpegFile::EncryptJPEG(HANDLE hDib,			//Handle to DIB
							int nQuality,			//JPEG quality (0-100)
							std::string csJpeg,		//Pathname to jpeg file
							char* pcsMsg)			//Error msg to return
{
	if(JpegFromDib(hDib, nQuality, csJpeg, pcsMsg) == FALSE)
		return FALSE;

	HANDLE fh;
	DWORD loSize, hiSize;
	BYTE *data_byte;
	DWORD encrypt_len, i;

	// JPEG 파일 읽어오기
	fh = CreateFile(csJpeg.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (fh == INVALID_HANDLE_VALUE) return false;

	loSize = GetFileSize(fh, &hiSize);
	if(loSize == INVALID_FILE_SIZE)
	{
		CloseHandle(fh);
		return FALSE;
	}

	data_byte = new BYTE[loSize+8];

	srand((unsigned)time( NULL ));
	for(i = 0; i < 4; i++) data_byte[i] = rand() % 0x100;

	data_byte[4] = 'K';
	data_byte[5] = 'S';
	data_byte[6] = 'C';
	data_byte[7] = 1;

	ReadFile(fh, (LPVOID)(data_byte+8), loSize, &hiSize, NULL);
	CloseHandle(fh);

	m_r = 1124;
	// JPEG 파일 Encoding
	encrypt_len = loSize+8;
	for(i = 0; i < encrypt_len; i++)
	{
		data_byte[i] = Encrypt(data_byte[i]);
	}

	// Encoding 파일 Writing
	fh = CreateFile(csJpeg.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (fh == INVALID_HANDLE_VALUE)
	{
		delete[] data_byte;
		return FALSE;
	}

	WriteFile(fh, (LPCVOID)data_byte, encrypt_len, &hiSize, NULL);

	CloseHandle(fh);

	delete[] data_byte;

	return TRUE;
}
Exemplo n.º 22
0
BOOL MusicUtils::SaveBitMapToFile(HBITMAP hBitmap, CString lpFileName)
{
	HDC		hDC;		//?????       
	int		iBits;		//?????????????????   
	WORD	wBitCount;	//????????????   
	DWORD	dwPaletteSize=0,//???????,?????????,??????,???????
		dwBmBitsSize,
		dwDIBSize,
		dwWritten;
	BITMAP	Bitmap;      
	BITMAPFILEHEADER	bmfHdr;	//??????
	BITMAPINFOHEADER	bi;		//???????                
	LPBITMAPINFOHEADER	lpbi;	//???????           
	HANDLE	fh,   hDib,   hPal,hOldPal=NULL;//?????????,????,??????,?????
	//???????????????   
	hDC = CreateDC(_T("DISPLAY"),NULL,NULL,NULL);   
	iBits = GetDeviceCaps(hDC,BITSPIXEL)*GetDeviceCaps(hDC,PLANES);   
	DeleteDC(hDC);
	if(iBits<=1)   
		wBitCount = 1;   
	else if(iBits<=4)   
		wBitCount = 4;   
	else if(iBits<=8)   
		wBitCount = 8;
	else if(iBits<=24)   
		wBitCount = 24;
	else
		wBitCount = 32;
	//???????   
	if(wBitCount<=8)   
		dwPaletteSize = (1<<wBitCount)*sizeof(RGBQUAD);   

	//?????????
	GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&Bitmap);   
	bi.biSize = sizeof(BITMAPINFOHEADER);
	bi.biWidth = Bitmap.bmWidth;   
	bi.biHeight = Bitmap.bmHeight;   
	bi.biPlanes = 1;   
	bi.biBitCount = wBitCount;   
	bi.biCompression = BI_RGB;   
	bi.biSizeImage = 0;   
	bi.biXPelsPerMeter = 0;   
	bi.biYPelsPerMeter = 0;   
	bi.biClrUsed = 0;   
	bi.biClrImportant = 0;   

	dwBmBitsSize = ((Bitmap.bmWidth*wBitCount+31)/32)*4*Bitmap.bmHeight;   

	//?????????   
	hDib = GlobalAlloc(GHND,dwBmBitsSize+dwPaletteSize+sizeof(BITMAPINFOHEADER));   
	lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDib);   
	*lpbi = bi;   

	//   ?????         
	hPal = GetStockObject(DEFAULT_PALETTE);   
	if(hPal)
	{   
		hDC = ::GetDC(NULL);   
		hOldPal = SelectPalette(hDC, (HPALETTE)hPal, FALSE);   
		RealizePalette(hDC);  
	}   

	//   ????????????   
	GetDIBits(hDC, hBitmap, 0, (UINT)Bitmap.bmHeight,
		(LPSTR)lpbi+sizeof(BITMAPINFOHEADER)+dwPaletteSize,
		(LPBITMAPINFO)lpbi,DIB_RGB_COLORS);   

	//?????         
	if(hOldPal)
	{
		SelectPalette(hDC,(HPALETTE)hOldPal,TRUE);
		RealizePalette(hDC);
		::ReleaseDC(NULL, hDC);
	}   

	//??????           
	fh = CreateFile(lpFileName,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,
		FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,NULL);

	if(fh==INVALID_HANDLE_VALUE)
		return   FALSE;

	//   ???????   
	bmfHdr.bfType = 0x4D42;//   "BM"   
	dwDIBSize = sizeof(BITMAPFILEHEADER)+
		sizeof(BITMAPINFOHEADER)+
		dwPaletteSize+dwBmBitsSize;
	bmfHdr.bfSize = dwDIBSize;
	bmfHdr.bfReserved1 = 0;
	bmfHdr.bfReserved2 = 0;
	bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER)+
		(DWORD)sizeof(BITMAPINFOHEADER)+dwPaletteSize;

	//   ???????
	WriteFile(fh,(LPSTR)&bmfHdr,sizeof(BITMAPFILEHEADER),&dwWritten,NULL);
	//   ??????????
	WriteFile(fh,(LPSTR)lpbi,dwDIBSize,&dwWritten,NULL);

	//??????
	GlobalUnlock(hDib);
	GlobalFree(hDib);
	CloseHandle(fh);
	return   TRUE;
}
Exemplo n.º 23
0
static int SplitFileNameAndSave (
        const wchar_t *cur_dir,
        const wchar_t *file_name,
        PVOID unpack,
        DWORD file_length
        )
{
    DWORD ByteWrite;
    wchar_t buf[MAX_PATH] = {0}, buf2[MAX_PATH];

    StringCchCopy(buf, MAX_PATH, cur_dir);
    StringCchCat (buf, MAX_PATH, L"\\");
    StringCchCat (buf, MAX_PATH, file_name);

    int len = wcslen(buf);
    int i = wcslen(cur_dir) + 1;
    wchar_t *p = buf, *end = buf + len;
    while (p <= end && i < len)
    {
        while(buf[i] != '\\' && buf[i] != '/' && buf[i] != '\0') ++i;
        if (buf[i] == '/') buf[i] = '\\';
        if (i<len)
        {
            wchar_t tmp = buf[i];
            buf[i] = '\0';

            CreateDirectoryW(p, 0);
            buf[i] = tmp;
            ++i;
        }
    }

    HANDLE hFile;
    int ret = 0;
    do {
        hFile = CreateFile(buf, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
        if (hFile == INVALID_HANDLE_VALUE)
        {
            StringCchPrintf(buf2, MAX_PATH, L"[文件创建错误]%s\r\n", file_name);
            ret = ERR_FILE_CREATE;
            break;
        }

        WriteFile(hFile, unpack, file_length, &ByteWrite, NULL);

        if (ByteWrite != file_length)
        {
            StringCchPrintf(buf2, MAX_PATH, L"[文件写入错误]%s\r\n", file_name);
            ret = ERR_FILE_ERITE;
            break;
        }

        int t = GetLastError();
        if (!t || t == ERROR_ALREADY_EXISTS)
            StringCchPrintf(buf2, MAX_PATH, L"[已保存]%s\r\n", file_name);
        else
        {
            StringCchPrintf(buf2, MAX_PATH, L"[无法保存]%s\r\n", file_name);
            ret = ERR_FILE_OTHERS;
        }
    } while(0);

    AppendMsg(buf2);
    CloseHandle(hFile);
    return ret;
}
Exemplo n.º 24
0
/* This function is for implementation convenience. It is not user-visible.
 * If wr==1 write, wr==0 read.
 *
 * Returns MPI_SUCCESS on success, mpi_errno on failure.
 */
int ADIOI_NTFS_aio(ADIO_File fd, void *buf, int len, ADIO_Offset offset,
		   int wr, MPI_Request *request)
{
    static char myname[] = "ADIOI_NTFS_aio";

    ADIOI_AIO_Request *aio_req;
    static DWORD dwNumWritten, dwNumRead;
    BOOL ret_val = FALSE;
    FDTYPE fd_sys;
    int mpi_errno = MPI_SUCCESS;
    DWORD err;

    fd_sys = fd->fd_sys;

    aio_req = (ADIOI_AIO_Request *)ADIOI_Calloc(sizeof(ADIOI_AIO_Request), 1);
    if (aio_req == NULL)
    {
	mpi_errno = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
	    myname, __LINE__, MPI_ERR_IO,
	    "**nomem", "**nomem %s", "AIO_REQ");
	return mpi_errno;
    }
    aio_req->lpOvl = (LPOVERLAPPED ) ADIOI_Calloc(sizeof(OVERLAPPED), 1);
    if (aio_req->lpOvl == NULL)
    {
	mpi_errno = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
	    myname, __LINE__, MPI_ERR_IO,
	    "**nomem", "**nomem %s", "OVERLAPPED");
    ADIOI_Free(aio_req);
	return mpi_errno;
    }
    aio_req->lpOvl->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (aio_req->lpOvl->hEvent == NULL)
    {
    char errMsg[ADIOI_NTFS_ERR_MSG_MAX];
	err = GetLastError();
    ADIOI_NTFS_Strerror(err, errMsg, ADIOI_NTFS_ERR_MSG_MAX);
	mpi_errno = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
	    myname, __LINE__, MPI_ERR_IO,
	    "**io", "**io %s", errMsg);
    ADIOI_Free(aio_req->lpOvl);
    ADIOI_Free(aio_req);
	return mpi_errno;
    }
    aio_req->lpOvl->Offset = DWORDLOW(offset);
    aio_req->lpOvl->OffsetHigh = DWORDHIGH(offset);
    aio_req->fd = fd_sys;
    
    /* XXX: initiate async I/O  */
    if (wr)
    {
	ret_val = WriteFile(fd_sys, buf, len, &dwNumWritten, aio_req->lpOvl);
    }
    else
    {
	ret_val = ReadFile(fd_sys, buf, len, &dwNumRead, aio_req->lpOvl);
    }

    /* --BEGIN ERROR HANDLING-- */
    if (ret_val == FALSE) 
    {
	mpi_errno = GetLastError();
	if (mpi_errno != ERROR_IO_PENDING)
	{
        char errMsg[ADIOI_NTFS_ERR_MSG_MAX];
        ADIOI_NTFS_Strerror(mpi_errno, errMsg, ADIOI_NTFS_ERR_MSG_MAX);
	    mpi_errno = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
		myname, __LINE__, MPI_ERR_IO,
		"**io",
		"**io %s", errMsg);
	    return mpi_errno;
	}
	mpi_errno = MPI_SUCCESS;
    }
    /* --END ERROR HANDLING-- */

    /* XXX: set up generalized request class and request */
    if (ADIOI_NTFS_greq_class == 0) {
	    mpi_errno = MPIX_Grequest_class_create(ADIOI_NTFS_aio_query_fn,
			    ADIOI_NTFS_aio_free_fn, MPIU_Greq_cancel_fn,
			    ADIOI_NTFS_aio_poll_fn, ADIOI_NTFS_aio_wait_fn,
			    &ADIOI_NTFS_greq_class);
        if(mpi_errno != MPI_SUCCESS){
        /* FIXME: Pass appropriate error code to user */
        }
    }
    mpi_errno = MPIX_Grequest_class_allocate(ADIOI_NTFS_greq_class, aio_req, request);
    if(mpi_errno != MPI_SUCCESS){
    /* FIXME: Pass appropriate error code to user */
    }
    memcpy(&(aio_req->req), request, sizeof(MPI_Request));
    return mpi_errno;
}
Exemplo n.º 25
0
BOOL
OnApply(HWND hwnd, PSHNOTIFY* phdr)
{
	CSSHProperty::string_list* files = (CSSHProperty::string_list*)GetWindowLong(hwnd, GWL_USERDATA);
	HANDLE   hFile;

	CSSHProperty::string_list::iterator it = files->begin();

	for(; it != files->end(); ++it) {
		std::wstring file = *it + L":SSHFSProperty.Permission";
		hFile = CreateFile(
					file.c_str(),
					GENERIC_READ,
					FILE_SHARE_READ,
					NULL,
					OPEN_EXISTING,
					0,
					NULL);

		if (hFile == INVALID_HANDLE_VALUE)
			continue;

		char buffer[32];
		DWORD readBytes = 0;
		ZeroMemory(buffer, sizeof(buffer));
		if (!ReadFile(hFile, buffer, sizeof(buffer), &readBytes, NULL)) {
			CloseHandle(hFile);
			continue;
		}
		CloseHandle(hFile);

		int owner = buffer[0] - '0';
		UINT state;
		state = IsDlgButtonChecked(hwnd, IDC_W_EXEC);
		if (state == BST_CHECKED)
			owner |= 0x1;
		if (state == BST_UNCHECKED)
			owner &= ~0x1;
		
		state = IsDlgButtonChecked(hwnd, IDC_W_WRITE);
		if (state == BST_CHECKED)
			owner |= 0x2;
		if (state == BST_UNCHECKED)
			owner &= ~0x2;

		state = IsDlgButtonChecked(hwnd, IDC_W_READ);
		if (state == BST_CHECKED)
			owner |= 0x4;
		if (state == BST_UNCHECKED)
			owner &= ~0x4;


		int group = buffer[1] - '0';
		state = IsDlgButtonChecked(hwnd, IDC_G_EXEC);
		if (state == BST_CHECKED)
			group |= 0x1;
		if (state == BST_UNCHECKED)
			group &= ~0x1;
		
		state = IsDlgButtonChecked(hwnd, IDC_G_WRITE);
		if (state == BST_CHECKED)
			group |= 0x2;
		if (state == BST_UNCHECKED)
			group &= ~0x2;

		state = IsDlgButtonChecked(hwnd, IDC_G_READ);
		if (state == BST_CHECKED)
			group |= 0x4;
		if (state == BST_UNCHECKED)
			group &= ~0x4;


		int other = buffer[2] - '0';
		state = IsDlgButtonChecked(hwnd, IDC_O_EXEC);
		if (state == BST_CHECKED)
			other |= 0x1;
		if (state == BST_UNCHECKED)
			other &= ~0x1;
		
		state = IsDlgButtonChecked(hwnd, IDC_O_WRITE);
		if (state == BST_CHECKED)
			other |= 0x2;
		if (state == BST_UNCHECKED)
			other &= ~0x2;

		state = IsDlgButtonChecked(hwnd, IDC_O_READ);
		if (state == BST_CHECKED)
			other |= 0x4;
		if (state == BST_UNCHECKED)
			other &= ~0x4;


		char newpermission[32];
		ZeroMemory(newpermission, sizeof(newpermission));
		newpermission[0] = owner + '0';
		newpermission[1] = group + '0';
		newpermission[2] = other + '0';

		bool changed = false;
		for(int i=0; i<3; ++i)
			if(buffer[i] != newpermission[i])
				changed = true;

		buffer[3] = '\0';
		//DokanDbgPrint("SSHFSProperty: %s %s -> %s\n",
		//	file.c_str(), buffer, newpermission);

		if (changed) {
			hFile = CreateFile(
				file.c_str(),
				GENERIC_WRITE,
				FILE_SHARE_WRITE,
				NULL,
				OPEN_EXISTING,
				0,
				NULL);

			if (hFile == INVALID_HANDLE_VALUE)
				continue;

			DWORD writtenBytes = 0;
			WriteFile(hFile, newpermission, 3, &writtenBytes, NULL);
			CloseHandle(hFile);
		}

	}

    // Return PSNRET_NOERROR to allow the sheet to close if the user clicked OK.
    SetWindowLong(hwnd, DWL_MSGRESULT, PSNRET_NOERROR);
    return TRUE;
}
Exemplo n.º 26
0
//
// Each worker thread starts here.
DWORD WINAPI ThreadFunc(LPVOID pVoid)
{
    BOOL    bResult;
    DWORD   dwNumRead;
    struct ContextKey *pCntx;
    LPOVERLAPPED lpOverlapped;

    UNREFERENCED_PARAMETER(pVoid);

    // Loop forever on getting packets from
    // the I/O completion port.
    for (;;)
    {
        bResult = GetQueuedCompletionStatus(
                      ghCompletionPort,
                      &dwNumRead,
                      &(DWORD)pCntx,
                      &lpOverlapped,
                      INFINITE
                  );

        if (bResult == FALSE
                && lpOverlapped == NULL)
        {
            FatalError(
                "ThreadFunc - Illegal call to GetQueuedCompletionStatus");
        }

        else if (bResult == FALSE
                 && lpOverlapped != NULL)
        {
            // This happens occasionally instead of
            // end-of-file. Not sure why.
            closesocket(pCntx->sock);
            free(pCntx);
            fprintf(stderr,
                    "ThreadFunc - I/O operation failed\n");
        }

        else if (dwNumRead == 0)
        {
            closesocket(pCntx->sock);
            free(pCntx);
            fprintf(stderr, "ThreadFunc - End of file.\n");
        }

        // Got a valid data block!
        // Save the data to our buffer and write it
        // all back out (echo it) if we have see a \n
        else
        {
            // Figure out where in the buffer to save the character
            char *pch = &pCntx->OutBuffer[pCntx->nOutBufIndex++];
            *pch++ = pCntx->InBuffer[0];
            *pch = '\0';    // For debugging, WriteFile doesn't care
            if (pCntx->InBuffer[0] == '\n')
            {
                WriteFile(
                    (HANDLE)(pCntx->sock),
                    pCntx->OutBuffer,
                    pCntx->nOutBufIndex,
                    &pCntx->dwWritten,
                    &pCntx->ovOut
                );
                pCntx->nOutBufIndex = 0;
                fprintf(stderr, "Echo on socket %x.\n", pCntx->sock);
            }

            // Start a new read
            IssueRead(pCntx);
        }
    }

    return 0;
}
Exemplo n.º 27
0
BOOL CParseChText4::SaveChText(LPCWSTR filePath)
{
	wstring loadFilePath = L"";
	if( filePath == NULL ){
		loadFilePath = this->filePath;
	}else{
		loadFilePath = filePath;
	}

	if( loadFilePath.size() == 0 ){
		return FALSE;
	}

/*
	std::wregex re(L".+\\(.+)\(.+\)\.ChSet4\.txt$");
	
	
	std::wstring text(str);
	std::wsmatch m;

	if( std::regex_search(text, m, re) ) this->mpStartTimeShifting = m[1];
*/



	HANDLE hFile = _CreateFile2( loadFilePath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	if( hFile == INVALID_HANDLE_VALUE ){
		return FALSE;
	}

	multimap<LONGLONG, CH_DATA4> sortList;
	multimap<LONGLONG, CH_DATA4>::iterator itr;
	for( itr = this->chList.begin(); itr != this->chList.end(); itr++ ){
		LONGLONG Key = ((LONGLONG)itr->second.space)<<32 | ((LONGLONG)itr->second.ch)<<16 | (LONGLONG)itr->second.serviceID;
		sortList.insert(pair<LONGLONG, CH_DATA4>(Key, itr->second));
	}

	for( itr = sortList.begin(); itr != sortList.end(); itr++ ){
		string chName="";
		WtoA(itr->second.chName, chName);
		string serviceName="";
		WtoA(itr->second.serviceName, serviceName);
		string networkName="";
		WtoA(itr->second.networkName, networkName);

		string strBuff;
		Format(strBuff, "%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\r\n",
			chName.c_str(),
			serviceName.c_str(),
			networkName.c_str(),
			itr->second.space,
			itr->second.ch,
			itr->second.originalNetworkID,
			itr->second.transportStreamID,
			itr->second.serviceID,
			itr->second.serviceType,
			itr->second.partialFlag,
			itr->second.useViewFlag,
			itr->second.remoconID
			);
		DWORD dwWrite = 0;
		WriteFile(hFile, strBuff.c_str(), (DWORD)strBuff.length(), &dwWrite, NULL);
	}

	CloseHandle(hFile);
	return TRUE;
}
Exemplo n.º 28
0
//+ ----------------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	BYTE* pEvt;

	gpModuleName = GetProcessName(gModuleName, sizeof(gModuleName));

	if (gpModuleName == NULL)
		return -1;

	HANDLE hEventAppear = CreateEvent(NULL, FALSE, FALSE, NULL);
	if (hEventAppear == NULL)
		return -2;
	//+ ----------------------------------------------------------------------------------------
	//+ system test
#ifdef _check_system
	Log.AddToLog(L"Starting system interceptor check...\n");
	{
		CheckJob_System SystemJob(&gDrvEventList);
		if (false == SystemJob.Start())
		{
			Log.AddToLog(L"Can't start check system !");
			gDrvEventList.SetError(_ERR_DRVFAULT);
		}
		else
		{
			SystemJob.ChangeActiveStatus(true);
			
			//+ ----------------------------------------------------------------------------------------
			//+ open process
			HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
			if (hProcess != NULL)
			{
				Log.AddToLog(L"protection fault - process opened!");
				gDrvEventList.SetError(_ERR_DRVFAULT);
				CloseHandle(hProcess);
			}
			
			//+ ----------------------------------------------------------------------------------------
			//+ create process (ex)
			PROCESS_INFORMATION pi;
			STARTUPINFO si;
			
			ZeroMemory( &si, sizeof(si) );
			si.cb = sizeof(si);
			ZeroMemory( &pi, sizeof(pi) );
			
			WCHAR cmdline[1024];
			if (!ExpandEnvironmentStrings(L"\"%ComSpec%\" /C echo app launched!", cmdline, sizeof(cmdline)))
				gDrvEventList.SetError(_ERR_INTERNAL);
			else
			{
				if (CreateProcess(NULL, cmdline, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
				{
					Log.AddToLog(L"protection fault - process started!");
					gDrvEventList.SetError(_ERR_DRVFAULT);
					WaitForSingleObject(pi.hProcess,INFINITE);
				}
			}
			
			//+ ----------------------------------------------------------------------------------------
			//+ terminate process
			TerminateProcess((HANDLE) -1, -2);
			
			SystemJob.ChangeActiveStatus(false);
		}
		
		while ((pEvt = gDrvEventList.GetFirst()) != NULL)
		{
			Log.AddToLog((PEVENT_TRANSMIT) pEvt);
			gDrvEventList.Free(pEvt);
		}
	}
#endif

	//- end system test
	//- ----------------------------------------------------------------------------------------

	//+ ----------------------------------------------------------------------------------------
	//+ file test
#ifdef _check_file
	Log.AddToLog(L"Starting file interceptor check...\n");
	{

		CheckJob_File FileJob(&gDrvEventList);
		if (false == FileJob.Start())
		{
			Log.AddToLog(L"Can't start check file interceptor!");
			gDrvEventList.SetError(_ERR_DRVFAULT);
		}
		else
		{
			FileJob.SetAllowEvents(true);
			FileJob.ChangeActiveStatus(true);

	#define _testfilename			L"TestFile.tst"
	#define _testfilename_renamed	L"TestFile renamed.tst"
	#define _testfilename_create	L"TestFile check create.tst"

			HANDLE hTestFile = CreateFile(_testfilename, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hTestFile == INVALID_HANDLE_VALUE)
			{
				FileJob.ChangeActiveStatus(false);

				Log.AddToLog(L"Can't create file TestFile.tst for test");
				gDrvEventList.SetError(_ERR_DRVFAULT);

				FileJob.ChangeActiveStatus(true);
			}
			else
			{
				DWORD dwBytes;

				BYTE buf[1024];
				ZeroMemory(buf, sizeof(buf));

				WriteFile(hTestFile, buf, sizeof(buf), &dwBytes, NULL);
				if (dwBytes != sizeof(buf))
				{
					Log.AddToLog(L"!Write to TestFile.tst failed");
					gDrvEventList.SetError(_ERR_INTERNAL);
				}
				
				FlushFileBuffers(hTestFile);

				SetFilePointer(hTestFile, 0, NULL, FILE_BEGIN);

				ReadFile(hTestFile, buf, sizeof(buf), &dwBytes, NULL);
				if (dwBytes != sizeof(buf))
				{
					Log.AddToLog(L"!Read from TestFile.tst failed");
					gDrvEventList.SetError(_ERR_INTERNAL);
				}

				CloseHandle(hTestFile);
				
				MoveFile(_testfilename, _testfilename_renamed);

				DeleteFile(_testfilename_renamed);

				// check deny create file
				FileJob.SetAllowEvents(false);
				hTestFile = CreateFile(_testfilename_create, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL);
				if (hTestFile != INVALID_HANDLE_VALUE)
				{
					Log.AddToLog(L"protection fault - file "_testfilename_create L" opened");
					gDrvEventList.SetError(_ERR_DRVFAULT);
					CloseHandle(hTestFile);
				}
			}
			
			FileJob.ChangeActiveStatus(false);

			Sleep(100);
		}

		while ((pEvt = gDrvEventList.GetFirst()) != NULL)
		{
			Log.AddToLog((PEVENT_TRANSMIT) pEvt);
			gDrvEventList.Free(pEvt);
		}
	}
#endif
	//- end files test
	//- ----------------------------------------------------------------------------------------

	//+ ----------------------------------------------------------------------------------------
	//+ registry
#ifdef _check_regestry
	Log.AddToLog(L"Starting registry interceptor check...\n");
	{
		CheckJob_Reg RegJob(&gDrvEventList);
		if (false == RegJob.Start())
		{
			Log.AddToLog(L"Can't start check file interceptor!");
			gDrvEventList.SetError(_ERR_DRVFAULT);
		}
		else
		{
			RegJob.SetAllowEvents(true);
			RegJob.ChangeActiveStatus(true);

			HKEY hKey = NULL;
			if (ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, L"Software", &hKey))
			{
				DWORD type;
				DWORD cbData = 0;
				RegQueryValueEx(hKey, NULL, 0, &type, NULL, &cbData);

				RegCloseKey(hKey);

				//+ ----------------------------------------------------------------------------------------
				//+ enum
				{
					HKEY hKey;
					if(ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, L"SOFTWARE", &hKey))
					{
						TCHAR SubkeyName[512];
						DWORD dwSubkeyName = sizeof(SubkeyName);
						
						DWORD dwIndex = 0;
						
						if (RegEnumKey(hKey, dwIndex, SubkeyName, dwSubkeyName) == ERROR_SUCCESS)
						{
							// empty if
						}
						
						RegCloseKey(hKey);
					}
				}

				//+ ----------------------------------------------------------------------------------------

			}
			
			RegJob.ChangeActiveStatus(false);
		}

		while ((pEvt = gDrvEventList.GetFirst()) != NULL)
		{
			Log.AddToLog((PEVENT_TRANSMIT) pEvt);
			gDrvEventList.Free(pEvt);
		}
	}
#endif
	//- end registry test
	//- ----------------------------------------------------------------------------------------

	//+ ----------------------------------------------------------------------------------------
	//+ filter's queue - add (top, bottom, position), enumerate, /*find*/, enable, disable, delete, reset
#ifdef _check_flt
	Log.AddToLog(L"Starting check filtering system\n");
	{
		CheckJob_Flt FltJob(&gDrvEventList, hEventAppear);
		if (false == FltJob.Start())
		{
			Log.AddToLog(L"Can't start check filtering system!");
			gDrvEventList.SetError(_ERR_DRVFAULT);
		}
		else
		{
			VERDICT Verdict;
			byte SinglEevent[512];
			PFILTER_EVENT_PARAM pSignleEvt = (PFILTER_EVENT_PARAM) SinglEevent;
			ZeroMemory(SinglEevent, sizeof(SinglEevent));

			pSignleEvt->HookID = FLTTYPE_FLT;
			pSignleEvt->FunctionMj = 0;
			pSignleEvt->FunctionMi = 0;
			pSignleEvt->ParamsCount = 1;
			pSignleEvt->ProcessingType = PreProcessing;
			
			PSINGLE_PARAM pSingleParam = (PSINGLE_PARAM) pSignleEvt->Params;

			BYTE FltTransmit[4095];
			PFILTER_TRANSMIT pFlt = (PFILTER_TRANSMIT) FltTransmit;
			ZeroMemory(FltTransmit, sizeof(FltTransmit));

			FltJob.SetAllowEvents(true);
			if (false == FltJob.ChangeActiveStatus(true))
			{
				Log.AddToLog(L"Can't activate check filtering system!");
				gDrvEventList.SetError(_ERR_DRVFAULT);
			}
			else
			{
				Log.AddToLog(L"check filter's order...");

				ULONG FltArr[4] = {0};

				FltArr[1] = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_DEFAULT, 
					FLTTYPE_FLT, 0, 0, 0, PreProcessing, NULL, NULL);

				FltArr[3] = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_DEFAULT, 
					FLTTYPE_FLT, 0, 0, 0, PreProcessing, NULL, NULL);

				if (!FltArr[1] || !FltArr[3])
				{
					Log.AddToLog(L"Add filter to FLTTYPE_FLT failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					DWORD site = 0;
					FltArr[0] = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_DEFAULT, 
						FLTTYPE_FLT, 0, 0, 0, PreProcessing, &site, NULL);

					site = FltArr[1];
					FltArr[2] = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_DEFAULT, 
						FLTTYPE_FLT, 0, 0, 0, PreProcessing, &site, NULL);
				}

				if (!FltArr[0] || !FltArr[2])
				{
					Log.AddToLog(L"Add filter to FLTTYPE_FLT failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					pFlt->m_AppID = FltJob.m_AppID;
					pFlt->m_FltCtl = FLTCTL_FIRST;
					
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Enumerating filter's failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}
					else
					{
						int ienum = 0;
						pFlt->m_FltCtl = FLTCTL_NEXT;
						do
						{
							if (ienum > sizeof(FltArr) / sizeof(FltArr[0]))
							{
								Log.AddToLog(L"Filter's count mismatch!");
								gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
							}
							else
							{
								if (FltArr[ienum] != pFlt->m_FilterID)
								{
									Log.AddToLog(L"Filter's order mismatch!");
									gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
								}

								ienum++;
							}

						} while (TRUE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)));
					}
				}

				if (_ERR_DRVFAULT_FLT & gDrvEventList.m_ErrorFlags)
				{
					Log.AddToLog(L"further filter's check skipped - errors...");
				}
				else
				{
					Log.AddToLog(L"checking enable/disable...");
					pFlt->m_FilterID = FltArr[2];
					pFlt->m_FltCtl = FLTCTL_DISABLE_FILTER;
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Disable filter failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}

					pFlt->m_FltCtl = FLTCTL_ENABLE_FILTER;
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Enable filter failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}

					Log.AddToLog(L"checking delete/reset...");

					ResetEvent(hEventAppear);
					pFlt->m_FltCtl = FLTCTL_DEL;
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Delete filter failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}

					pFlt->m_FltCtl = FLTCTL_RESET_FILTERS;
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Reset filter failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}

					if (WAIT_OBJECT_0 != WaitForSingleObject(hEventAppear, 1000 * 60 * 3))	// 3 min
					{
						Log.AddToLog(L"Error: change filter's queue not detected!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}
				}
			}

#define _flt_timeout	20 /*sec*/
			Log.AddToLog(L"checking filter with timeout...");

			FILETIME STasFT;
			ULARGE_INTEGER ExpTime;
			
			GetSystemTimeAsFileTime(&STasFT);
			ExpTime.LowPart=STasFT.dwLowDateTime;
			ExpTime.HighPart=STasFT.dwHighDateTime;
			STasFT.dwLowDateTime=_flt_timeout;
			ExpTime.QuadPart=ExpTime.QuadPart+(LONGLONG)STasFT.dwLowDateTime * 6000000;	//600000000

			ULONG FltTimeout = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_INFO, 
					FLTTYPE_FLT, 0, 0, *((__int64*)&ExpTime), PreProcessing, NULL, NULL);
			if (FltTimeout == 0)
			{
				Log.AddToLog(L"Error: add filter with timeout failed!");
				gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
			}
			else
			{
				pSingleParam->ParamFlags = _SINGLE_PARAM_FLAG_NONE;
				pSingleParam->ParamID = _PARAM_OBJECT_URL_W;
				lstrcpy((PWCHAR)pSingleParam->ParamValue, L"this is test filter with timeout...");
				pSingleParam->ParamSize = (lstrlen((PWCHAR)pSingleParam->ParamValue) + 1) * sizeof(WCHAR);

				if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, FALSE, &Verdict))
				{
					Log.AddToLog(L"Error: check filter with timeout failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					Sleep((_flt_timeout + 1) * 1000);
					
					lstrcpy((PWCHAR)pSingleParam->ParamValue, L"Error: filter with timeout is present in queue after timeout!");
					pSingleParam->ParamSize = (lstrlen((PWCHAR)pSingleParam->ParamValue) + 1) * sizeof(WCHAR);

					if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, FALSE, &Verdict))
					{
						Log.AddToLog(L"Error: check filter with timeout failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}
				}
			}
	
			while ((pEvt = gDrvEventList.GetFirst()) != NULL)
			{
				Log.AddToLog((PEVENT_TRANSMIT) pEvt);
				gDrvEventList.Free(pEvt);
			}

			// params and cache
#define _test_params			20
			BYTE pbParams[_test_params][sizeof(FILTER_PARAM) + 0x100];
			ZeroMemory(pbParams, sizeof(pbParams));

			if (!(_ERR_DRVFAULT_FLT & gDrvEventList.m_ErrorFlags))
			{
				PFILTER_PARAM pArrFltParam[_test_params];

				// dword - FLT_PARAM_AND, FLT_PARAM_EUA, FLT_PARAM_ABV, FLT_PARAM_BEL, FLT_PARAM_MORE, FLT_PARAM_LESS, FLT_PARAM_MASK, FLT_PARAM_EQU_LIST
				// string - FLT_PARAM_WILDCARD

#define FltParam(_idx, _type, _value) { pArrFltParam[_idx] = (PFILTER_PARAM) pbParams[_idx];\
				pArrFltParam[_idx]->m_ParamFlags = _FILTER_PARAM_FLAG_CACHABLE;\
				pArrFltParam[_idx]->m_ParamFlt = _idx;\
				pArrFltParam[_idx]->m_ParamID = _idx;\
				pArrFltParam[_idx]->m_ParamSize = sizeof(_type);\
				*(_type*)(pArrFltParam[_idx]->m_ParamValue) = _value;}


				FltParam(FLT_PARAM_AND, BYTE, 1);
				FltParam(FLT_PARAM_ABV, DWORD, 50001);
				FltParam(FLT_PARAM_BEL, DWORD, 50001);
				FltParam(FLT_PARAM_MORE, DWORD, 0x2000003);
				FltParam(FLT_PARAM_LESS, DWORD, 0x2000003);

				ULONG FltTimeout = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_INFO | FLT_A_SAVE2CACHE | FLT_A_USECACHE | FLT_A_RESETCACHE, 
					FLTTYPE_FLT, 0, 0, 0, PreProcessing, NULL, 
					pArrFltParam[FLT_PARAM_AND], pArrFltParam[FLT_PARAM_ABV], 
					pArrFltParam[FLT_PARAM_BEL], pArrFltParam[FLT_PARAM_MORE], pArrFltParam[FLT_PARAM_LESS],
					NULL);

				if (FltTimeout == 0)
				{
					Log.AddToLog(L"Error: add filter with parameters failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					VERDICT VerdictOk, VerdictBad;
					
					pSingleParam->ParamFlags = _SINGLE_PARAM_FLAG_NONE;

#define _check_flt_op(_str, _op, _type, _val1, _val2) Log.AddToLog(L"Checking flt op " _str L"...");\
					pSingleParam->ParamID = _op;\
					*(_type*)pSingleParam->ParamValue = _val1;\
					pSingleParam->ParamSize = sizeof(_type);\
					if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, TRUE, &VerdictOk))\
						 VerdictOk = Verdict_Debug;\
					*(_type*)pSingleParam->ParamValue = _val2;\
					if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, TRUE, &VerdictBad))\
						 VerdictBad = Verdict_Debug;\
					if (VerdictOk != Verdict_Pass || VerdictBad != Verdict_NotFiltered)\
					{\
						Log.AddToLog(L"Flt operation" _str L" returned bad result");\
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);\
					}
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"AND", FLT_PARAM_AND, BYTE, 1, 2);
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"ABV", FLT_PARAM_ABV, DWORD, 50001, 50000);
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"BEL", FLT_PARAM_BEL, DWORD, 50001, 50002);
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"MORE", FLT_PARAM_MORE, DWORD, 0x2000003, 0x2000004);
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"LESS", FLT_PARAM_LESS, DWORD, 0x2000003, 0x2000002);
				}
			}
			
			if (!(_ERR_DRVFAULT_FLT & gDrvEventList.m_ErrorFlags))
			{
				pFlt->m_FltCtl = FLTCTL_RESET_FILTERS;
				if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
				{
					Log.AddToLog(L"Reset filter failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
			}
			
			if (!(_ERR_DRVFAULT_FLT & gDrvEventList.m_ErrorFlags))
			{
				PFILTER_PARAM pCacheParam = (PFILTER_PARAM) pbParams;
				pCacheParam->m_ParamFlags = _FILTER_PARAM_FLAG_CACHABLE;
				pCacheParam->m_ParamFlt = FLT_PARAM_WILDCARD;
				pCacheParam->m_ParamID = _PARAM_OBJECT_URL_W;
				lstrcpy((PWCHAR)pCacheParam->m_ParamValue, L"*");
				pCacheParam->m_ParamSize = (lstrlen((PWCHAR)pCacheParam->m_ParamValue) + 1) * sizeof(WCHAR);

				ULONG FltCache = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 0, FLT_A_POPUP | FLT_A_SAVE2CACHE | FLT_A_USECACHE, 
					FLTTYPE_FLT, 0, 0, 0, PreProcessing, NULL, pCacheParam, NULL);
				if (!FltCache)
				{
					Log.AddToLog(L"Error: can't add filter for checking cache!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					VERDICT Verdict1, Verdict2;
					pSignleEvt->ProcessingType = PreProcessing;
					
					pSingleParam->ParamFlags = _SINGLE_PARAM_FLAG_NONE;
					pSingleParam->ParamID = _PARAM_OBJECT_URL_W;
					lstrcpy((PWCHAR)pSingleParam->ParamValue, L"check cache (must be one such string in log!)");
					pSingleParam->ParamSize = (lstrlen((PWCHAR)pSingleParam->ParamValue) + 1) * sizeof(WCHAR);

					if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, FALSE, &Verdict1))
					{
						Log.AddToLog(L"Error: check driver cache!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}
					else
					{
						if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, FALSE, &Verdict2))
						{
							Log.AddToLog(L"Error: check driver cache (second event)!");
							gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
						}
						else
						{
							if ((Verdict1 != Verdict_Pass) || (Verdict2 != Verdict_Pass))
							{
								Log.AddToLog(L"Error: check driver cache failed!");
								gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
							}
						}
					}
				}
			}

 			FltJob.ChangeActiveStatus(false);

			while ((pEvt = gDrvEventList.GetFirst()) != NULL)
			{
				Log.AddToLog((PEVENT_TRANSMIT) pEvt);
				gDrvEventList.Free(pEvt);
			}
		}
	}
#endif
	//-
	//- ----------------------------------------------------------------------------------------

	Log.AddToLog(L"\nTest finished.");

	if (gDrvEventList.m_Errors)
	{
		WCHAR err[128];
		wsprintf(err, L"Errors %d, mask %x", gDrvEventList.m_Errors, gDrvEventList.m_ErrorFlags);
		Log.AddToLog(err);
		
		return gDrvEventList.m_ErrorFlags;
	}

	Log.AddToLog(L"\n\nNo errors.");
	
	return 0;
}
Exemplo n.º 29
0
static void translateinfstringex_test(void)
{
    HINF hinf;
    HRESULT hr;
    char buffer[MAX_PATH];
    DWORD size = MAX_PATH;

    create_inf_file();
    
    /* need to see if there are any flags */

    /* try a NULL filename */
    hr = pOpenINFEngine(NULL, "Options.NTx86", 0, &hinf, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try an empty filename */
    hr = pOpenINFEngine("", "Options.NTx86", 0, &hinf, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) /* NT+ */ ||
       hr == HRESULT_FROM_WIN32(E_UNEXPECTED) /* 9x */,
        "Expected HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND or E_UNEXPECTED), got %08x\n", hr);

    /* try a NULL hinf */
    hr = pOpenINFEngine(inf_file, "Options.NTx86", 0, NULL, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* open the INF without the Install section specified */
    hr = pOpenINFEngine(inf_file, NULL, 0, &hinf, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    /* try a NULL hinf */
    hr = pTranslateInfStringEx(NULL, inf_file, "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try a NULL filename */
    hr = pTranslateInfStringEx(hinf, NULL, "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try an empty filename */
    memset(buffer, 'a', 25);
    buffer[24] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, "", "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    todo_wine
    {
        ok(!strcmp(buffer, TEST_STRING2), "Expected %s, got %s\n", TEST_STRING2, buffer);
        ok(size == 25, "Expected size 25, got %d\n", size);
    }

    /* try a NULL translate section */
    hr = pTranslateInfStringEx(hinf, inf_file, NULL, "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try an empty translate section */
    hr = pTranslateInfStringEx(hinf, inf_file, "", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == SPAPI_E_LINE_NOT_FOUND, "Expected SPAPI_E_LINE_NOT_FOUND, got %08x\n", hr);

    /* try a NULL translate key */
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", NULL,
                              buffer, size, &size, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try an empty translate key */
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "",
                              buffer, size, &size, NULL);
    ok(hr == SPAPI_E_LINE_NOT_FOUND, "Expected SPAPI_E_LINE_NOT_FOUND, got %08x\n", hr);

    /* successfully translate the string */
    memset(buffer, 'a', 25);
    buffer[24] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    todo_wine
    {
        ok(!strcmp(buffer, TEST_STRING2), "Expected %s, got %s\n", TEST_STRING2, buffer);
        ok(size == 25, "Expected size 25, got %d\n", size);
    }

    /* try a NULL hinf */
    hr = pCloseINFEngine(NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* successfully close the hinf */
    hr = pCloseINFEngine(hinf);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    /* open the inf with the install section */
    hr = pOpenINFEngine(inf_file, "section", 0, &hinf, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    /* translate the string with the install section specified */
    memset(buffer, 'a', APP_PATH_LEN);
    buffer[APP_PATH_LEN - 1] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(!strcmp(buffer, APP_PATH), "Expected %s, got %s\n", APP_PATH, buffer);
    ok(size == APP_PATH_LEN, "Expected size %d, got %d\n", APP_PATH_LEN, size);

    /* Single quote test (Note size includes null on return from call) */
    memset(buffer, 'a', APP_PATH_LEN);
    buffer[APP_PATH_LEN - 1] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "Result1",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(!lstrcmpi(buffer, PROG_FILES_ROOT),
           "Expected %s, got %s\n", PROG_FILES_ROOT, buffer);
    ok(size == lstrlenA(PROG_FILES_ROOT)+1, "Expected size %d, got %d\n",
           lstrlenA(PROG_FILES_ROOT)+1, size);

    memset(buffer, 'a', APP_PATH_LEN);
    buffer[APP_PATH_LEN - 1] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "Result2",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(!lstrcmpi(buffer, PROG_FILES_ROOT),
           "Expected %s, got %s\n", PROG_FILES_ROOT, buffer);
    ok(size == lstrlenA(PROG_FILES_ROOT)+1, "Expected size %d, got %d\n",
           lstrlenA(PROG_FILES_ROOT)+1, size);

    {
        char drive[MAX_PATH];
        lstrcpy(drive, PROG_FILES_ROOT);
        drive[3] = 0x00; /* Just keep the system drive plus '\' */

        memset(buffer, 'a', APP_PATH_LEN);
        buffer[APP_PATH_LEN - 1] = '\0';
        size = MAX_PATH;
        hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "Result3",
                                  buffer, size, &size, NULL);
        ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
        ok(!lstrcmpi(buffer, drive),
               "Expected %s, got %s\n", drive, buffer);
        ok(size == lstrlenA(drive)+1, "Expected size %d, got %d\n",
               lstrlenA(drive)+1, size);
    }

    /* close the INF again */
    hr = pCloseINFEngine(hinf);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    DeleteFileA(inf_file);

    /* Create another .inf file which is just here to trigger a wine bug */
    {
        char data[1024];
        char *ptr = data;
        DWORD dwNumberOfBytesWritten;
        HANDLE hf = CreateFile(inf_file, GENERIC_WRITE, 0, NULL,
                           CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

        append_str(&ptr, "[Version]\n");
        append_str(&ptr, "Signature=\"$Chicago$\"\n");
        append_str(&ptr, "[section]\n");
        append_str(&ptr, "NotACustomDestination=Version\n");
        append_str(&ptr, "CustomDestination=CustInstDestSection\n");
        append_str(&ptr, "[CustInstDestSection]\n");
        append_str(&ptr, "49010=DestA,1\n");
        append_str(&ptr, "49020=DestB\n");
        append_str(&ptr, "49030=DestC\n");
        append_str(&ptr, "49040=DestD\n");
        append_str(&ptr, "[Options.NTx86]\n");
        append_str(&ptr, "Result2=%%49030%%\n");
        append_str(&ptr, "[DestA]\n");
        append_str(&ptr, "HKLM,\"Software\\Garbage\",\"ProgramFilesDir\",,'%%24%%'\n");
        /* The point of this test is to have HKCU just before the quoted HKLM */
        append_str(&ptr, "[DestB]\n");
        append_str(&ptr, "HKCU,\"Software\\Garbage\",\"ProgramFilesDir\",,'%%24%%'\n");
        append_str(&ptr, "[DestC]\n");
        append_str(&ptr, "'HKLM','Software\\Microsoft\\Windows\\CurrentVersion',");
        append_str(&ptr, "'ProgramFilesDir',,\"%%24%%\"\n");
        append_str(&ptr, "[DestD]\n");
        append_str(&ptr, "HKLM,\"Software\\Garbage\",\"ProgramFilesDir\",,'%%24%%'\n");

        WriteFile(hf, data, ptr - data, &dwNumberOfBytesWritten, NULL);
        CloseHandle(hf);
    }

    /* open the inf with the install section */
    hr = pOpenINFEngine(inf_file, "section", 0, &hinf, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    /* Single quote test (Note size includes null on return from call) */
    memset(buffer, 'a', APP_PATH_LEN);
    buffer[APP_PATH_LEN - 1] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "Result2",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(!lstrcmpi(buffer, PROG_FILES_ROOT),
           "Expected %s, got %s\n", PROG_FILES_ROOT, buffer);
    ok(size == lstrlenA(PROG_FILES_ROOT)+1, "Expected size %d, got %d\n",
           lstrlenA(PROG_FILES_ROOT)+1, size);

    /* close the INF again */
    hr = pCloseINFEngine(hinf);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    DeleteFileA(inf_file);
}
Exemplo n.º 30
0
int __cdecl main(int argc, char *argv[])
{
    const char* szStringTest = "1234567890";
    const char* szWritableFile = "writeable.txt";
    HANDLE hFile = NULL;
    DWORD dwBytesWritten;

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

    /* create the test file */ 
    hFile = CreateFile(szWritableFile, 
        GENERIC_WRITE,
        FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        Fail("WriteFile: ERROR -> Unable to create file \"%s\".\n", 
            szWritableFile);
    }


    /* test wtriting to the file */
    if( WriteFile(hFile,        /* HANDLE handle to file    */
        szStringTest,           /* data buffer              */
        strlen(szStringTest),   /* number of bytes to write */
        &dwBytesWritten,        /* number of bytes written  */
        NULL)                   /* overlapped buffer        */
        ==0)
    {
        Trace("WriteFile: ERROR -> Unable to write to file error: %ld \n",
            GetLastError());
        CleanUp(hFile,szWritableFile);
        Fail("");
    }

    if(!FlushFileBuffers(hFile))
    {   Trace("WriteFile: ERROR -> Call to FlushFile Buffers failed "
              "error %ld \n",GetLastError());
        CleanUp(hFile,szWritableFile);
        Fail("");        
    }

    /* check the file size */
    if(GetFileSize(hFile, NULL)!=strlen(szStringTest))
    {
        Trace("WriteFile: ERROR -> writing %u chars to empty file "
            "caused its size to become %u\n",strlen(szStringTest),
            GetFileSize(hFile, NULL));
        CleanUp(hFile,szWritableFile);        
        Fail("");
    }

    /* test writing to the file at position 5. */
    SetFilePointer(
        hFile,              /* handle to file           */
        0x5,                /* bytes to move pointer    */
        NULL,               /* bytes to move pointer    */
        FILE_BEGIN          /* starting point           */
        );


    if( WriteFile(hFile,        /* HANDLE handle to file    */
        szStringTest,           /* data buffer              */
        strlen(szStringTest),   /* number of bytes to write */
        &dwBytesWritten,        /* number of bytes written  */
        NULL)                   /* overlapped buffer        */
        ==0)
    {
        Trace("WriteFile: ERROR -> Unable to write to file after "
              " moiving the file poiner to 5 error: %ld \n",
              GetLastError());       
        CleanUp(hFile,szWritableFile);        
        Fail("");
    }


    if(!FlushFileBuffers(hFile))
    {
        Trace("WriteFile: ERROR -> Call to FlushFile Buffers failed "
              "error %ld \n",GetLastError());
        CleanUp(hFile,szWritableFile);
        Fail("");
    }

    /* Check the file size */
    if(GetFileSize(hFile, NULL)!=(strlen(szStringTest)+5))
    {
        Trace("WriteFile: ERROR -> writing %u chars to the file after "
              "sitting the file pointer to 5 resulted in wrong file size; "
              "Expected %u resulted %u.",strlen(szStringTest),
              (strlen(szStringTest)+5),GetFileSize(hFile, NULL));
        CleanUp(hFile,szWritableFile);
        Fail("");
    }

    if (!CleanUp(hFile,szWritableFile))
    {
        Fail("");
    }

    PAL_Terminate();
    return PASS;
}