static int WriteFile_ToHDD(char *NameF, char *msg)           //Запись файла на HDD рекордера
{
   DWORD nb;

   if(OpenInFilePC(NameF) < 0) return -1;                    //Открыли входной файл для чтения с компьютера
   DWORD wSizeB = sCl_B;                                     //Число байт чтения равно числу байт в кластере
   LONGLONG SizeToEnd = Size_inF.QuadPart;                   //Число байт которые осталось записать
   DWORD numCl = DWORD((Size_inF.QuadPart + sCl_B - 1) / sCl_B);//Число кластеров необходимое для размещения файла данного размера
   if(numCl > maxZapFAT1 - 1 - writeCl)
      return MaloMesta(numCl);                               //"Запись невозможна, на HDD LG нет свободного места."},
   if(numCl > 0)
      InitProgressBar(numCl, msg);
   DWORD n, nCl = 1;                                         //Номер последнего записанного кластера
   for(DWORD i=0; i<numCl; i++)                              //По числу кластеров
   {  for(n=nCl+1; n<maxZapFAT1; n++)                        //Просмотр FAT для поиска первого свободного кластера
        if(*(c_FAT1 + n) == 0) break;
      if(n >= maxZapFAT1)
         return Error1((Lan+190)->msg);                      //"Запись невозможна, на HDD LG нет свободного места."},
      if(wSizeB > SizeToEnd)
      {  wSizeB = DWORD(SizeToEnd);                          //Размер остатка чтения меньше размера кластера
         ZeroMemory(bufIO, sCl_B);
      }
      if(ReadFile(inFile, bufIO, wSizeB, &nb, NULL) == false || nb != wSizeB)
         return ErrorSys1((Lan+87)->msg);                    //"Ошибка при чтении файла."
#if !defined EMULATOR_HDD                                    //НЕТ Режима эмулятора
      if(WriteClast1P(n, bufIO) < 0) return -1;              //Запись кластера
#endif
      if(nCl > 1)
        *(c_FAT1 + nCl) = n;                                 //Ссылка на следубщий кластер в цепочке кластеров
      else nCl_1 = n;                                        //Номер кластера начала файла
      nCl = n;                                               //Последний записанный кластер
      SizeToEnd -= wSizeB;                                   //Число байт которые осталось прочитать
      if(ProgressBar(wSizeB) < 0) return -1;                 //Оператор нажал кнопку Прервать
   }
   *(c_FAT1 + nCl) = 0x0FFFFFFF;                             //Признак конца цепочки
   CloseFile(&inFile);
   writeNewCl += numCl;                                      //Число записанных кластеров
   return Change_Dir_For_File(NameF);                        //Изменение каталога (запись нового файла)
}
Exemplo n.º 2
0
void DrawProgressBar(int nPercent) {
  int nMax;

  if(nShowPhase != 1) {
    if(! ::nProcessRank) fprintf(stderr, "\n");
    InitProgressBar();
    nShowPhase = 1;
  } // if nShowPhase

  nRotateChar = (nRotateChar + 1) % 4;

//  nMax = int(double((nPercent*(nScreenWidth-13)))/100.0);
  nMax = nBarStart + 1 + int(double((nPercent*(nScreenWidth-nBarStart-12)))/100.0);
  for(int i=nBarStart + 1; i<nMax; i++) {
    if(i == nMax - 1 && nPercent != 100)
      strImage[i] = '>';
    else
      strImage[i] = '=';
  } // for i
  sprintf(strImage + nScreenWidth-12, "] %3i %%  %c \r", nPercent, *(strRotateImage+nRotateChar));

  if(! ::nProcessRank) fprintf(stderr, strImage);
  return;
} // DrawProgressBar
Exemplo n.º 3
0
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;
	}
