//-------------------------------------------------------------------------------------------------------------- // Starts a new download if there are queued requests void DownloadManager::StartNewDownload() { if ( m_activeRequest || !m_queuedRequests.Count() ) return; while ( !m_activeRequest && m_queuedRequests.Count() ) { // Remove one request from the queue and make it active m_activeRequest = m_queuedRequests[0]; m_queuedRequests.Remove( 0 ); if ( g_pFileSystem->FileExists( m_activeRequest->gamePath ) ) { ConDColorMsg( DownloadColor, "Skipping existing file %s%s.\n", m_activeRequest->baseURL, m_activeRequest->gamePath ); m_activeRequest->shouldStop = true; m_activeRequest->threadDone = true; m_completedRequests.AddToTail( m_activeRequest ); m_activeRequest = NULL; } } if ( !m_activeRequest ) return; if ( g_pFileSystem->FileExists( m_activeRequest->gamePath ) ) { m_activeRequest->shouldStop = true; m_activeRequest->threadDone = true; m_completedRequests.AddToTail( m_activeRequest ); m_activeRequest = NULL; return; // don't download existing files } if ( m_activeRequest->bAsHTTP ) { // Check cache for partial match TheDownloadCache->GetCachedData( m_activeRequest ); //TODO: ContinueLoadingProgressBar( "Http", m_totalRequests - m_queuedRequests.Count(), 0.0f ); //TODO: SetLoadingProgressBarStatusText( "#GameUI_VerifyingAndDownloading" ); //TODO: SetSecondaryProgressBarText( m_activeRequest->gamePath ); //TODO: SetSecondaryProgressBar( 0.0f ); UpdateProgressBar(); ConDColorMsg( DownloadColor, "Downloading %s%s.\n", m_activeRequest->baseURL, m_activeRequest->gamePath ); m_lastPercent = 0; // Start the thread DWORD threadID; VCRHook_CreateThread(NULL, 0, DownloadThread, m_activeRequest, 0, &threadID ); } else { UpdateProgressBar(); ConDColorMsg( DownloadColor, "Downloading %s.\n", m_activeRequest->gamePath ); m_lastPercent = 0; m_activeRequest->nRequestID = cl.m_NetChannel->RequestFile( m_activeRequest->gamePath ); } }
BOOL WriteSector (void *dev, char *sector, char *write_buf, int *write_buf_cnt, __int64 *nSecNo, PCRYPTO_INFO cryptoInfo) { static __int32 updateTime = 0; (*nSecNo)++; memcpy (write_buf + *write_buf_cnt, sector, FormatSectorSize); (*write_buf_cnt) += FormatSectorSize; if (*write_buf_cnt == FormatWriteBufferSize && !FlushFormatWriteBuffer (dev, write_buf, write_buf_cnt, nSecNo, cryptoInfo)) return FALSE; if (GetTickCount () - updateTime > 25) { if (UpdateProgressBar (*nSecNo * FormatSectorSize)) return FALSE; updateTime = GetTickCount (); } return TRUE; }
bool DownloadManager::FileReceived( const char *filename, unsigned int requestID ) { if ( !m_activeRequest ) return false; if ( m_activeRequest->nRequestID != requestID ) return false; if ( m_activeRequest->bAsHTTP ) return false; ConDColorMsg( DownloadCompleteColor, "Download finished!\n" ); UpdateProgressBar(); m_completedRequests.AddToTail( m_activeRequest ); m_activeRequest = NULL; return true; }
void nsTopProgressManager::Tick(void) { TRACE_PROGRESS(("nsProgressManager.Tick: aggregating information for active objects\n")); AggregateTransferInfo info = { 0, 0, 0, 0, 0, 0, 0 }; PL_HashTableEnumerateEntries(fURLs, pm_AggregateTransferInfo, (void*) &info); TRACE_PROGRESS(("nsProgressManager.Tick: %ld of %ld objects complete, " "%ldms left, " "%ld of %ld bytes xferred\n", info.CompleteCount, info.ObjectCount, info.MSecRemaining, info.BytesReceived, info.ContentLength)); PR_ASSERT(info.ObjectCount > 0); if (info.ObjectCount == 0) return; UpdateProgressBar(info); UpdateStatusMessage(info); // Check to see if we're done. if (info.CompleteCount == info.ObjectCount) { TRACE_PROGRESS(("Complete: %ld/%ld objects loaded\n", info.CompleteCount, info.ObjectCount)); // XXX needs to go to allxpstr.h FE_Progress(fContext, " "); PL_HashTableDestroy(fURLs); fURLs = NULL; fTimeout = NULL; } else { // Reset the timeout to fire again... fTimeout = FE_SetTimeout(nsTopProgressManager::TimeoutCallback, (void*) this, 500); } }
bool DownloadManager::FileDenied( const char *filename, unsigned int requestID ) { if ( !m_activeRequest ) return false; if ( m_activeRequest->nRequestID != requestID ) return false; if ( m_activeRequest->bAsHTTP ) return false; ConDColorMsg( DownloadErrorColor, "Error downloading %s\n", m_activeRequest->gamePath ); UpdateProgressBar(); // try to download the next file m_completedRequests.AddToTail( m_activeRequest ); m_activeRequest = NULL; return true; }
void CNB_Vote_Panel::UpdateVote() { UpdateVotePanelStatus(); UpdateVisibility(); if ( m_VotePanelStatus == VPS_NONE ) return; UpdateProgressBar(); if ( m_VotePanelStatus == VPS_VOTE ) { UpdateVoteLabels(); } else if ( m_VotePanelStatus == VPS_RESTART ) { UpdateRestartLabels(); } else if ( m_VotePanelStatus == VPS_TECH_FAIL ) { UpdateTechFailLabels(); } }
int FormatNoFs (HWND hwndDlg, unsigned __int64 startSector, __int64 num_sectors, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat) { int write_buf_cnt = 0; char sector[TC_MAX_VOLUME_SECTOR_SIZE], *write_buf; unsigned __int64 nSecNo = startSector; int retVal = 0; DWORD err; char temporaryKey[MASTER_KEYDATA_SIZE]; char originalK2[MASTER_KEYDATA_SIZE]; LARGE_INTEGER startOffset; LARGE_INTEGER newOffset; // Seek to start sector startOffset.QuadPart = startSector * FormatSectorSize; if (!SetFilePointerEx ((HANDLE) dev, startOffset, &newOffset, FILE_BEGIN) || newOffset.QuadPart != startOffset.QuadPart) { return ERR_OS_ERROR; } write_buf = (char *)TCalloc (FormatWriteBufferSize); if (!write_buf) return ERR_OUTOFMEMORY; VirtualLock (temporaryKey, sizeof (temporaryKey)); VirtualLock (originalK2, sizeof (originalK2)); memset (sector, 0, sizeof (sector)); // Remember the original secondary key (XTS mode) before generating a temporary one memcpy (originalK2, cryptoInfo->k2, sizeof (cryptoInfo->k2)); /* Fill the rest of the data area with random data */ if(!quickFormat) { /* Generate a random temporary key set to be used for "dummy" encryption that will fill the free disk space (data area) with random data. This is necessary for plausible deniability of hidden volumes. */ // Temporary master key if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE)) goto fail; // Temporary secondary key (XTS mode) if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) goto fail; retVal = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); if (retVal != ERR_SUCCESS) goto fail; if (!EAInitMode (cryptoInfo)) { retVal = ERR_MODE_INIT_FAILED; goto fail; } while (num_sectors--) { if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo) == FALSE) goto fail; } if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) goto fail; } else nSecNo = num_sectors; UpdateProgressBar (nSecNo * FormatSectorSize); // Restore the original secondary key (XTS mode) in case NTFS format fails and the user wants to try FAT immediately memcpy (cryptoInfo->k2, originalK2, sizeof (cryptoInfo->k2)); // Reinitialize the encryption algorithm and mode in case NTFS format fails and the user wants to try FAT immediately retVal = EAInit (cryptoInfo->ea, cryptoInfo->master_keydata, cryptoInfo->ks); if (retVal != ERR_SUCCESS) goto fail; if (!EAInitMode (cryptoInfo)) { retVal = ERR_MODE_INIT_FAILED; goto fail; } burn (temporaryKey, sizeof(temporaryKey)); burn (originalK2, sizeof(originalK2)); VirtualUnlock (temporaryKey, sizeof (temporaryKey)); VirtualUnlock (originalK2, sizeof (originalK2)); TCfree (write_buf); return 0; fail: err = GetLastError(); burn (temporaryKey, sizeof(temporaryKey)); burn (originalK2, sizeof(originalK2)); VirtualUnlock (temporaryKey, sizeof (temporaryKey)); VirtualUnlock (originalK2, sizeof (originalK2)); TCfree (write_buf); SetLastError (err); return (retVal ? retVal : ERR_OS_ERROR); }
VOID WINAPI WorkerThreadHashFile( PCOMMONCONTEXT pcmnctx, PCTSTR pszPath, PBOOL pbSuccess, PWHCTXEX pwhctx, PWHRESULTEX pwhres, PBYTE pbuffer, PFILESIZE pFileSize, LPARAM lParam, PCRITICAL_SECTION pUpdateCritSec, volatile ULONGLONG* pcbCurrentMaxSize #ifdef _TIMED , PDWORD pdwElapsed #endif ) { HANDLE hFile; *pbSuccess = FALSE; // If the worker thread is working so fast that the UI cannot catch up, // pause for a bit to let things settle down while (pcmnctx->cSentMsgs > pcmnctx->cHandledMsgs + 50) { Sleep(50); if (pcmnctx->status == PAUSED) WaitForSingleObject(pcmnctx->hUnpauseEvent, INFINITE); if (pcmnctx->status == CANCEL_REQUESTED) return; } // Indicate that we want lower-case results (TODO: make this an option) pwhctx->uCaseMode = WHFMT_LOWERCASE; if ((hFile = OpenFileForReading(pszPath)) != INVALID_HANDLE_VALUE) { ULONGLONG cbFileSize, cbFileRead = 0; DWORD cbBufferRead; UINT lastProgress = 0; UINT8 cInner = 0; if (GetFileSizeEx(hFile, (PLARGE_INTEGER)&cbFileSize)) { // The progress bar is updates only once every 4 buffer reads; if // the file is small enough that it requires only one such cycle, // then do not bother with updating the progress bar; this improves // performance when working with large numbers of small files BOOL bUpdateProgress = cbFileSize >= READ_BUFFER_SIZE * 4, bCurrentlyUpdating = FALSE; // If the caller provides a way to return the file size, then set // the file size; send a SETSIZE notification only if it was "big" if (pFileSize) { pFileSize->ui64 = cbFileSize; StrFormatKBSize(cbFileSize, pFileSize->sz, countof(pFileSize->sz)); if (cbFileSize > READ_BUFFER_SIZE) PostMessage(pcmnctx->hWnd, HM_WORKERTHREAD_SETSIZE, (WPARAM)pcmnctx, lParam != -1 ? lParam : (LPARAM)pFileSize); } #ifdef _TIMED DWORD dwStarted; if (pdwElapsed) dwStarted = GetTickCount(); #endif // Finally, read the file and calculate the checksum; the // progress bar is updated only once every 4 buffer reads (512K) WHInitEx(pwhctx); do // Outer loop: keep going until the end { do // Inner loop: break every 4 cycles or if the end is reached { if (pcmnctx->status == PAUSED) WaitForSingleObject(pcmnctx->hUnpauseEvent, INFINITE); if (pcmnctx->status == CANCEL_REQUESTED) { CloseHandle(hFile); return; } ReadFile(hFile, pbuffer, READ_BUFFER_SIZE, &cbBufferRead, NULL); WHUpdateEx(pwhctx, pbuffer, cbBufferRead); cbFileRead += cbBufferRead; } while (cbBufferRead == READ_BUFFER_SIZE && (++cInner & 0x03)); if (bUpdateProgress) UpdateProgressBar(pcmnctx->hWndPBFile, pUpdateCritSec, &bCurrentlyUpdating, pcbCurrentMaxSize, cbFileSize, cbFileRead, &lastProgress); } while (cbBufferRead == READ_BUFFER_SIZE); WHFinishEx(pwhctx, pwhres); #ifdef _TIMED if (pdwElapsed) *pdwElapsed = GetTickCount() - dwStarted; #endif if (cbFileRead == cbFileSize) *pbSuccess = TRUE; if (bUpdateProgress) UpdateProgressBar(pcmnctx->hWndPBFile, pUpdateCritSec, &bCurrentlyUpdating, pcbCurrentMaxSize, cbFileSize, 0, &lastProgress); } CloseHandle(hFile); } }
TInt DoZipDownload(RFile &aBootFile) { TZipInfo z; z.iRemain=FileSize; InitProgressBar(0,(TUint)FileSize,_L("LOAD")); TInt r=Initialise(z); CHECK(r); RThread t; t.SetHandle(z.iThreadHandle); while (z.iRemain && z.iThreadStatus==KRequestPending) { TRequestStatus dummy; TRequestStatus* pS=&dummy; r=ReadBlockToBuffer(z, aBootFile); if (r != KErrNone) { PrintToScreen(_L("FAULT: Unzip Error %d\r\n"),r); if (z.iFileBufW-z.iFileBufR==z.iFileBufSize) { PrintToScreen(_L("Check there is only one image\n\rin the zip file.\r\n")); } CHECK(r); } UpdateProgressBar(0,(TUint)(FileSize-z.iRemain)); t.RequestComplete(pS,0); // same process while(z.iHeaderDone==0 && z.iThreadStatus==KRequestPending) { DELAY(20000); } if (z.iHeaderDone==1 && z.iThreadStatus==KRequestPending) { // after reading first block, process the header ProcessHeader(z); } } // while User::WaitForRequest(z.iThreadStatus); TInt exitType=t.ExitType(); TInt exitReason=t.ExitReason(); if (z.iRemain || exitType!=EExitKill || exitReason!=KErrNone) { TBuf<32> exitCat=t.ExitCategory(); PrintToScreen(_L("Exit code %d,%d,%S\n"),exitType,exitReason,&exitCat); TEST(0); } PrintToScreen(_L("Unzip complete\r\n")); TUint8* pD=Buffer; TInt len=1024; r=ReadInputData(pD,len); TEST(r==KErrEof); DELAY(20000); Cleanup(z); return KErrNone; }
/* ExpandVolume Sets the volume size in the volume header (and backup header) to a larger value, and resizes the filesystem within the volume (only NTFS supported) Parameters: hwndDlg : HWND [in] handle to progress dialog lpszVolume : char * [in] Pointer to a string that contains the path to the truecrypt volume pVolumePassword : Password * [in] Pointer to the volume password newHostSize : uint64 [in] new value of the volume host size (can be zero for devices, which means the volume should use all space of the host device) initFreeSpace : BOOL [in] if true, the new volume space will be initalized with random data Return value: int with Truecrypt error code (ERR_SUCCESS on success) Remarks: a lot of code is from TrueCrypt 'Common\Password.c' :: ChangePwd() */ static int ExpandVolume (HWND hwndDlg, wchar_t *lpszVolume, Password *pVolumePassword, int VolumePkcs5, int VolumePim, uint64 newHostSize, BOOL initFreeSpace) { int nDosLinkCreated = 1, nStatus = ERR_OS_ERROR; wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; wchar_t szDosDevice[TC_MAX_PATH]; char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; PCRYPTO_INFO cryptoInfo = NULL, ci = NULL; void *dev = INVALID_HANDLE_VALUE; DWORD dwError; BOOL bDevice; uint64 hostSize=0, newDataAreaSize, currentVolSize; DWORD HostSectorSize; FILETIME ftCreationTime; FILETIME ftLastWriteTime; FILETIME ftLastAccessTime; BOOL bTimeStampValid = FALSE; LARGE_INTEGER headerOffset; BOOL backupHeader; byte *wipeBuffer = NULL; uint32 workChunkSize = TC_VOLUME_HEADER_GROUP_SIZE; if (pVolumePassword->Length == 0) return -1; WaitCursor (); CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), lpszVolume, &bDevice); if (bDevice == FALSE) { wcscpy (szCFDevice, szDiskFile); } else { nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice), FALSE); if (nDosLinkCreated != 0) // note: nStatus == ERR_OS_ERROR goto error; } dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (dev == INVALID_HANDLE_VALUE) goto error; if (bDevice) { /* This is necessary to determine the hidden volume header offset */ if (dev == INVALID_HANDLE_VALUE) { goto error; } else { PARTITION_INFORMATION diskInfo; DWORD dwResult; BOOL bResult; bResult = GetPartitionInfo (lpszVolume, &diskInfo); if (bResult) { hostSize = diskInfo.PartitionLength.QuadPart; HostSectorSize = TC_SECTOR_SIZE_FILE_HOSTED_VOLUME; //TO DO: get the real host disk sector size } else { DISK_GEOMETRY driveInfo; bResult = DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveInfo, sizeof (driveInfo), &dwResult, NULL); if (!bResult) goto error; hostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; HostSectorSize = driveInfo.BytesPerSector; } if (hostSize == 0) { nStatus = ERR_VOL_SIZE_WRONG; goto error; } } } else { LARGE_INTEGER fileSize; if (!GetFileSizeEx (dev, &fileSize)) { nStatus = ERR_OS_ERROR; goto error; } hostSize = fileSize.QuadPart; HostSectorSize = TC_SECTOR_SIZE_FILE_HOSTED_VOLUME; //TO DO: get the real host disk sector size } if (Randinit ()) { if (CryptoAPILastError == ERROR_SUCCESS) nStatus = ERR_RAND_INIT_FAILED; else nStatus = ERR_CAPI_INIT_FAILED; goto error; } if (!bDevice && bPreserveTimestamp) { /* Remember the container modification/creation date and time, (used to reset file date and time of file-hosted volumes after password change (or attempt to), in order to preserve plausible deniability of hidden volumes (last password change time is stored in the volume header). */ if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) { bTimeStampValid = FALSE; MessageBoxW (hwndDlg, GetString ("GETFILETIME_FAILED_PW"), lpszTitle, MB_OK | MB_ICONEXCLAMATION); } else bTimeStampValid = TRUE; } // Seek the volume header headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET; if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) { nStatus = ERR_OS_ERROR; goto error; } /* Read in volume header */ nStatus = _lread ((HFILE) dev, buffer, sizeof (buffer)); if (nStatus != sizeof (buffer)) { // Windows may report EOF when reading sectors from the last cluster of a device formatted as NTFS memset (buffer, 0, sizeof (buffer)); } /* Try to decrypt the header */ nStatus = ReadVolumeHeader (FALSE, buffer, pVolumePassword, VolumePkcs5, VolumePim, FALSE, &cryptoInfo, NULL); if (nStatus == ERR_CIPHER_INIT_WEAK_KEY) nStatus = 0; // We can ignore this error here if (nStatus != 0) { cryptoInfo = NULL; goto error; } if (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_ENCRYPTED_SYSTEM) { nStatus = ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG; goto error; } if (bDevice && newHostSize == 0) { // this means we shall take all host space as new volume size newHostSize = hostSize; } if ( newHostSize % cryptoInfo->SectorSize != 0 || newHostSize > TC_MAX_VOLUME_SIZE || (bDevice && newHostSize > hostSize) ) { // 1. must be multiple of sector size // 2. truecrypt volume size limit // 3. for devices volume size can't be larger than host size cryptoInfo = NULL; nStatus = ERR_PARAMETER_INCORRECT; goto error; } newDataAreaSize = GetVolumeDataAreaSize (newHostSize, cryptoInfo->LegacyVolume); if (cryptoInfo->LegacyVolume) { if (bDevice) { if (initFreeSpace) { // unsupported cryptoInfo = NULL; nStatus = ERR_PARAMETER_INCORRECT; goto error; } else { // note: dummy value (only used for parameter checks) cryptoInfo->VolumeSize.Value = newDataAreaSize - TC_MINVAL_FS_EXPAND; } } else { cryptoInfo->VolumeSize.Value = GetVolumeDataAreaSize (hostSize, TRUE); } } currentVolSize = GetVolumeSizeByDataAreaSize (cryptoInfo->VolumeSize.Value, cryptoInfo->LegacyVolume); if ( newDataAreaSize < cryptoInfo->VolumeSize.Value + TC_MINVAL_FS_EXPAND ) { // shrinking a volume or enlarging by less then TC_MINVAL_FS_EXPAND is not allowed cryptoInfo = NULL; nStatus = ERR_PARAMETER_INCORRECT; goto error; } InitProgressBar ( newHostSize, currentVolSize, FALSE, FALSE, FALSE, TRUE); if (bVolTransformThreadCancel) { SetLastError(0); nStatus = ERR_USER_ABORT; goto error; } if (!bDevice) { LARGE_INTEGER liNewSize; liNewSize.QuadPart=(LONGLONG)newHostSize; // Preallocate the file if (!SetFilePointerEx (dev, liNewSize, NULL, FILE_BEGIN) || !SetEndOfFile (dev) || SetFilePointer (dev, 0, NULL, FILE_BEGIN) != 0) { nStatus = ERR_OS_ERROR; goto error; } } if (initFreeSpace) { uint64 startSector; int64 num_sectors; // fill new space with random data startSector = currentVolSize/HostSectorSize ; num_sectors = (newHostSize/HostSectorSize) - startSector; if (bDevice && !StartFormatWriteThread()) { nStatus = ERR_OS_ERROR; goto error; } DebugAddProgressDlgStatus(hwndDlg, L"Writing random data to new space ...\r\n"); SetFormatSectorSize(HostSectorSize); nStatus = FormatNoFs (hwndDlg, startSector, num_sectors, dev, cryptoInfo, FALSE); dwError = GetLastError(); StopFormatWriteThread(); SetLastError (dwError); } else { UpdateProgressBar(newHostSize); } if (nStatus != ERR_SUCCESS) { dwError = GetLastError(); DebugAddProgressDlgStatus(hwndDlg, L"Error: failed to write random data ...\r\n"); if ( !bDevice ) { // restore original size of the container file LARGE_INTEGER liOldSize; liOldSize.QuadPart=(LONGLONG)hostSize; if (!SetFilePointerEx (dev, liOldSize, NULL, FILE_BEGIN) || !SetEndOfFile (dev)) { DebugAddProgressDlgStatus(hwndDlg, L"Warning: failed to restore original size of the container file\r\n"); } } SetLastError (dwError); goto error; } RandSetHashFunction (cryptoInfo->pkcs5); // Re-encrypt the volume header forn non-legacy volumes: backup header first backupHeader = TRUE; headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET + newHostSize - TC_VOLUME_HEADER_GROUP_SIZE; /* note: updating the header is not neccessary for legay volumes */ while ( !cryptoInfo->LegacyVolume ) { if (backupHeader) DebugAddProgressDlgStatus(hwndDlg, L"Writing re-encrypted backup header ...\r\n"); else DebugAddProgressDlgStatus(hwndDlg, L"Writing re-encrypted primary header ...\r\n"); // Prepare new volume header nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, buffer, cryptoInfo->ea, cryptoInfo->mode, pVolumePassword, cryptoInfo->pkcs5, VolumePim, (char*)(cryptoInfo->master_keydata), &ci, newDataAreaSize, 0, // hiddenVolumeSize cryptoInfo->EncryptedAreaStart.Value, newDataAreaSize, cryptoInfo->RequiredProgramVersion, cryptoInfo->HeaderFlags, cryptoInfo->SectorSize, TRUE ); // use slow poll if (ci != NULL) crypto_close (ci); if (nStatus != 0) goto error; if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) { nStatus = ERR_OS_ERROR; goto error; } nStatus = _lwrite ((HFILE) dev, buffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); if (nStatus != TC_VOLUME_HEADER_EFFECTIVE_SIZE) { nStatus = ERR_OS_ERROR; goto error; } if ( ( backupHeader && !initFreeSpace ) || ( bDevice && !cryptoInfo->LegacyVolume && !cryptoInfo->hiddenVolume && cryptoInfo->HeaderVersion == 4 // BUG in TrueCrypt: doing this only for v4 make no sense && (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0 && (cryptoInfo->HeaderFlags & ~TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0 ) ) { //DebugAddProgressDlgStatus(hwndDlg, L"WriteRandomDataToReservedHeaderAreas() ...\r\n"); nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, newDataAreaSize, !backupHeader, backupHeader); if (nStatus != ERR_SUCCESS) goto error; } FlushFileBuffers (dev); if (!backupHeader) break; backupHeader = FALSE; headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET; // offset for main header } /* header successfully updated */ nStatus = ERR_SUCCESS; if (bVolTransformThreadCancel) { nStatus = ERR_USER_ABORT; goto error; } /* wipe old backup header */ if ( !cryptoInfo->LegacyVolume ) { byte wipeRandChars [TC_WIPE_RAND_CHAR_COUNT]; byte wipeRandCharsUpdate [TC_WIPE_RAND_CHAR_COUNT]; byte wipePass; UINT64_STRUCT unitNo; LARGE_INTEGER offset; WipeAlgorithmId wipeAlgorithm = TC_WIPE_35_GUTMANN; if ( !RandgetBytes (hwndDlg, wipeRandChars, TC_WIPE_RAND_CHAR_COUNT, TRUE) || !RandgetBytes (hwndDlg, wipeRandCharsUpdate, TC_WIPE_RAND_CHAR_COUNT, TRUE) ) { nStatus = ERR_OS_ERROR; goto error; } DebugAddProgressDlgStatus(hwndDlg, L"Wiping old backup header ...\r\n"); wipeBuffer = (byte *) TCalloc (workChunkSize); if (!wipeBuffer) { nStatus = ERR_OUTOFMEMORY; goto error; } offset.QuadPart = currentVolSize - TC_VOLUME_HEADER_GROUP_SIZE; unitNo.Value = offset.QuadPart; for (wipePass = 1; wipePass <= GetWipePassCount (wipeAlgorithm); ++wipePass) { if (!WipeBuffer (wipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, workChunkSize)) { ULONG i; for (i = 0; i < workChunkSize; ++i) { wipeBuffer[i] = wipePass; } EncryptDataUnits (wipeBuffer, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, cryptoInfo); memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); } if ( !SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) || _lwrite ((HFILE)dev, (LPCSTR)wipeBuffer, workChunkSize) == HFILE_ERROR ) { // Write error DebugAddProgressDlgStatus(hwndDlg, L"Warning: Failed to wipe old backup header\r\n"); MessageBoxW (hwndDlg, L"WARNING: Failed to wipe old backup header!\n\nIt may be possible to use the current volume password to decrypt the old backup header even after a future password change.\n", lpszTitle, MB_OK | MB_ICONEXCLAMATION); if (wipePass == 1) continue; // retry once // non-critical error - it's better to continue nStatus = ERR_SUCCESS; goto error; } FlushFileBuffers(dev); // we don't check FlushFileBuffers() return code, because it fails for devices // (same implementation in password.c - a bug or not ???) } burn (wipeRandChars, TC_WIPE_RAND_CHAR_COUNT); burn (wipeRandCharsUpdate, TC_WIPE_RAND_CHAR_COUNT); } error: dwError = GetLastError (); if (wipeBuffer) { burn (wipeBuffer, workChunkSize); TCfree (wipeBuffer); wipeBuffer = NULL; } burn (buffer, sizeof (buffer)); if (cryptoInfo != NULL) crypto_close (cryptoInfo); if (bTimeStampValid) { // Restore the container timestamp (to preserve plausible deniability of possible hidden volume). if (SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) MessageBoxW (hwndDlg, GetString ("SETFILETIME_FAILED_PW"), lpszTitle, MB_OK | MB_ICONEXCLAMATION); } if (dev != INVALID_HANDLE_VALUE) CloseHandle ((HANDLE) dev); if (nDosLinkCreated == 0) RemoveFakeDosName (szDiskFile, szDosDevice); RandStop (FALSE); if (bVolTransformThreadCancel) nStatus = ERR_USER_ABORT; SetLastError (dwError); if (nStatus == ERR_SUCCESS) { nStatus = ExtendFileSystem (hwndDlg, lpszVolume, pVolumePassword, VolumePkcs5, VolumePim, newDataAreaSize); } return nStatus; }
void MaxAWDExporter::ProcessGeoBlocks() { AWDTriGeom *geoBlock; AWDBlockIterator *it; int proccessed=0; it = new AWDBlockIterator(awd->get_mesh_data_blocks()); UpdateProgressBar(MAXAWD_PHASE_PROCESS_GEOMETRY, (double)proccessed/(double)awd->get_mesh_data_blocks()->get_num_blocks()); INodeTab lNodes; while ((geoBlock = (AWDTriGeom * ) it->next()) != NULL){ INode * node = (INode *)INodeToGeoBlockCache->Get(geoBlock); if (node==NULL){ AWDMessageBlock * newWarning = new AWDMessageBlock(geoBlock->get_name(), "ERROR: Could not find the INode for this AWDGeometry."); awd->get_message_blocks()->append(newWarning); return; } lNodes.AppendNode( node ); } IGameScene* _pIgame = NULL; _pIgame = GetIGameInterface(); _pIgame->InitialiseIGame( lNodes ); it->reset(); while ((geoBlock = (AWDTriGeom * ) it->next()) != NULL){ INode * node = (INode *)INodeToGeoBlockCache->Get(geoBlock); if (node==NULL){ AWDMessageBlock * newWarning = new AWDMessageBlock(geoBlock->get_name(), "ERROR: Could not find the INode for this AWDGeometry."); awd->get_message_blocks()->append(newWarning); } else{ int exportThis=false; IGameObject * gobj = NULL; IGameMesh * igame_mesh = NULL; gobj = GetIGameInterface()->GetIGameNode(node)->GetIGameObject(); if(gobj->GetIGameType()==IGameObject::IGAME_MESH){ igame_mesh = (IGameMesh*)gobj; if (igame_mesh!=NULL){ igame_mesh->InitializeData(); if(igame_mesh->GetNumberOfFaces()>0){ exportThis=true; } } } if (exportThis){ Object *obj; obj = node->GetObjectRef(); int skinIdx; ObjectState os; IDerivedObject *derivedObject = NULL; skinIdx = IndexOfSkinMod(node->GetObjectRef(), &derivedObject); if (skinIdx >= 0) { // Flatten all modifiers up to but not including // the skin modifier. // to do: get the correct time for the neutral-pose os = derivedObject->Eval(0, skinIdx + 1); } else { // Flatten entire modifier stack // to do: get the correct time for the neutral-pose os = node->EvalWorldState(maxInterface->GetTime()); } obj = os.obj; ISkin *skin = NULL; if (derivedObject != NULL && skinIdx >= 0) { Modifier *mod = derivedObject->GetModifier(skinIdx); skin = (ISkin *)mod->GetInterface(I_SKIN); } ExportTriGeom(geoBlock,obj,node,skin, igame_mesh); RETURN_IF_ERROR; } } proccessed++; UpdateProgressBar(MAXAWD_PHASE_PROCESS_GEOMETRY, (double)proccessed/(double)awd->get_mesh_data_blocks()->get_num_blocks()); } delete it; _pIgame->ReleaseIGame(); }
void CLoadingScreen::LoadingProgressCallback(ELoadingProgressTask eTask, float fProgress, void* pUser) { // No need to update content info if a different screen is being rendered... if( m_pRenderScreen ) return; EnterCriticalSection(&m_MissionUpdate); static float fWeights[eLoadingProgressTask_NumTasks] = { 0.05f, //eLoadingProgressTask_WorldBsp, 0.15f, //eLoadingProgressTask_Objects, 0.80f, //eLoadingProgressTask_Assets, 0.00f, //eLoadingProgressTask_User0, 0.00f, //eLoadingProgressTask_User1, 0.00f, //eLoadingProgressTask_User2, 0.00f, //eLoadingProgressTask_User3, 0.00f, //eLoadingProgressTask_User4, 0.00f, //eLoadingProgressTask_User5, 0.00f, //eLoadingProgressTask_User6, 0.00f, //eLoadingProgressTask_User7, }; float fCurrWt = fWeights[eTask] * fProgress; UpdateProgressBar(m_fLoadProgress + fCurrWt); if (fProgress == 1.0f) { m_fLoadProgress += fWeights[eTask]; } /* DebugCPrint(0,"%s progress = %0.2f",__FUNCTION__,m_fLoadProgress); switch(eTask) { case eLoadingProgressTask_WorldBsp: DebugCPrint(0,"%s (eLoadingProgressTask_WorldBsp) %0.2f : %0.2f",__FUNCTION__,fProgress, (clock() / (float)CLOCKS_PER_SEC)); break; case eLoadingProgressTask_Objects: DebugCPrint(0,"%s (eLoadingProgressTask_Objects) %0.2f : %0.2f",__FUNCTION__,fProgress,(clock() / (float)CLOCKS_PER_SEC)); break; case eLoadingProgressTask_Assets: DebugCPrint(0,"%s (eLoadingProgressTask_Assets) %0.2f : %0.2f",__FUNCTION__,fProgress,(clock() / (float)CLOCKS_PER_SEC)); break; default: if (eTask >= eLoadingProgressTask_User0 && eTask < eLoadingProgressTask_User7) { DebugCPrint(0,"%s (eLoadingProgressTask_User) %0.2f : %0.2f",__FUNCTION__,fProgress,(clock() / (float)CLOCKS_PER_SEC)); } break; } */ LeaveCriticalSection(&m_MissionUpdate); Update(); // let GameClientShell perform any progress related processing g_pGameClientShell->OnWorldLoadingProgress(); }
bool CLoadingScreen::Init() { if (m_eCurState != STATE_NONE) return false; // DebugCPrint(0,"%s : SettingCallback : %0.2f",__FUNCTION__,(clock() / (float)CLOCKS_PER_SEC)); m_dlgClientLoggedIn.Attach(this,g_pClientConnectionMgr,g_pClientConnectionMgr->ClientLoggedInEvent); g_pLTClient->LoadingProgress()->SetLoadingCallback( LoadingProgressCallbackFn , this); m_fLoadProgress = 0.0f; if( m_pRenderScreen ) { // Just let the render screen know it is about to be draw and set the state to init... m_pRenderScreen->OnFocus( true ); m_eCurState = STATE_INIT; return true; } m_photo = ""; m_bHaveServerInfo = false; CFontInfo Font(g_pLayoutDB->GetHelpFont(),12); nAlpha = 255; bFade = true; CLTGUICtrl_create cs; m_MissionName.Create(L"",Font,cs); m_LevelName.Create(L"",Font,cs); m_Briefing.Create(L"",Font,cs); m_ServerMsg.Create(L"",Font,cs); m_BriefingHeader.Create(LoadString("LoadScreen_Briefing"),Font,cs); m_ServerMsgHeader.Create(LoadString("LoadScreen_ServerMessage"),Font,cs); m_Help.Create(L"",Font,cs); m_CurrentFileName.Create(L"",Font,cs); m_CurrentFileTime.Create(L"",Font,cs); m_FilesLeft.Create(L"",Font,cs); m_TotalTime.Create(L"",Font,cs); HRECORD hMission = NULL; if( !g_pMissionMgr->IsCustomLevel( )) { uint32 nCurMission = g_pMissionMgr->GetCurrentMission( ); hMission = g_pMissionDB->GetMission( nCurMission ); } // Check if we have a mission entry. if (IsMultiplayerGameClient()) { m_layout = g_pLayoutDB->GetLoadScreenRecord("DefaultMP"); m_Briefing.SetClipping(true); } else { m_layout = g_pLayoutDB->GetLoadScreenRecord("Default"); m_Briefing.SetClipping(false); } if (!g_DefaultLayout.m_bReadLayout) { g_DefaultLayout.Read(g_pLayoutDB->GetLoadScreenRecord("Default")); } if( hMission ) { ReadMissionInfo(hMission); UpdateServerInfo(); } if (!g_CurrentLayout.Read(m_layout)) g_CurrentLayout = g_DefaultLayout; UpdateLayout(); // Reset the frame counter m_nFrameCounter = 0; m_fLastFrameTime = CWinUtil::GetTime(); m_fCurFrameDelta = 0.0f; m_eCurState = STATE_INIT; UpdateProgressBar(0.0f); UpdateCurrentBar(0.0f); UpdateTotalBar(0.0f); if (!hMission) { UpdateSessionName( ); m_Briefing.SetString(L""); m_ServerMsg.SetString(L""); m_Help.SetString(L""); m_BriefingHeader.Show(false); m_ServerMsgHeader.Show(false); } if (g_pGameClientShell->IsRunningPerformanceTest()) { m_Briefing.SetString(LoadString("IDS_PERFORMANCE_TEST_BRIEF")); } return true; }
//-------------------------------------------------------------------------------------------------------------- // Checks download status, and updates progress bar void DownloadManager::CheckActiveDownload() { if ( !m_activeRequest ) return; if ( !m_activeRequest->bAsHTTP ) { UpdateProgressBar(); return; } // check active request for completion / error / progress update switch ( m_activeRequest->status ) { case HTTP_DONE: ConDColorMsg( DownloadCompleteColor, "Download finished!\n" ); UpdateProgressBar(); if ( m_activeRequest->nBytesTotal ) { // Persist complete data to disk, and remove cache entry //TODO: SetSecondaryProgressBarText( m_activeRequest->gamePath ); TheDownloadCache->PersistToDisk( m_activeRequest ); m_activeRequest->shouldStop = true; m_completedRequests.AddToTail( m_activeRequest ); m_activeRequest = NULL; if ( !m_queuedRequests.Count() ) { //TODO: StopLoadingProgressBar(); //TODO: Cbuf_AddText("retry\n"); } } break; case HTTP_ERROR: ConDColorMsg( DownloadErrorColor, "Error downloading %s%s\n", m_activeRequest->baseURL, m_activeRequest->gamePath ); UpdateProgressBar(); // try to download the next file m_activeRequest->shouldStop = true; m_completedRequests.AddToTail( m_activeRequest ); m_activeRequest = NULL; if ( !m_queuedRequests.Count() ) { //TODO: StopLoadingProgressBar(); //TODO: Cbuf_AddText("retry\n"); } break; case HTTP_FETCH: UpdateProgressBar(); // Update progress bar //TODO: SetSecondaryProgressBarText( m_activeRequest->gamePath ); if ( m_activeRequest->nBytesTotal ) { int percent = ( m_activeRequest->nBytesCurrent * 100 / m_activeRequest->nBytesTotal ); if ( percent != m_lastPercent ) { /* ConDColorMsg( DownloadColor, "Downloading %s%s: %3.3d%% - %d of %d bytes\n", m_activeRequest->baseURL, m_activeRequest->gamePath, percent, m_activeRequest->nBytesCurrent, m_activeRequest->nBytesTotal ); */ m_lastPercent = percent; //TODO: SetSecondaryProgressBar( m_lastPercent * 0.01f ); } } break; } }
static BOOL RunInstaller() { PROCESS_INFORMATION pi; STARTUPINFO sti; char szCmdLine[MAX_BUF]; char szSetupFile[MAX_BUF]; char szUninstallFile[MAX_BUF]; char szArcLstFile[MAX_BUF]; BOOL bRet; char szText[256]; char szTempPath[MAX_BUF]; char szTmp[MAX_PATH]; char xpiDir[MAX_PATH]; char szFilename[MAX_BUF]; char szBuf[MAX_BUF]; if(gbUncompressOnly == TRUE) return(TRUE); // Update UI UpdateProgressBar(100); LoadString(hInst, IDS_STATUS_LAUNCHING_SETUP, szText, sizeof(szText)); SetStatusLine(szText); memset(&sti,0,sizeof(sti)); sti.cb = sizeof(STARTUPINFO); // Setup program is in the directory specified for temporary files GetFullTempPathName("", MAX_BUF, szTempPath); GetFullTempPathName("Archive.lst", sizeof(szArcLstFile), szArcLstFile); GetFullTempPathName("SETUP.EXE", sizeof(szSetupFile), szSetupFile); GetFullTempPathName("uninstall.exe", sizeof(szUninstallFile), szUninstallFile); GetPrivateProfileString("Archives", "uninstall.exe", "", szBuf, sizeof(szBuf), szArcLstFile); if((FileExists(szUninstallFile) != FALSE) && (*szBuf != '\0')) { lstrcpy(szCmdLine, szUninstallFile); } else { lstrcpy(szCmdLine, szSetupFile); GetModuleFileName(NULL, szFilename, sizeof(szFilename)); ParsePath(szFilename, xpiDir, sizeof(xpiDir), PP_PATH_ONLY); AppendBackSlash(xpiDir, sizeof(xpiDir)); lstrcat(xpiDir, "xpi"); if(FileExists(xpiDir)) { GetShortPathName(xpiDir, szBuf, sizeof(szBuf)); lstrcat(szCmdLine, " -a "); lstrcat(szCmdLine, szBuf); } lstrcat(szCmdLine, " -n "); lstrcat(szCmdLine, szFilename); } if(szCmdLine != NULL) lstrcat(szCmdLine, szCmdLineToSetup); // Launch the installer bRet = CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, 0, NULL, szTempPath, &sti, &pi); if (!bRet) return FALSE; CloseHandle(pi.hThread); // Wait for the InstallShield UI to appear before taking down the dialog box WaitForInputIdle(pi.hProcess, 3000); // wait up to 3 seconds if(dwMode != SILENT) { DestroyWindow(dlgInfo.hWndDlg); } // Wait for the installer to complete WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); // Delete the files from the temp directory EnumResourceNames(NULL, "FILE", (ENUMRESNAMEPROC)DeleteTempFilesProc, 0); // delete archive.lst file in the temp directory GetFullTempPathName("Archive.lst", sizeof(szTmp), szTmp); DeleteFile(szTmp); GetFullTempPathName("xpcom.ns", sizeof(szTmp), szTmp); DirectoryRemove(szTmp, TRUE); DirectoryRemove(szTempPath, FALSE); return TRUE; }
BOOL APIENTRY ExtractFilesProc(HANDLE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG lParam) { char szTmpFile[MAX_PATH]; char szArcLstFile[MAX_PATH]; HRSRC hResInfo; HGLOBAL hGlobal; LPBYTE lpBytes; LPBYTE lptr; LPBYTE lpBytesUnCmp; HANDLE hFile; char szStatus[128]; char szText[4096]; // Update the UI LoadString(hInst, IDS_STATUS_EXTRACTING, szText, sizeof(szText)); wsprintf(szStatus, szText, lpszName); SetStatusLine(szStatus); if(gbUncompressOnly == TRUE) lstrcpy(szTmpFile, lpszName); else { // Create a file in the temp directory GetFullTempPathName(lpszName, sizeof(szTmpFile), szTmpFile); CreateDirectoriesAll(szTmpFile); } if((*gszFileToUncompress != '\0') && (lstrcmpi(lpszName, gszFileToUncompress) != 0)) // We have a file to uncompress, but the one found is not the one we want, // so return TRUE to continue looking for the right one. return TRUE; // Extract the file hResInfo = FindResource((HINSTANCE)hModule, lpszName, lpszType); hGlobal = LoadResource((HINSTANCE)hModule, hResInfo); lpBytes = (LPBYTE)LockResource(hGlobal); // Create the file hFile = CreateFile(szTmpFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL); if (hFile != INVALID_HANDLE_VALUE) { DWORD dwSize; DWORD dwSizeUnCmp; DWORD dwTemp; GetFullTempPathName("Archive.lst", sizeof(szArcLstFile), szArcLstFile); WritePrivateProfileString("Archives", lpszName, "TRUE", szArcLstFile); lptr = (LPBYTE)malloc((*(LPDWORD)(lpBytes + sizeof(DWORD))) + 1); if(!lptr) { char szBuf[512]; LoadString(hInst, IDS_ERROR_OUT_OF_MEMORY, szBuf, sizeof(szBuf)); MessageBox(NULL, szBuf, NULL, MB_OK | MB_ICONEXCLAMATION); return FALSE; } lpBytesUnCmp = lptr; dwSizeUnCmp = *(LPDWORD)(lpBytes + sizeof(DWORD)); // Copy the file. The first DWORD specifies the size of the file dwSize = *(LPDWORD)lpBytes; lpBytes += (sizeof(DWORD) * 2); dwTemp = uncompress(lpBytesUnCmp, &dwSizeUnCmp, lpBytes, dwSize); while (dwSizeUnCmp > 0) { DWORD dwBytesToWrite, dwBytesWritten; ProcessWindowsMessages(); dwBytesToWrite = dwSizeUnCmp > 4096 ? 4096 : dwSizeUnCmp; if (!WriteFile(hFile, lpBytesUnCmp, dwBytesToWrite, &dwBytesWritten, NULL)) { char szBuf[512]; LoadString(hInst, IDS_STATUS_EXTRACTING, szText, sizeof(szText)); wsprintf(szBuf, szText, szTmpFile); MessageBox(NULL, szBuf, szTitle, MB_OK | MB_ICONEXCLAMATION); FreeResource(hResInfo); if(lptr) free(lptr); return FALSE; } dwSizeUnCmp -= dwBytesWritten; lpBytesUnCmp += dwBytesWritten; // Update the UI to reflect the total number of bytes written static DWORD nBytesWritten = 0; nBytesWritten += dwBytesWritten; UpdateProgressBar(nBytesWritten * 100 / nTotalBytes); } CloseHandle(hFile); } // Release the resource FreeResource(hResInfo); if(lptr) free(lptr); if((*gszFileToUncompress != '\0') && (lstrcmpi(lpszName, gszFileToUncompress) == 0)) // We have a file to uncompress, and we have uncompressed it, // so return FALSE to stop uncompressing any other file. return FALSE; return TRUE; // keep enumerating }