WriteFile writing filename to file - c++

I'm getting quite a strange problem.
I'm hooking to the Winsock function on the Xbox 360, send. This function is called a-lot in the application I'm trying to dump the Http Request information from.
First I will show the code and explain my issue:
WritetoFile function.
BOOL WritetoFile(char* filename, char* buffer, DWORD len)
{
// Setup expansion
doMountPath("Hdd:", "\\Device\\Harddisk0\\Partition1");
//print
printf("Creating %s\n", filename);
//create our file
HANDLE fileHandle = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
//does file exist?
if(fileHandle!=INVALID_HANDLE_VALUE)
{
//print
printf("Writing to file... \n");
//bytes written parameter
DWORD wfbr;
//write to our file
if(WriteFile(fileHandle, (void*)&buffer, len, &wfbr, NULL))
{
printf("File written! (Bytes Written:%u) \n", wfbr);
} else {
printf("Error writing to file: (Error:%u)\n", GetLastError());
}
//close our file handle
CloseHandle(fileHandle);
} else {
printf("Error creating file: (Error:%u)\n", GetLastError());
}
return true;
}
Winsock hook
INT WINSOCK_SEND_HOOK(SOCKET s,const char FAR *buf,int len,int flags)
{
memcpy(SocketData.SendData, buf, len);
if(len>40)
{
WINSOCK_SEND_COUNT +=1;
char Filename[40];
sprintf(Filename, "Hdd:\\Dump\\Send\\Winsock_Send_%d.txt", WINSOCK_SEND_COUNT);
WritetoFile(Filename, SocketData.SendData, len);
} else { printf("Winsock skipped\n"); }
memset(SocketData.SendData, 0, 0x1388);
return send(s, buf, len, flags);
}
The problem is pretty difficult to explain. So the first time I ran my .dll to hook onto this function it worked fine up until tries to create 'Winsock_Send_85.txt'. It prints this:
`Creating b0ZEK0EwSDBwSXR2RW5EdXd5ZXFnN1IrLzFQYno4RmN0ZnI2MnNnWWQwb2JXMGlYbEdQRkxGOXFkdHJabiszb1I2MG1vUFlkSjBJVW0xcFB4UzZxWEtqZEVYSjEvQmJtOHhmMUdVMDlZaHA2SUtWZTJjb0ZVU1RsUTlvYXJhc0NDOHJNUitlUDBaQmVSOTNUWVM1TU1hLzB0NlhGZmQ2dE1CVDRKVTRxdzliRUtlRmVvVGgvaVdoMUFBczBpNzhkcXNlVUYwaTlQT3B5ekdyeU9ZTzU0QWYyVXpUSXZiTDMzRWl4SXhzOUJOZDZxaWtDQUlNQmZkNHRYVTNaS2pKZngxRmd3dXE2QnRIYmkySlgxcE9vUjFyVlRpci9iZHdTZTZEOTJDSXFqNkNqM0lSaDY1N3VKUzhOQ3VxaFZpclhTUnZMZlJCN21mTS9aV2dCRUJNWHBVeUdZcGxqOVNGUÿÿexception code=0xc0000005 thread=0xf9000044 address=0x910d0a00 read=0x910d0a00 firstxbWatson: Xbox is restarting`
And crashes. After restarting the console I then run it again and it works fine and doesnt crash but it's now writing the incorrect data to the files which is all the same repetitive data even though the buffer points to different data. This is what it writes to file:
‘ÀÛ( W
ÿÿÿÿÿÿÿÿ ÿÿÿÿ‘Á Hdd:\Dump\Send\Winsock_Send_87.txt  ‚i夀…Ü H>
I then discovered a way to stop this from happening which was to unplug the console entirely from all power but then it goes back to the first issue.
Please ignore what you may think be un-necessary uses of memcpy.

The problem was solved pretty quickly (embarrassing) and I cant believe I was struggling with this for 1 hour, silly mistake.
I wasn't checking the size of the buffer therefore I wasn't allocating enough memory.

Related

Why are these 2 sectors different?

i tried to read ntfs partition.
main function:
int main(int argc, char** argv)
{
BYTE sector[512];
ReadSector(L"\\\\.\\E:", 0, sector);
PrintBPB(ReadBPB(sector));
BYTE sector2[512];
ReadSector(L"\\\\.\\E:", 0, sector2);
PrintBPB(ReadBPB(sector2));
return 0;
}
ReadSector function:
int ReadSector(LPCWSTR drive, long readPoint, BYTE sector[Sector_Size])
{
int retCode = 0;
DWORD bytesRead;
HANDLE device = NULL;
device = CreateFile(drive, // Drive to open
GENERIC_READ, // Access mode
FILE_SHARE_READ | FILE_SHARE_WRITE, // Share Mode
NULL, // Security Descriptor
OPEN_EXISTING, // How to create
0, // File attributes
NULL); // Handle to template
if (device == INVALID_HANDLE_VALUE) // Open Error
{
printf("CreateFile: %u\n", GetLastError());
return 1;
}
SetFilePointer(device, readPoint, NULL, FILE_BEGIN);//Set a Point to Read
if (!ReadFile(device, sector, 512, &bytesRead, NULL))
{
printf("ReadFile: %u\n", GetLastError());
}
else
{
printf("Success!\n");
}
CloseHandle(device);
}
I think the way I copy those bytes into my BPB bpb is fine.
So what happend? Why they are different?
I can figure out that its relate to winapi, readfile, createfile but I still dont understand it :(
sorry for my bad english.
The bug is in the code we cannot see: PrintBPB. Apparently it switches to hexadecimal output (for the "Volume serial number") and then fails to switch back to decimal until later.
When the code calls PrintBPB a second time the output mode is still in hexadecimal format, and printing "Bytes per Sector" now displays 200 (0x200 is the same value as 512).
If you need to know whether two chunks of memory hold identical values, just memcmp them. This avoids introducing a bug in a transformation (such as console output).

Crash when calling ReadFile after LockFileEx

I have several processes that try to read and write the same file. I want each of them to lock the file so that only one of them accesses it at a time.
I tried this (edit: this is a complete test code this time):
#include "stdafx.h"
#include "Windows.h"
bool test()
{
const char* path = "test.txt";
HANDLE hFile = CreateFileA(path,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("ERROR: Cannot open file %s\n", path);
return false;
}
// Lock the file
{
OVERLAPPED overlapped = {0};
BOOL res = LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK, 0, ~0, ~0, &overlapped);
if (!res)
{
printf("ERROR: Cannot lock file %s\n", path);
return false;
}
}
DWORD fileSize = GetFileSize(hFile, NULL);
if (fileSize > 0)
{
char* content = new char[fileSize+1];
// Read the file
BOOL res = ReadFile(hFile, content, fileSize, NULL, NULL);
if (!res)
{
printf("ERROR: Cannot read file %s\n", path);
}
delete[] content;
}
const char* newContent = "bla";
int newContentSize = 3;
// Write the file
BOOL res = WriteFile(hFile, newContent, newContentSize, NULL, NULL);
if (!res)
{
//int err = GetLastError();
printf("ERROR: Cannot write to file\n");
}
// Unlock the file
{
OVERLAPPED overlapped = {0};
UnlockFileEx(hFile, 0, ~0, ~0, &overlapped);
}
CloseHandle(hFile);
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
bool res = test();
return 0;
}
This works fine on my computer, which has Windows 8. But on my colleague's computer, which has Windows 7, it crashes. Specifically, the calls to ReadFile and WriteFile crash, always.
Note that it never enters the code paths with the error printfs. This code triggers no error except for a write at location 0x00000000 in ReadFile (when run on Windows 7).
We tried to also pass the overlapped struct to the ReadFile and WriteFile calls. It prevents the crash but the lock doesn't work anymore, the file is all scrambled (not with this test code, with the real code).
What am I doing wrong?
Looks like your problem is:
lpNumberOfBytesRead [out, optional] argument is null in your call.
This parameter can be NULL only when the lpOverlapped parameter is not NULL.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467%28v=vs.85%29.aspx
Heres your problem :
You are missing a necessary struct-member and:
0 and ~0 and {0} are all bad code, constant expressions like these will always produce unepected results -- WINAPI doesnt work like libc, parameters are not always compared against constants, instead they are tested against/via macros and other preprocessor-definitions themselves so passing constant values or initializing WINAPI structs with constants will often lead to errors like these.
After years of experimenting i have found that there is only one surefire way of avoiding them, i will express it in corrected code :
OVERLAPPED overlapped;
overlapped.hEvent = CreateEvent( ........... ); // put valid parameters here!
UnlockFileEx(hFile, 0 /*"reserved"*/, ULONG_MAX, ULONG_MAX, &overlapped);
please read this carefully : http://msdn.microsoft.com/en-us/library/windows/desktop/aa365716%28v=vs.85%29.aspx

C++ WriteFile only writing 4 bytes

Here's what I'm trying to achieve; I'm hooking onto the HttpSendRequest function (on Xbox it's XHttp) and trying dump the certificate that's in pcszHeaders which has the size of 0x1F0E.
Now the problem; it only seems to write 4 bytes, I've even tried allocating extra memory and setting each bit to 0 to see if it's the size of Headers and it continues to only write 4 bytes. I've been able to dump pcszHeaders remotely because I got the address whilst debugging but I need to dump it at run-time.
Something I notice whilst debugging - The address of pcszHeaders only shows in locals until it reaches;
printf("XHttpSendRequest: %s\n", "Creating Certificate.bin...");
Once it reaches the printf() above the address changes to 0x00000000 (bad ptr) but it still writes the first byte of correct data of pcszHeaders correctly but nothing more.
Here is the entire hook;
BOOL XHTTP_SEND_REQUEST_HOOK(
HINTERNET hRequest,
const CHAR *pcszHeaders,
DWORD dwHeadersLength,
const VOID *lpOptional,
DWORD dwOptionalLength,
DWORD dwTotalLength,
DWORD_PTR dwContext)
{
if(pcszHeaders != XHTTP_NO_ADDITIONAL_HEADERS)
{
printf("XHttpSendRequest: %s\n", "Creating Certificate.bin...");
// Setup expansion
doMountPath("Hdd:", "\\Device\\Harddisk0\\Partition1");
//create our file
HANDLE fileHandle = CreateFile("Hdd:\\Certificate.bin", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
//does file exist?
if(GetLastError()!=ERROR_ALREADY_EXISTS
||fileHandle!=INVALID_HANDLE_VALUE)
{
printf("XHttpSendRequest: %s\n", "Writing to file...");
DWORD wfbr;
//write to our file
if(WriteFile(fileHandle, pcszHeaders, 0x2000, &wfbr, NULL))
{
printf("XHttpSendRequest: %s\n", "File written!");
printf("%s\n", "Request has ended.");
CloseHandle(fileHandle);
return XHttpSendRequest(hRequest, pcszHeaders, dwHeadersLength, lpOptional, dwOptionalLength, dwTotalLength, dwContext);
}
}
}
}
EDIT: I've changed the code slightly and I've copied pcszHeaders data into another section of memory that I've created and my pointers seems to have all the correct data and I've tried Writing it to file and it still only writes 4 bytes. I've even used sizeof() instead of hard-coded 0x2000.
pcszHeaders is a char* pointer. sizeof(pcszHeaders) is 4 in a 32bit app (8 in a 64bit app). You need to use the dwHeadersLength parameter instead, which tells you how many characters are in pcszHeaders.
Also, your GetLastError() check after CreateFile() is wrong. If CreateFile() fails for any reason other than ERROR_ALREADY_EXISTS, you are entering the code block and thus writing data to an invalid file handle. When using CREATE_NEW, CreateFile() returns INVALID_HANDLE_VALUE if the file already exists. You don't need to check GetLastError() for that, checking for INVALID_HANDLE_VALUE by itself is enough. If you want to overwrite the existing file, use CREATE_ALWAYS instead.
You are also leaking the file handle if WriteFile() fails.
And you are calling the original HttpSendRequest() only if you successfully write headers to your file. If there are no headers, or the create/write fails, you are not allowing the request to proceed. Is that what you really want?
Try this instead:
BOOL XHTTP_SEND_REQUEST_HOOK(
HINTERNET hRequest,
const CHAR *pcszHeaders,
DWORD dwHeadersLength,
const VOID *lpOptional,
DWORD dwOptionalLength,
DWORD dwTotalLength,
DWORD_PTR dwContext)
{
if (pcszHeaders != XHTTP_NO_ADDITIONAL_HEADERS)
{
printf("XHttpSendRequest: Creating Certificate.bin...\n");
// Setup expansion
doMountPath("Hdd:", "\\Device\\Harddisk0\\Partition1");
//create our file
HANDLE fileHandle = CreateFile("Hdd:\\Certificate.bin", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
//is file open?
if (fileHandle != INVALID_HANDLE_VALUE)
{
printf("XHttpSendRequest: Writing to file...\n");
DWORD wfbr;
//write to our file
if (WriteFile(fileHandle, pcszHeaders, dwHeadersLength, &wfbr, NULL))
printf("XHttpSendRequest: File written!\n");
else
printf("XHttpSendRequest: Error writing to file: %u\n", GetLastError());
CloseHandle(fileHandle);
}
else
printf("XHttpSendRequest: Error creating file: %u\n", GetLastError());
}
printf("Request has ended.\n");
return XHttpSendRequest(hRequest, pcszHeaders, dwHeadersLength, lpOptional, dwOptionalLength, dwTotalLength, dwContext);
}
Finally the problem has been solved!
First I created an empty array for the data to be stored.
CHAR xtoken[0x2000];
memset(xtoken, 0, 0x2000);
The first part of the hook is to store the header data.
DWORD bufferLength = dwHeadersLength;
memcpy(xtoken, pcszHeaders, bufferLength);
I then write the data to file
WriteFile(fileHandle, (void*)&xtoken, bufferLength, &wfbr, NULL))
Success! I guess the problem was that parameter 2 of WriteFile() was incorrect.

Can't write to a mailslot on a pc while it's ok on some others

First of all i appologize for my bad english because i'm not english :)
I wanted to use mailslots from vb.net. I'm quite noob about mailslots, not sure on how they works. Had some difficulties and ended to basic testing in simple c++ win32 code to firstly understand how it works without caring about vb managed/unmanaged stuff. I used vs 2010 in a virtual machine.
Here is the problem: i finally realized that my basic test program works fine on several computers but not on my developpement computer... I don't have any idea on what could be the cause and what i have to check.
Here is the code:
#include <stdio.h>
#include <Windows.h>
void main()
{
HANDLE hservslot;
HANDLE hclislot;
hservslot = CreateMailslot("\\\\.\\mailslot\\testingslot", 0, 0, NULL);
if (hservslot == INVALID_HANDLE_VALUE)
{
printf("CreateMailslot error : %d", GetLastError());
getchar();
return;
}
hclislot = CreateFile("\\\\*\\mailslot\\testingslot", GENERIC_WRITE, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);
if (hclislot == INVALID_HANDLE_VALUE)
{
CloseHandle(hservslot);
printf("CreateFile error : %d", GetLastError());
getchar();
return;
}
BOOL fResult;
DWORD cbWritten;
BYTE buff[4] = {0,1,2,3};
fResult = WriteFile(hclislot, buff , 4, &cbWritten, (LPOVERLAPPED) NULL);
if (fResult)
{
printf("Slot written to successfully.\n");
}
else
{
printf("WriteFile failed with %d.\n", GetLastError());
}
getchar();
CloseHandle(hclislot);
CloseHandle(hservslot);
}
On my computer i get the "WriteFile failed with 53" (which means "The network path was not found." according to msdn doc). On some other computers, including the virtual one, i get "Slot written to successfully."
Any idea on wich direction i should search the "bug" to fix it ?
Thx.
Edit: By the way, all the pc, including vm, are on windows 7 pro 64 bits.

how in C++ send file to browser

I need to send file from my directory to user. The problem file was not send.
Can any one help me?
My code is like:
CHttpServerContext* pCtxt;
// ... there i set headers for open
DWORD dwRead;
CString fileName = "c:\txt.doc";
HANDLE hFile = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ,
(LPSECURITY_ATTRIBUTES) NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, (HANDLE) NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
int c = 0;
CHAR szBuffer [2048];
do
{
if (c++ > 20) {
break;
return;
}
// read chunk of the file
if (!ReadFile (hFile, szBuffer, 2048, &dwRead, NULL))
{
return;
}
if (!dwRead)
// EOF reached, bail out
break;
// Send binary chunk to the browser
if (!pCtxt->WriteClient( szBuffer, &dwRead, 0))
{
return;
}
}
while (1);
CloseHandle (hFile);
}
Doctor, I'm sick. What's wrong with me?
I mean, you give almost no information about what happened.
Do you know if some function returned you an error in your code?
Why do you abort the loop after 20 iterations? This limits you to 40KB.
How exactly do you initialize CHttpServerContext?
You might use high-performance TransmitFile function if you just send the file as-is.
What is your client? How do you know it didn't get the file?
No point in re-inventing the wheel - just use the TransmitFile API instead - it is built into CHttpServerContent::TransmitFile().