/*
   File: readmbr.c
   Author: Devin Smith

   Desc:
   This is Windows specific code to read the MBR from the hard disk. 
*/

#include <windows.h>

static HANDLE hDiskVolume = NULL;
static ULONG SectorNumber = 0;
static BYTE SectorBuffer[512];

static void printUsage();



static void printUsage()
{
   printf("readmbr - devin smith.\n");
   printf("usage: readmbr mbr.bin\n\n");
   printf("writes output to mbr.bin\n");
}


int main(int argc, char *argv[])
{
   DWORD dwNumberOfBytesRead;
   DWORD dwNumberOfBytesWritten;
   DWORD dwFilePosition;
   BOOL	bRetVal;
   HANDLE hBackupFile;

   if(argc < 2)
   {
      printUsage();
      return 0;
   }

   hDiskVolume = CreateFile("\\\\.\\C:", GENERIC_READ | GENERIC_WRITE,
		   FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 
		   OPEN_EXISTING, 0, NULL);

   if (hDiskVolume == INVALID_HANDLE_VALUE)
   {
      printf("(%s:%d) Error opening drive 0.\n", __FILE__, __LINE__);
      return -1;
   }


   dwFilePosition = SetFilePointer(hDiskVolume, (SectorNumber * 512), NULL, FILE_BEGIN);
   if (dwFilePosition != (SectorNumber * 512))
   {
      printf("(%s:%d) SetFilePointer() failed. Error code %ld.\n", __FILE__,
		      __LINE__, GetLastError());
      CloseHandle(hDiskVolume);
      return -1;
   }
	
   bRetVal = ReadFile(hDiskVolume, SectorBuffer, 512, &dwNumberOfBytesRead, NULL);
   if (!bRetVal || (dwNumberOfBytesRead != 512))
   {
      printf("(%s:%d) ReadFile() failed. Error code %ld.\n", __FILE__,
		      __LINE__, GetLastError());
      CloseHandle(hDiskVolume);
      return -1;
   }
   CloseHandle(hDiskVolume);

   hBackupFile = CreateFile(argv[1], GENERIC_WRITE, 0, NULL, CREATE_NEW, /*FILE_ATTRIBUTE_SYSTEM*/0, NULL);
   if (hBackupFile == INVALID_HANDLE_VALUE)
   {
      printf("(%s:%d) Error creating file %s.\n", __FILE__, __LINE__, argv[1]);
      if(GetLastError() != ERROR_ALREADY_EXISTS)
         printf("(%s:%d) File already exists.\n", __FILE__, __LINE__);
      else
	 printf("(%s:%d) Unknown problem. Error code %ld.\n", __FILE__,
			 __LINE__, GetLastError());
      return -1;
   }
   bRetVal = WriteFile(hBackupFile, SectorBuffer, 512, &dwNumberOfBytesWritten, NULL);
   if (!bRetVal || (dwNumberOfBytesWritten != 512))
   {
      printf("(%s:%d) WriteFile() failed. Error code %ld.\n", __FILE__,
		      __LINE__, GetLastError());
      CloseHandle(hBackupFile);
      return -1;
   }

   CloseHandle(hBackupFile);

   printf("Boot sector written to %s\n", argv[1]);

   return 0;
}
