Ejemplo n.º 1
0
void CCopyThread::DoCopyFile(string source, string dest)
{
	source = str_replaceallA(source,"\\\\","\\");
	dest = str_replaceallA(dest,"\\\\","\\");


	File_Size.QuadPart = File_Prog.QuadPart = 0;
	SetCurFile(source);

	if (Action == CDA_SDMODE)
	{
		//DebugMsg("Move %s to %s",source.c_str(),dest.c_str());
		if (MoveFile(source.c_str(),dest.c_str()))
			Total_FilesCopied++;
	} else {
		//DebugMsg("Copy %s to %s",source.c_str(),dest.c_str());
		if (CopyFileEx(source.c_str(),dest.c_str(),CopyProgressRoutine,(void*)this,NULL,0))
			Total_FilesCopied++;
	}

	if (Action == CDA_MOVEFILES)
	{
		//DebugMsg("_unlink %s",source.c_str());
		_unlink(source.c_str());
	}

	// add file progress to total progress and reset file stuff
	Total_Prog.QuadPart += File_Prog.QuadPart;
	File_Prog.QuadPart = 0;
	File_Size.QuadPart = 0;
}
Ejemplo n.º 2
0
	bool MoveAction::Act(const Archive & archive)
	{
		if (!dest_dir_.empty())
		{
			int create_dir = SHCreateDirectory(NULL, dest_dir_.c_str());
			if (create_dir != ERROR_SUCCESS)
			{
				std::wstring error = util::FormatErrorMessage();
				return false;
			}
		}
		int ret = CopyFileEx(archive.FullName().c_str(), dest_path_.c_str(), (LPPROGRESS_ROUTINE)Callback, this, NULL, 0);
		if (!ret)
		{			
			std::wstring errormessage = util::FormatErrorMessage();
			return false;
		}

		if (!orignal_reserved_)
		{
			DeleteFile(archive.FullName().c_str());
		}

		return true;
	}