Exemplo n.º 4
0
void 
FileTransfer::FileTransferDownload()
{
	rfbFileDownloadDataMsg fdd;
	m_clientconn->ReadExact((char *)&fdd, sz_rfbFileDownloadDataMsg);
	fdd.realSize = Swap16IfLE(fdd.realSize);
	fdd.compressedSize = Swap16IfLE(fdd.compressedSize);

	char path[rfbMAX_PATH + rfbMAX_PATH + 3];
	
	if (m_bFirstFileDownloadMsg) {
		m_dwDownloadBlockSize = fdd.compressedSize;
		sprintf(path, "%s\\%s", m_ClientPath, m_ServerFilename);
		strcpy(m_DownloadFilename, path);
		m_hFiletoWrite = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
									NULL, CREATE_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
		int amount = m_sizeDownloadFile / ((m_dwDownloadBlockSize + 1) * 10);
		InitProgressBar(0, 0, amount, 1);
		m_bFirstFileDownloadMsg = FALSE;
		m_bDownloadStarted = TRUE;
	}
	if ((fdd.realSize == 0) && (fdd.compressedSize == 0)) {
		unsigned int mTime;
		m_clientconn->ReadExact((char *) &mTime, sizeof(unsigned int));
		if (m_hFiletoWrite == INVALID_HANDLE_VALUE) {
			CancelDownload("Could not create file");
			MessageBox(m_hwndFileTransfer, "Download failed: could not create local file",
					   "Download Failed", MB_ICONEXCLAMATION | MB_OK);
			SendMessage(m_hwndFTProgress, PBM_SETPOS, 0, 0);
			// Send message to start download for next selected file.
			PostMessage(m_hwndFileTransfer, WM_COMMAND, IDC_FTCOPY, 0);
			return;
		}
		FILETIME Filetime;
		Time70ToFiletime(mTime, &Filetime);
		SetFileTime(m_hFiletoWrite, &Filetime, &Filetime, &Filetime);
		SendMessage(m_hwndFTProgress, PBM_SETPOS, 0, 0);
		SetWindowText(m_hwndFTStatus, "");
		CloseHandle(m_hFiletoWrite);
		ShowClientItems(m_ClientPath);
		m_bFirstFileDownloadMsg = TRUE;
		m_bDownloadStarted = FALSE;
		// Send message to start download for next selected file.
		PostMessage(m_hwndFileTransfer, WM_COMMAND, IDC_FTCOPY, 0);
		return;
	}
	char * pBuff = new char [fdd.compressedSize];
	DWORD dwNumberOfBytesWritten;
	m_clientconn->ReadExact(pBuff, fdd.compressedSize);
	ProcessDlgMessage(m_hwndFileTransfer);
	if (!m_bTransferEnable) {
		CancelDownload("Download cancelled by user");
		delete [] pBuff;
		return;
	}
	if (m_hFiletoWrite == INVALID_HANDLE_VALUE) {
		CancelDownload("Could not create file");
		MessageBox(m_hwndFileTransfer, "Download failed: could not create local file",
				   "Download Failed", MB_ICONEXCLAMATION | MB_OK);
		delete [] pBuff;
		return;
	}
	WriteFile(m_hFiletoWrite, pBuff, fdd.compressedSize, &dwNumberOfBytesWritten, NULL);
	m_dwDownloadRead += dwNumberOfBytesWritten;
	if (m_dwDownloadRead >= (10 * m_dwDownloadBlockSize)) {
		m_dwDownloadRead = 0;
		SendMessage(m_hwndFTProgress, PBM_STEPIT, 0, 0); 
	}
	delete [] pBuff;
}
Exemplo n.º 5
0
void 
FileTransfer::FileTransferUpload()
{
	int numOfFilesToUpload = 0, currentUploadIndex = -1;
	DWORD sz_rfbFileSize;
	DWORD sz_rfbBlockSize= 8192;
	DWORD dwNumberOfBytesRead = 0;
	unsigned int mTime = 0;
	char path[rfbMAX_PATH + rfbMAX_PATH + 2];
	BOOL bResult;
	numOfFilesToUpload = ListView_GetSelectedCount(m_hwndFTClientList);
	if (numOfFilesToUpload < 0) {
		SetWindowText(m_hwndFTStatus, "No file selected, nothing to upload.");
		BlockingFileTransferDialog(TRUE);
		EnableWindow(GetDlgItem(m_hwndFileTransfer, IDC_FTCANCEL), FALSE);
		return;
	}

	for (int i = 0; i < numOfFilesToUpload; i++) {
		BlockingFileTransferDialog(FALSE);
		EnableWindow(GetDlgItem(m_hwndFileTransfer, IDC_FTCANCEL), TRUE);
		int index = ListView_GetNextItem(m_hwndFTClientList, currentUploadIndex, LVNI_SELECTED);
		if (index < 0) {
			SetWindowText(m_hwndFTStatus, "No file is selected, nothing to download.");
			return;
		}
		currentUploadIndex = index;
		ListView_GetItemText(m_hwndFTClientList, currentUploadIndex, 0, m_ClientFilename, rfbMAX_PATH);
		sprintf(path, "%s\\%s", m_ClientPath, m_ClientFilename);
		strcpy(m_UploadFilename, path);
		WIN32_FIND_DATA FindFileData;
		SetErrorMode(SEM_FAILCRITICALERRORS);
		HANDLE hFile = FindFirstFile(path, &FindFileData);
		SetErrorMode(0);
		if (hFile == INVALID_HANDLE_VALUE) {
			SetWindowText(m_hwndFTStatus, "Could not find selected file, can't upload");
			// Continue with upload of other files.
			continue;
		} else if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
			SetWindowText(m_hwndFTStatus, "Cannot upload a directory");
			// Continue with upload of other files.
			continue;
		} else {
			sz_rfbFileSize = FindFileData.nFileSizeLow;
			mTime = FiletimeToTime70(FindFileData.ftLastWriteTime);
			strcpy(m_ServerFilename, FindFileData.cFileName);
		}
		FindClose(hFile);
		if ((sz_rfbFileSize != 0) && (sz_rfbFileSize <= sz_rfbBlockSize)) sz_rfbBlockSize = sz_rfbFileSize;
		m_hFiletoRead = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
		if (m_hFiletoRead == INVALID_HANDLE_VALUE) {
			SetWindowText(m_hwndFTStatus, "Upload failed: could not open selected file");
			BlockingFileTransferDialog(TRUE);
			EnableWindow(GetDlgItem(m_hwndFileTransfer, IDC_FTCANCEL), FALSE);
			return;
		}
		char buffer[rfbMAX_PATH + rfbMAX_PATH + rfbMAX_PATH + rfbMAX_PATH + 20];
		sprintf(buffer, "Uploading: %s\\%s -> %s\\%s ...",
				m_ClientPath, m_ClientFilename, m_ServerPath, m_ServerFilename);
		SetWindowText(m_hwndFTStatus, buffer);
		sprintf(path, "%s\\%s", m_ServerPath, m_ClientFilename);
		ConvertPath(path);
		int pathLen = strlen(path);

		char *pAllFURMessage = new char[sz_rfbFileUploadRequestMsg + pathLen];
		rfbFileUploadRequestMsg *pFUR = (rfbFileUploadRequestMsg *) pAllFURMessage;
		char *pFollowMsg = &pAllFURMessage[sz_rfbFileUploadRequestMsg];
		pFUR->type = rfbFileUploadRequest;
		pFUR->compressedLevel = 0;
		pFUR->fNameSize = Swap16IfLE(pathLen);
		pFUR->position = Swap32IfLE(0);
		memcpy(pFollowMsg, path, pathLen);
		m_clientconn->WriteExact(pAllFURMessage, sz_rfbFileUploadRequestMsg + pathLen); 
		delete [] pAllFURMessage;

		if (sz_rfbFileSize == 0) {
			SendFileUploadDataMessage(mTime);
		} else {
			int amount = sz_rfbFileSize / (sz_rfbBlockSize * 10);

			InitProgressBar(0, 0, amount, 1);

			DWORD dwPortionRead = 0;
			char *pBuff = new char [sz_rfbBlockSize];
			m_bUploadStarted = TRUE;
			while(m_bUploadStarted) {
				ProcessDlgMessage(m_hwndFileTransfer);
				if (m_bTransferEnable == FALSE) {
					SetWindowText(m_hwndFTStatus, "File transfer canceled");
					EnableWindow(GetDlgItem(m_hwndFileTransfer, IDC_FTCANCEL), FALSE);
					BlockingFileTransferDialog(TRUE);
					char reason[] = "File transfer canceled by user";
					int reasonLen = strlen(reason);
					char *pFUFMessage = new char[sz_rfbFileUploadFailedMsg + reasonLen];
					rfbFileUploadFailedMsg *pFUF = (rfbFileUploadFailedMsg *) pFUFMessage;
					char *pReason = &pFUFMessage[sz_rfbFileUploadFailedMsg];
					pFUF->type = rfbFileUploadFailed;
					pFUF->reasonLen = Swap16IfLE(reasonLen);
					memcpy(pReason, reason, reasonLen);
					m_clientconn->WriteExact(pFUFMessage, sz_rfbFileUploadFailedMsg + reasonLen);
					delete [] pFUFMessage;
					break;
				}
				bResult = ReadFile(m_hFiletoRead, pBuff, sz_rfbBlockSize, &dwNumberOfBytesRead, NULL);
				if (bResult && dwNumberOfBytesRead == 0) {
					/* This is the end of the file. */
					SendFileUploadDataMessage(mTime);
					break;
				}
				SendFileUploadDataMessage((unsigned short)dwNumberOfBytesRead, pBuff);
				dwPortionRead += dwNumberOfBytesRead;
				if (dwPortionRead >= (10 * sz_rfbBlockSize)) {
					dwPortionRead = 0;
					SendMessage(m_hwndFTProgress, PBM_STEPIT, 0, 0);
				}
			}
			if (m_bTransferEnable == FALSE)
				break;
			m_bUploadStarted = FALSE;
			delete [] pBuff;
		}
		SendMessage(m_hwndFTProgress, PBM_SETPOS, 0, 0);
		SetWindowText(m_hwndFTStatus, "");
		CloseHandle(m_hFiletoRead);
	}
	EnableWindow(GetDlgItem(m_hwndFileTransfer, IDC_FTCANCEL), FALSE);
	BlockingFileTransferDialog(TRUE);
	SendFileListRequestMessage(m_ServerPath, 0);
}
Exemplo n.º 6
0
/*
	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;
}
Exemplo n.º 7
0
//11static int Copy_One_File(PAR_FILE *pf, char *msg, char *fName) //Копирование одного файла
static int Copy_One_File(PAR_FILE *pf, char *msg)            //Копирование одного файла
{
   BYTE buff[sCl_B];                                         //Память под один кластер
   DWORD nb;
#if !defined EMULATOR_HDD_AND_COPY                           //НЕТ Режима эмулятора с эмуляцией копирования
   ZeroMemory(buff, sCl_B);                                  //Очистка буфера чтения
#endif
   DWORD wSizeB = sCl_B;                                     //Число записываемых байт равно числу байт в кластере
   DWORD nCl = pf->ClSt;                                     //Текущий номер кластера равен первому кластеру файла
   LONGLONG SizeToEnd = pf->SizeF;                           //Число байт которые осталось записать
   DWORD numCl = DWORD((pf->SizeF + sCl_B - 1) / sCl_B);     //Число кластеров необходимое для размещения файла данного размера
   if(numCl > 0)
      InitProgressBar(numCl, msg);
   for(DWORD i=0; i<numCl; i++)                              //По числу кластеров
   {  if(nCl == 0x0FFFFFFF)                                  //Признак конца цепочки
        return Error1((Lan+12)->msg);                        //return Error1("Неожиданно найден признак конца цепочки FAT.");
      if(*(FAT1 + nCl) == 0)                                 //Ненормальная ситуация
        return Error1((Lan+11)->msg);                        //return Error1("Обнаружено несоответствие значения FAT и ссылки на кластер файла.");
      if(wSizeB > SizeToEnd)
//11     wSizeB = DWORD(((SizeToEnd + 511) / 512) * 512);    //Размер остатка записи меньше размера кластера  ?? Почему сектор
         wSizeB = DWORD(SizeToEnd);                          //Размер остатка записи меньше размера кластера
#if !defined EMULATOR_HDD_AND_COPY                           //НЕТ Режима эмулятора с эмуляцией копирования
      DWORD nSector = Start_SecDir1 + (nCl - 1) * sClSec;    //Сектор начала текущего кластера
      if(ReadClast1_P(nSector, buff) < 0) return -1;         //Чтение очeредного кластера
#endif
      if(WriteFile(outFile, buff, wSizeB, &nb, NULL) == false || nb != wSizeB)
        return ErrorSys1((Lan+83)->msg);                     //return ErrorSys1("Ошибка при записи выходного файла.");
      SizeToEnd -= wSizeB;                                   //Число байт которые осталось записать
      nCl = *(FAT1 + nCl);                                   //Номер следующего кластера
      if(nCl > maxZapFAT1 && nCl != 0x0FFFFFFF)
        return Error1((Lan+13)->msg);                        //"Номер кластера превышает допустимое значение."
      if(SizeToEnd == 0 && nCl != 0x0FFFFFFF)
        Error1((Lan+29)->msg);                               //return Error2("Выходной файл заданного размера записан,", "а признак конца цепочки FAT не найден.");
      if(ProgressBar(wSizeB) < 0) return -1;                 //Оператор нажал кнопку Прервать
   }
   CloseFile(&outFile);                                      //Закрыли выходной файл
/*11
   if((pf->SizeF % sCl_B) != 0)                              //Размер файла не является кратным размеру кластера
 {
   int n = 0;                                                //Счетчик для ожидания освобождения файла
   if(Open_FileR(fName, &outFile, &n) < 0)                   //Открытие выходного файла
      return -1;
   LARGE_INTEGER TPoz;
   TPoz.QuadPart = pf->SizeF;
   TPoz.u.LowPart = SetFilePointer(outFile, TPoz.u.LowPart, &TPoz.u.HighPart, FILE_BEGIN);
   if(TPoz.u.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR)
      return ErrorSys1((Lan+83)->msg);                       //"Ошибка при позиционировании по диску."
    if(SetEndOfFile(outFile) == false)
      return ErrorSys1((Lan+83)->msg);                     //return ErrorSys1("Ошибка при записи выходного файла.");
 }
*/
   FILETIME fTime, flTime;
   SYSTEMTIME sysTime;
   sysTime.wYear = pf->Year;
   sysTime.wMonth = pf->Mon;