Ejemplo n.º 3
0
BOOLEAN CopyToNewFile (const char * const src_filename, const char * const dest_filename, void (*callback_fn) ())
{
	LPPROGRESS_ROUTINE prog_fn = (LPPROGRESS_ROUTINE) callback_fn;

	if (callback_fn)
		{
			return (CopyFileEx (src_filename, dest_filename, prog_fn, NULL, 0, 0) != 0);
		}
	else
		{
			return (CopyFile (src_filename, dest_filename, TRUE) != 0);
		}
}
Ejemplo n.º 4
0
void CFilePage::OnBnClickedBtnApiCopyFileEx()
{
    BOOL bRet = FALSE;
    m_strCopyDstFile.Format(TEXT("E:\\TargetCopy_%d.txt"), GetTickCount());
    API_VERIFY_EXCEPT1(DeleteFile(m_strCopyDstFile), ERROR_FILE_NOT_FOUND);

    CFElapseCounter counter;
    counter.Start();
    BOOL bCancel = FALSE;
    API_VERIFY(CopyFileEx(m_strCopySrcFile, m_strCopyDstFile, CopyProgressRoutine, this, &bCancel, 0));
    counter.Stop();

    CFStringFormater formater;
    formater.Format(TEXT("API CopyFileEx Elapse %d(ms)\n"), counter.GetElapseTime() / NANOSECOND_PER_MILLISECOND);
    OutputDebugString(formater.GetString());
}
Ejemplo n.º 5
0
unsigned __stdcall _OpFileMoveThread(void *pVoid) {

  OPERATIONSTRUCT os  = *reinterpret_cast<POPERATIONSTRUCT>(pVoid);
  OPCALLBACKDATA ocd;
  TSTRINGLISTIT it    = os.Files.begin();
  UINT uiCurFile      = 1U;
  bool bAskOverwrite  = true;
  BOOL bCancelOp      = FALSE;
  TSTRING tsTemp;

 /*
  * If the destination directory is invalid,
  * it's probably been moved, or renamed
  * since its association with the application.
  * Prompt the user to see if they'd like to 
  * create it, or abort.
  */
  if (FALSE == PathIsDirectory(os.tsDest.c_str())) {

    INT_PTR iChoice = PrintMsgBox(os.hWnd, _T("extFileCopy")
                                  _T(" : Directory not found"),
                                  MB_YESNO | MB_ICONWARNING,
                                  _T("The destination directory:\n\n")
                                  _T("%s\n\nhas either been moved")
                                  _T(" or renamed since its association")
                                  _T(" with extFileCopy. Would you like")
                                  _T(" to create it?"),
                                  os.tsDest.c_str());
            
    switch (iChoice) {

      case IDYES:
      {
       /*
        * Attempt to create the directory.
        */
        if (FALSE == CreateDirectory(os.tsDest.c_str(), NULL)) {

         /*
          * We've failed miserably.
          * Can't copy any files to a non-existant
          * directory; done.
          */
          PrintMsgBox(os.hWnd, _T("extFileCopy : ERROR"),
                      MB_OK | MB_ICONSTOP,
                      _T("An error occurred while attempting")
                      _T(" to create the directory:\n\n%s.\n\n")
                      _T("The directory will be disassociated with")
                      _T("extFileCopy.\n\n")
                      _T("Win32 error: %d"),
                      os.tsDest.c_str(),
                      GetLastError());

          RegUtil_RemAssociatedDirectory(ExtensionFromList(os.Files), os.tsDest);

          goto mtFinish;
        }

      }
      break;

      case IDNO:
      {
       /*
        * User doesn't want to bother creating
        * the directory; We have to remove
        * the association in the registry.
        */
        PrintMsgBox(os.hWnd, _T("extFileCopy : Removing association"),
                    MB_OK | MB_ICONWARNING,
                    _T("The inaccessible directory:\n\n%s\n\nwill now")
                    _T(" be disassociated with extFileCopy."),
                    os.tsDest.c_str());

        RegUtil_RemAssociatedDirectory(ExtensionFromList(os.Files), os.tsDest);

        goto mtFinish;
      }
      break;

    }

  }

  os.pDlg->SetCancelPtr(&bCancelOp);

 /*
  * Set up the dialog UI
  */
  if (os.bCopy) {

    os.pDlg->SetWindowText(_T("Copying ..."));

  } else {

    os.pDlg->SetWindowText(_T("Moving ..."));

  }

  os.pDlg->SetElapsedTime(0);

  for(; it != os.Files.end(); it++) {

   /*
    * Check if the operation was cancelled
    * by the user
    */
    os.pMutex->Lock();

    if (TRUE == bCancelOp) {

      os.pMutex->Unlock();
      goto mtFinish;
    }

    os.pMutex->Unlock();

   /*
    * Update overall progress
    */
    INT64 iOverallPct = ((uiCurFile * 100) / os.Files.size());

    sprintf(tsTemp, _T("Overall Progress (file %d of %d) : %I64d%%"),
            uiCurFile++, os.Files.size(), iOverallPct);

    os.pDlg->SetOverallProgress(iOverallPct, tsTemp);

   /*
    * Update current file name
    */
    TSTRING tsShortFile = GetFileFromPath((*it));
    TSTRING tsDisplay   = tsShortFile;

   /*
    * Truncate file name if necessary
    */
    tsDisplay = FileGetCompactName(tsDisplay, PD_MAXCURFILE);
    
    sprintf(tsTemp, _T("Current file '%s' : %I64d%%"),
            tsDisplay.c_str(), 0LL);

    os.pDlg->SetCurrentProgress(0, tsTemp);

   /*
    * Reset transfer rate
    */
    os.pDlg->SetTransferRate(_T("Transfer Rate: calculating..."));
            
   /* 
    * If the resulting destination path is > MAX_PATH,
    * we've got to skip this file and tell the user.
    */
    TSTRING tsDest = PathConcatFile(os.tsDest, tsShortFile);

    if (MAX_PATH < tsDest.size()) {

      PrintMsgBox(os.hWnd, _T("extFileCopy : Can't copy file"),
                  MB_OK | MB_ICONWARNING,
                  _T("The following destination path:\n\n")
                  _T("%s\n\nis longer than MAX_PATH characters, and")
                  _T(" cannot be created."), tsDest.c_str());

      continue;

    }

   /*
    * Make sure the file doesn't exist; if it does,
    * we've got to prompt the user to overwrite.
    */
    if (-1 != GetFileAttributes(tsDest.c_str())) {

     /*
      * Yeah, the file exists.
      */
      if (bAskOverwrite) {

        OverwriteDlg dlg((*it), tsDest, 1 < os.Files.size());

        if (!dlg.DoModal(static_cast<HINSTANCE>(g_hModule),
                         MAKEINTRESOURCE(IDD_OVERWRITE),
                         os.pDlg->m_hWnd))
        {
          
          MessageBox(os.pDlg->m_hWnd, _T("A fatal internal error has occurred. Cannot continue.\n"),
                     _T("extFileCopy : ERROR"), MB_OK | MB_ICONSTOP);

          os.pDlg->CleanUp();
          _endthreadex(1);

        }

       /*
        * Find out what the user chose
        */
        switch (dlg.Result()) {

          case YES:
           /*
            * Ok to overwrite, but don't touch
            * bAskOverwrite.
            */            
          break;

          case YESTOALL:
           /*
            * Ok to overwrite ALL files.
            */
            bAskOverwrite = false;
          break;

          case NO:
           /*
            * Don't overwrite this file;
            * instead skip to the next.
            */
            continue;
          break;

          case CANCEL:
           /*
            * Forget it. We're outta here.
            */
            os.pMutex->Lock();
            bCancelOp = TRUE;
            os.pMutex->Unlock();
            goto mtFinish;
          break;

        }

      }

    }

   /*
    * File doesn't exist, or we don't
    * really care.  Continue normally
    */
    TSTRING tsCurFile = FileGetCompactName(tsShortFile.c_str(), PD_MAXCURFILE);

    ocd.pbCancel    = &bCancelOp;
    ocd.dwStartTime = (2 == uiCurFile) ? GetTickCount() : ocd.dwStartTime;
    ocd.dwLastTime  = (2 == uiCurFile) ? ocd.dwStartTime : ocd.dwLastTime;
    ocd.dwLastRate  = GetTickCount();
    ocd.iLastPct    = 0LL;
    ocd.iThroughput = 0LL;
    ocd.pDlg        = os.pDlg;
    ocd.pMutex      = os.pMutex;
    ocd.szCurFile   = tsCurFile.c_str();

    if (os.bCopy) {

     /*
      * This is a copy operation
      */
      if (0 == CopyFileEx((*it).c_str(), tsDest.c_str(), _Callback,
                           &ocd, &bCancelOp, 0UL))
      {

       /*
        * The copy operation has failed!
        * Let's tell the user, and then
        * if there's more than one file
        * being copied, ask the user if
        * they'd like to continue with
        * the next file. (If the error
        * didn't result from user abortion)
        */
        if (ERROR_REQUEST_ABORTED != GetLastError()) {

          INT_PTR iUser = ErrorPrompt(os.pDlg->m_hWnd, (*it), tsDest, 
                                    (1 < os.Files.size()) ? true : false, os.bCopy);

          if (1 < os.Files.size()) {

            if (IDYES == iUser) {

            /*
              * User wishes to try the next file.
              */
              continue;

            } else if (IDNO == iUser) {

              break;

            }

          } else {

            continue;

          }

        }

      }

    } else {

     /*
      * This is a move operation
      */
      if (0 == MoveFileWithProgress((*it).c_str(), tsDest.c_str(), _Callback,
                                    &ocd, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING
                                    | MOVEFILE_WRITE_THROUGH))
      {

       /*
        * The move operation has failed!
        * Let's tell the user, and then
        * if there's more than one file
        * being copied, ask the user if
        * they'd like to continue with
        * the next file. (If the error
        * didn't result from user abortion)
        */
        if (ERROR_REQUEST_ABORTED != GetLastError()) {

          INT_PTR iUser = ErrorPrompt(os.pDlg->m_hWnd, (*it), tsDest,
                                      (1 < os.Files.size()) ? true : false, os.bCopy);

          if (1 < os.Files.size()) {

            if (IDYES == iUser) {

            /*
              * User wishes to try the next file.
              */
              continue;

            } else if (IDNO == iUser) {

              break;

            }

          } else {

            continue;

          }

        }

      }

    }

  }

mtFinish:

  os.pDlg->CleanUp();
  _endthreadex(0U);
  return 0U;
}
Ejemplo n.º 6
0
void
ConnectionList::RetrieveProxyCookies( std::string& cookie ) {

	if ( curConnection == NULL ) {
		CosignLog( L"Current connection is not set.  Could not retrieve proxy cookies." );
		return;
	}

	HANDLE	hpf = INVALID_HANDLE_VALUE;
	DWORD	bytesWritten = 0;
	DWORD	err;
   DWORD   success = 0;
   std::string   in;
   std::basic_string <char>::size_type   index;
   std::basic_string <char>::size_type   last;
   std::string crlf = "\r\n";
   std::string line;
   std::string status;

	try { 


	// Create file to hold proxy cookie data
	WCHAR	tempFileName[ 32768 ];
	CosignTrace1( L"proxy Cookies Diretory path = %s", proxyCookiesDirectory.c_str() );
	if ( GetTempFileName( proxyCookiesDirectory.c_str(), L"pck", 0, tempFileName ) == 0 ) {
		err = GetLastError();
		CosignLog( L"GetTempFileName failed with 0x%x", err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	CosignTrace1( L"tempFileName = %s", tempFileName );
	hpf = CreateFile( tempFileName,
		GENERIC_WRITE,
		FILE_SHARE_READ,
		NULL,
		CREATE_ALWAYS,
		FILE_ATTRIBUTE_TEMPORARY,
		NULL );
	if ( hpf == INVALID_HANDLE_VALUE ) {
		err = GetLastError();
		CosignLog( L"CreateFile failed with 0x%x", err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	// Retrieve proxy cookies and store
	Snet*	snet = curConnection;
	std::string out = "RETR " + cookie + " cookies\r\n";
	CosignTrace1( ">> %s", out.c_str() );
	if ( snet->write( out ) == -1 ) {
		CosignLog( "Error writing data to socket \"%s\"\n", out.c_str() );
      goto done;
	}

	while(1) {

		if ( snet->getLine() == -1 ) {
			CosignLog( L"Error reading data from socket" );
         goto done;
		}
		in = snet->data;

		for ( index = 0; index < in.length(); index += 2 ) {
			last = index;
			index = in.find( crlf, index );
			line = in.substr( last, index - last );
			CosignTrace1( "Parsed line << %s", line.c_str() );
			if ( line.length() < 4 ) {
				CosignTrace1( "Error RETR cookies.  Expected more data: %s", in.c_str() );
            goto done;
			}
			status = line.substr( 0, 4 );
			if ( status[ 0 ] != '2' ||
				!isdigit( status[ 1 ] ) ||
				!isdigit( status[ 2 ] ) ) {
				CosignTrace1( "Error RETR cookies.  Server replied: %s", in.c_str() );
            goto done;
			}
			if ( status[ 3 ] == '-' ) {
				// Write cookie to file
				bytesWritten = 0;
				line.replace( 0, 4, "" );
				line += "\r\n";
				const char*	szLine = line.c_str();
				CosignTrace1( "Writing to file: %s", line.c_str() );
				if ( !WriteFile( hpf,
					line.c_str(),
					(DWORD)line.length(),
					&bytesWritten,
					NULL ) ) {

					err = GetLastError();
					CosignLog( L"WriteFile(%s) failed with 0x%x", out.c_str(), err );
					throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
				}
			}
		}
		if ( status.length() >= 4 && status[ 3 ] != '-' ) {
			CosignTrace0( L"Breaking out of RETR loop" );
         success = 1;
			break;
		}
	}

done:
	if ( hpf != INVALID_HANDLE_VALUE ) {
		if ( !CloseHandle( hpf ) ) {
			CosignLog( L"CloseHandle( proxyTmpFile ) failed with 0x%x", GetLastError() );
		}
	}
   if ( !success ) {
      CosignLog( L"Failed to retrieve proxy cookies" );
      return;
   }
	
	std::wstring	wcookie;
	StringToWString( cookie, wcookie );
	index = wcookie.find( L'=' );
	index++;
	if ( index != std::wstring::npos ) {
		wcookie.replace( 0, index, L"" );
	}
	std::wstring	proxyCookiePath = this->proxyCookiesDirectory + wcookie;

	CosignTrace2( L"Copying %s to %s", tempFileName, proxyCookiePath.c_str() );
	if ( !CopyFileEx( tempFileName, proxyCookiePath.c_str(), NULL, NULL, FALSE, 0 ) ) {
		err = GetLastError();
		CosignLog( L"Could not copy file %s to %s: 0x%x", tempFileName, proxyCookiePath.c_str(), err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}
	if ( !DeleteFile( tempFileName ) ) {
		err = GetLastError();
		CosignLog( L"Could not delete temp file %s: 0x%x", tempFileName, err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	} catch ( CosignError ce ) {
		if ( hpf != INVALID_HANDLE_VALUE ) {
			if ( !CloseHandle( hpf ) ) {
				CosignLog( L"CloseHandle( proxyTmpFile ) failed with 0x%x", GetLastError() );
			}
		}
		ce.showError();
	}
}
Ejemplo n.º 7
0
INT
copy(TCHAR source[MAX_PATH],
     TCHAR dest[MAX_PATH],
     INT append,
     DWORD lpdwFlags,
     BOOL bTouch)
{
    FILETIME srctime,NewFileTime;
    HANDLE hFileSrc;
    HANDLE hFileDest;
    LPBYTE buffer;
    DWORD  dwAttrib;
    DWORD  dwRead;
    DWORD  dwWritten;
    BOOL   bEof = FALSE;
    TCHAR TrueDest[MAX_PATH];
    TCHAR TempSrc[MAX_PATH];
    TCHAR * FileName;
    SYSTEMTIME CurrentTime;

    /* Check Breaker */
    if (CheckCtrlBreak(BREAK_INPUT))
        return 0;

    TRACE ("checking mode\n");

    if (bTouch)
    {
        hFileSrc = CreateFile (source, GENERIC_WRITE, FILE_SHARE_READ,
            NULL, OPEN_EXISTING, 0, NULL);
        if (hFileSrc == INVALID_HANDLE_VALUE)
        {
            ConOutResPrintf(STRING_COPY_ERROR1, source);
            nErrorLevel = 1;
            return 0;
        }

        GetSystemTime(&CurrentTime);
        SystemTimeToFileTime(&CurrentTime, &NewFileTime);
        if (SetFileTime(hFileSrc,(LPFILETIME) NULL, (LPFILETIME) NULL, &NewFileTime))
        {
            CloseHandle(hFileSrc);
            nErrorLevel = 1;
            return 1;

        }
        else
        {
            CloseHandle(hFileSrc);
            return 0;
        }
    }

    dwAttrib = GetFileAttributes (source);

    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        nErrorLevel = 1;
        return 0;
    }

    TRACE ("getting time\n");

    GetFileTime (hFileSrc, &srctime, NULL, NULL);

    TRACE ("copy: flags has %s\n",
        lpdwFlags & COPY_ASCII ? "ASCII" : "BINARY");

    /* Check to see if /D or /Z are true, if so we need a middle
       man to copy the file too to allow us to use CopyFileEx later */
    if (lpdwFlags & COPY_DECRYPT)
    {
        GetEnvironmentVariable(_T("TEMP"),TempSrc,MAX_PATH);
        _tcscat(TempSrc,_T("\\"));
        FileName = _tcsrchr(source,_T('\\'));
        FileName++;
        _tcscat(TempSrc,FileName);
        /* This is needed to be on the end to prevent an error
           if the user did "copy /D /Z foo bar then it would be copied
           too %TEMP%\foo here and when %TEMP%\foo when it sets it up
           for COPY_RESTART, this would mean it is copying to itself
           which would error when it tried to open the handles for ReadFile
           and WriteFile */
        _tcscat(TempSrc,_T(".decrypt"));
        if (!CopyFileEx(source, TempSrc, NULL, NULL, FALSE, COPY_FILE_ALLOW_DECRYPTED_DESTINATION))
        {
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
        _tcscpy(source, TempSrc);
    }


    if (lpdwFlags & COPY_RESTART)
    {
        _tcscpy(TrueDest, dest);
        GetEnvironmentVariable(_T("TEMP"),dest,MAX_PATH);
        _tcscat(dest,_T("\\"));
        FileName = _tcsrchr(TrueDest,_T('\\'));
        FileName++;
        _tcscat(dest,FileName);
    }


    if (!IsExistingFile (dest))
    {
        TRACE ("opening/creating\n");
        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else if (!append)
    {
        TRACE ("SetFileAttributes (%s, FILE_ATTRIBUTE_NORMAL);\n", debugstr_aw(dest));
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        TRACE ("DeleteFile (%s);\n", debugstr_aw(dest));
        DeleteFile (dest);

        hFileDest =	CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else
    {
        LONG lFilePosHigh = 0;

        if (!_tcscmp (dest, source))
        {
            CloseHandle (hFileSrc);
            return 0;
        }

        TRACE ("opening/appending\n");
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

        /* Move to end of file to start writing */
        SetFilePointer (hFileDest, 0, &lFilePosHigh,FILE_END);
    }


    if (hFileDest == INVALID_HANDLE_VALUE)
    {
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_PATH_NOT_FOUND);
        nErrorLevel = 1;
        return 0;
    }

    /* A page-aligned buffer usually give more speed */
    buffer = VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
    if (buffer == NULL)
    {
        CloseHandle (hFileDest);
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_OUT_OF_MEMORY);
        nErrorLevel = 1;
        return 0;
    }

    do
    {
        ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);
        if (lpdwFlags & COPY_ASCII)
        {
            LPBYTE pEof = memchr(buffer, 0x1A, dwRead);
            if (pEof != NULL)
            {
                bEof = TRUE;
                dwRead = pEof-buffer+1;
                break;
            }
        }

        if (dwRead == 0)
            break;

        WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);
        if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
        {
            ConOutResPuts(STRING_COPY_ERROR3);

            VirtualFree (buffer, 0, MEM_RELEASE);
            CloseHandle (hFileDest);
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
    }
    while (!bEof);

    TRACE ("setting time\n");
    SetFileTime (hFileDest, &srctime, NULL, NULL);

    if ((lpdwFlags & COPY_ASCII) && !bEof)
    {
        /* we're dealing with ASCII files! */
        buffer[0] = 0x1A;
        TRACE ("appending ^Z\n");
        WriteFile (hFileDest, buffer, sizeof(CHAR), &dwWritten, NULL);
    }

    VirtualFree (buffer, 0, MEM_RELEASE);
    CloseHandle (hFileDest);
    CloseHandle (hFileSrc);

    TRACE ("setting mode\n");
    SetFileAttributes (dest, dwAttrib);

    /* Now finish off the copy if needed with CopyFileEx */
    if (lpdwFlags & COPY_RESTART)
    {
        if (!CopyFileEx(dest, TrueDest, NULL, NULL, FALSE, COPY_FILE_RESTARTABLE))
        {
            nErrorLevel = 1;
            DeleteFile(dest);
            return 0;
        }
        /* Take care of file in the temp folder */
        DeleteFile(dest);

    }

    if (lpdwFlags & COPY_DECRYPT)
        DeleteFile(TempSrc);

    return 1;
}
Ejemplo n.º 8
0
COSIGNSTATUS
CookieDatabase::StoreCookie( std::wstring& cookie, CosignServiceInfo* csi ) {

	DWORD	err;
	WCHAR	tempFileName[ 32768 ];
	HANDLE hcf;
	COSIGNSTATUS	status = COSIGNOK;

	try {

	CosignLog( L"path = %s", path.c_str() );
	if ( GetTempFileName( path.c_str(), L"cck", 0, tempFileName ) == 0 ) {
		err = GetLastError();
		CosignLog( L"GetTempFileName failed with 0x%x", err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}
	CosignLog( L"tempFileName = %s", tempFileName );
	hcf = CreateFile( tempFileName,
		GENERIC_WRITE,
		FILE_SHARE_READ,
		NULL,
		CREATE_ALWAYS,
		FILE_ATTRIBUTE_TEMPORARY,
		NULL );
	if ( hcf == INVALID_HANDLE_VALUE ) {
		err = GetLastError();
		CosignLog( L"CreateFile failed with 0x%x", err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	std::string out = "i" + csi->ipAddr + "\r\n";
	DWORD	bytesWritten = 0;
	if ( !WriteFile( hcf,
		out.c_str(),
		(DWORD)out.length(),
		&bytesWritten,
		NULL ) ) {

		err = GetLastError();
		CosignLog( L"WriteFile(%s) failed with 0x%x", out.c_str(), err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	out = "p" + csi->user + "\r\n";
	bytesWritten = 0;
	if ( !WriteFile( hcf,
		out.c_str(),
		(DWORD)out.length(),
		&bytesWritten,
		NULL ) ) {

		err = GetLastError();
		CosignLog( L"WriteFile(%s) failed with 0x%x", out.c_str(), err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	out = "r" + csi->realm + "\r\n";
	bytesWritten = 0;
	if ( !WriteFile( hcf,
		out.c_str(),
		(DWORD)out.length(),
		&bytesWritten,
		NULL ) ) {

		err = GetLastError();
		CosignLog( L"WriteFile(%s) failed with 0x%x", out.c_str(), err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	out = "f" + csi->strFactors + "\r\n";
	bytesWritten = 0;
	if ( !WriteFile( hcf,
		out.c_str(),
		(DWORD)out.length(),
		&bytesWritten,
		NULL ) ) {

		err = GetLastError();
		CosignLog( L"WriteFile(%s) failed with 0x%x", out.c_str(), err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	if ( hcf != INVALID_HANDLE_VALUE ) {
		CloseHandle( hcf );
		hcf = INVALID_HANDLE_VALUE;
	}

	std::wstring	cookiePath = path + cookie;
	if ( !CopyFileEx( tempFileName, cookiePath.c_str(), NULL, NULL, FALSE, 0 ) ) {
		err = GetLastError();
		CosignLog( L"Could not copy file %s to %s: 0x%x", tempFileName, cookiePath.c_str(), err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}
	if ( !DeleteFile( tempFileName ) ) {
		err = GetLastError();
		CosignLog( L"Could not delete temp file %s: 0x%x", tempFileName, err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	} catch ( CosignError ce ) {
		ce.showError();
		if ( hcf != INVALID_HANDLE_VALUE ) {
			CloseHandle( hcf );
		}
		return( COSIGNERROR );
	}
	
	return( status );
}