// sysTime.wDayOfWeek = 0;
   sysTime.wDay = pf->Day;
   sysTime.wHour = pf->Hour;
   sysTime.wMinute = pf->Min;
   sysTime.wSecond = pf->Sec;
   sysTime.wMilliseconds = 0;
   SystemTimeToFileTime(&sysTime, &flTime);                  //Преобразовали время
   LocalFileTimeToFileTime(&flTime, &fTime);
   SetFileTime(outFile, &fTime, &fTime, &fTime);             //Дата файла
   return 0;
Exemplo n.º 8
0
int main(int argc, char **argv)
{
	int i, j, k, treeNo, sumLength;
	char ch;
	TTree **treeSet;
	FILE *text_fv;
	clock_t totalStart;
	double totalSecs, scale, sum;
	char *ancestor;

	totalStart = clock();

	ReadParams(argc, argv);

	if (rateHetero == CodonRates && invariableSites) {
		fprintf(stderr, "Invariable sites model cannot be used with codon rate heterogeneity.\n");
		exit(4);
	}

	if (writeAncestors && fileFormat == NEXUSFormat) {
		fprintf(stderr, "Warning - When writing ancestral sequences, relaxed PHYLIP format is used.\n");
	}

	if (writeAncestors && maxPartitions > 1) {
		fprintf(stderr, "Writing ancestral sequences can only be used for a single partition.\n");
		exit(4);
	}
			
	if (!userSeed)
		randomSeed = CreateSeed();
		
	SetSeed(randomSeed);

	if (!quiet)
 		PrintTitle();
	
	numTrees = OpenTreeFile();

	/* if (!treeFile) { */
		ReadFileParams();
	/*} */


	if ((ancestorSeq>0 && !hasAlignment) || ancestorSeq>numSequences) {
		fprintf(stderr, "Bad ancestral sequence number: %d (%d sequences loaded)\n", ancestorSeq, numSequences);
		exit(4);
	}
	
	if (textFile) {
		if ( (text_fv=fopen(textFileName, "rt"))==NULL ) {
			fprintf(stderr, "Error opening text file for insertion into output: '%s'\n", textFileName);
			exit(4);
		}
	}

	ancestor=NULL;
	if (hasAlignment) {
		AllocateMemory();	
		ReadFile();
		
		if (numSites<0)
			numSites=numAlignmentSites;		
			
		if (ancestorSeq>0) {
			if (numSites!=numAlignmentSites) {
				fprintf(stderr, "Ancestral sequence is of a different length to the simulated sequences (%d)\n", numAlignmentSites);
				exit(4);
			}
			ancestor=sequences[ancestorSeq-1];
		}
	} else if (numSites<0)
		numSites=1000;
	
	SetModel(model);
	
	numTaxa=-1;
	scale=1.0;
	
	treeSet = (TTree **)malloc(sizeof(TTree **) * maxPartitions);
	if (treeSet==NULL) {
		fprintf(stderr, "Out of memory\n");
		exit(5);
	}
	
	partitionLengths = (int *)malloc(sizeof(int) * maxPartitions);
	if (partitionLengths==NULL) {
		fprintf(stderr, "Out of memory\n");
		exit(5);
	}
	
	partitionRates = (double *)malloc(sizeof(double) * maxPartitions);
	if (partitionRates==NULL) {
		fprintf(stderr, "Out of memory\n");
		exit(5);
	}
	
	for (i = 0; i < maxPartitions; i++) {
		if ((treeSet[i]=NewTree())==NULL) {
			fprintf(stderr, "Out of memory\n");
			exit(5);
		}
	}
					
	CreateRates();
	
	treeNo=0;
	do {
		partitionLengths[0] = -1;
		ReadTree(tree_fv, treeSet[0], treeNo+1, 0, NULL, &partitionLengths[0], &partitionRates[0]);

		if (treeNo==0) {
			numTaxa=treeSet[0]->numTips;
			
			if (!quiet)
				fprintf(stderr, "Random number generator seed: %ld\n\n", randomSeed);
				
			if (fileFormat == NEXUSFormat) {
				fprintf(stdout, "#NEXUS\n");
				fprintf(stdout, "[\nGenerated by %s %s\n\n", PROGRAM_NAME, VERSION_NUMBER);
				PrintVerbose(stdout);
				fprintf(stdout, "]\n\n");
			}
		} else if (treeSet[0]->numTips != numTaxa) {
			fprintf(stderr, "All trees must have the same number of tips.\n");
			exit(4);
		}
		
		if (maxPartitions == 1) {
			if (partitionLengths[0] != -1) {
				fprintf(stderr, "\nWARNING: The treefile contained partion lengths but only one partition\n");
				fprintf(stderr, "was specified.\n");
			}
			partitionLengths[0] = numSites;
		}

		sumLength = partitionLengths[0];
		i = 1;
		while (sumLength < numSites && i <= maxPartitions) {
			if (!IsTreeAvail(tree_fv)) {
				fprintf(stderr, "\nA set of trees number %d had less partition length (%d) than\n", treeNo + 1, sumLength);
				fprintf(stderr, "was required to make a sequence of length %d.\n", numSites);
				exit(4);
			}
				
			ReadTree(tree_fv, treeSet[i], treeNo+1, treeSet[0]->numTips, treeSet[0]->names, 
						&partitionLengths[i], &partitionRates[i]);
						
			if (treeSet[i]->numTips != numTaxa) {
				fprintf(stderr, "All trees must have the same number of tips.\n");
				exit(4);
			}
			
			sumLength += partitionLengths[i];
			i++;
		}
		if (i > maxPartitions) {
			fprintf(stderr, "\nA set of trees number %d had more partitions (%d) than\n", treeNo + 1, i);
			fprintf(stderr, "was specified in the user options (%d).\n", maxPartitions);
		}
		numPartitions = i;
				
		if (sumLength != numSites) {
			fprintf(stderr, "The sum of the partition lengths in the treefile does not equal\n");
			fprintf(stderr, "the specified number of sites.\n");
			exit(4);
		}
			
		for (i = 0; i < numPartitions; i++)
			CreateSequences(treeSet[i], partitionLengths[i]);
		
		if (numPartitions > 1) {
			sum = 0.0;
			for (i = 0; i < numPartitions; i++)
				sum += partitionRates[i] * partitionLengths[i];
				
			for (i = 0; i < numPartitions; i++)
				partitionRates[i] *= numSites / sum;
		}
		
		if (treeNo==0 && verbose && !quiet) {
			PrintVerbose(stderr);
			InitProgressBar(numTrees*numDatasets);
			DrawProgressBar();
		}

		for (i=0; i<numDatasets; i++) {
			SetCategories();
			
			k = 0;
			for (j = 0; j < numPartitions; j++) {
				scale = partitionRates[j];
				
				if (scaleTrees) { 
					if (!treeSet[j]->rooted) {
						fprintf(stderr, "To scale tree length, they must be rooted and ultrametric.\n");
						exit(4);
					}
					scale *= treeScale/treeSet[j]->totalLength;
				} else if (scaleBranches)
					scale *= branchScale;

				EvolveSequences(treeSet[j], k, partitionLengths[j], scale, ancestor);
				k += partitionLengths[j];
			}
			
			if (writeAncestors)
				WriteAncestralSequences(stdout, treeSet[0]);
			else
				WriteSequences(stdout, (numTrees > 1 ? treeNo+1 : -1), (numDatasets > 1 ? i+1 : -1), treeSet, partitionLengths);

			if (writeRates) {
				WriteRates(stderr);
			}

			if (textFile) {
				while (!feof(text_fv)) {
					ch = fgetc(text_fv);
					if (!feof(text_fv))
						fputc(ch, stdout);
				}
				fputc('\n', stdout);
				rewind(text_fv);
			}
			
			if (verbose && !quiet)
				ProgressBar();
		}
				
		for (i = 0; i < numPartitions; i++)
			DisposeTree(treeSet[i]);
			
		treeNo++;
	} while (IsTreeAvail(tree_fv));
	
/*	for (i = 0; i < maxPartitions; i++)
		FreeTree(treeSet[i]);	*/
	
	if (treeFile)
		fclose(tree_fv);

	if (textFile)
		fclose(text_fv);

	totalSecs = (double)(clock() - totalStart) / CLOCKS_PER_SEC;
	if (!quiet) {
		fprintf(stderr, "Time taken: %G seconds\n", totalSecs);
		if (verboseMemory)
			fprintf(stderr, "Total memory used: %ld\n", totalMem);
	}
	
	return 0;
}