Ejemplo n.º 1
0
// 将遍历到的文件保存
bool CLogMgr::ProcessFile(const TCHAR *filename,time_t createtime)
{
	// 把文件名保存到数组中,判断如果文件个数多于须保存个数,
	// 安照文件生成的时间对文件进行排序,删除最早生成的文件
	// 遍历返回的是最先生产的文件,故这里不需要进行排序
	// 返回是以文件的创建时间为依据,最先创建的最先返回
	time_t filecreatetime;

	filecreatetime = createtime;
	// 小于保存数目时不删除
	if (m_nSaveIndex < MAX_MAINTENANCE_LOG_NUM)
	{
		T_SNPRINTF(m_szFileName[m_nSaveIndex],(MAX_MAINTENANCE_LOG_NUM - 1), _T("%s"), filename);
		m_szFileCreateTime[m_nSaveIndex] = filecreatetime;
		m_nSaveIndex++;
	}
	else // 超过最大维护数,先排序删除最早创建的日志
	{
		// 排序
		sort();
		// 删除文件
		_tunlink(m_szFileName[0]);
		T_SNPRINTF(m_szFileName[0], (MAX_MAINTENANCE_LOG_NUM - 1), _T("%s"), filename);
		m_szFileCreateTime[0] = filecreatetime;
	}

	return true;
}
Ejemplo n.º 2
0
// Delete a tree.
// 'path' should include a trailing backslash.
void deleteTree(const STRING path)
{
	WIN32_FIND_DATA fd;

	HANDLE hSearch = FindFirstFile((path + _T("*")).c_str(), &fd);
	do
	{
		const STRING strFile = fd.cFileName;

		if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			// Delete this directory too.
			if ((strFile != _T(".")) && (strFile != _T("..")))
			{
				deleteTree(path + strFile + _T("\\"));
			}
		}
		else
		{
			// Unlink each file.
			_tunlink((path + fd.cFileName).c_str());
		}
	} while (FindNextFile(hSearch, &fd));
	FindClose(hSearch);

	// Then remove the directory.
	RemoveDirectory(path.c_str());
}
Ejemplo n.º 3
0
bool CeCosTestPlatform::SaveToDir (LPCTSTR pszDir)
{
  bool rc=false;
  void *pHandle;
  TCHAR szOrigDir[256];
  _tgetcwd(szOrigDir,sizeof szOrigDir-1);
  if(0==_tchdir(pszDir)){
    // Delete all the files under directory "pszDir"
    String strFile;
    for(bool b=CeCosTestUtils::StartSearch(pHandle,strFile);b;b=CeCosTestUtils::NextFile(pHandle,strFile)){
      if(CeCosTestUtils::IsFile(strFile)){
        _tunlink(strFile);
      }
    }
    CeCosTestUtils::EndSearch(pHandle);
    rc=true;
    // Rewrite the files
    for(int i=0;i<(signed)arPlatforms.size();i++){
      CeCosTestPlatform &t=arPlatforms[i];
      CeCosTestPlatformProperties prop(&t);
      rc&=prop.SaveToFile(t.Name());
    }
  } else {
    ERROR(_T("Failed to change to %s from %s\n"),pszDir,szOrigDir);
  }
  
  return rc;
}
Ejemplo n.º 4
0
bool CTestResource::SaveToDirectory (LPCTSTR pszDir)
{
  bool rc=false;    
  ENTERCRITICAL;
  {
    // Delete all the files under directory "pszDir"
    void *pHandle;
    TCHAR szOrigDir[256];
    _tgetcwd(szOrigDir,sizeof szOrigDir-1);
    if(0==_tchdir(pszDir)){
      String strFile;
      for(bool b=CeCosTestUtils::StartSearch(pHandle,strFile);b;b=CeCosTestUtils::NextFile(pHandle,strFile)){
        if(CeCosTestUtils::IsFile(strFile)){
          _tunlink(strFile);
        }
      }
      CeCosTestUtils::EndSearch(pHandle);
      rc=true;
      for(CTestResource *pResource=pFirstInstance;pResource;pResource=pResource->m_pNextInstance){
        CTestResourceProperties prop(pResource);
        rc&=prop.SaveToFile(pResource->FileName());
      }
    } else {
      fprintf(stderr,"Failed to change to %s from %s\n",pszDir,szOrigDir);
    }
    _tchdir(szOrigDir);
  }
  
  LEAVECRITICAL;
  
  return rc;
}
Ejemplo n.º 5
0
/*!	外部ファイルを指定でのファイルを表示
*/
BOOL CEditView::MakeDiffTmpFile2( TCHAR* tmpName, const TCHAR* orgName, ECodeType code, ECodeType saveCode )
{
	//一時
	TCHAR* pszTmpName = _ttempnam( NULL, SAKURA_DIFF_TEMP_PREFIX );
	if( NULL == pszTmpName ){
		WarningMessage( NULL, LS(STR_DIFF_FAILED) );
		return FALSE;
	}

	_tcscpy( tmpName, pszTmpName );
	free( pszTmpName );

	bool bBom = false;
	const STypeConfigMini* typeMini;
	CDocTypeManager().GetTypeConfigMini( CDocTypeManager().GetDocumentTypeOfPath( orgName ), &typeMini );
	CFileLoad	cfl( typeMini->m_encoding );
	CTextOutputStream out(tmpName, saveCode, true, false);
	if(!out){
		WarningMessage( NULL, LS(STR_DIFF_FAILED_TEMP) );
		return FALSE;
	}
	try{
		bool bBigFile;
#ifdef _WIN64
		bBigFile = true;
#else
		bBigFile = false;
#endif
		cfl.FileOpen( orgName, bBigFile, code, GetDllShareData().m_Common.m_sFile.GetAutoMIMEdecode(), &bBom );
		CNativeW cLine;
		CEol cEol;
		while( RESULT_FAILURE != cfl.ReadLine( &cLine, &cEol ) ) {
			const wchar_t*	pLineData;
			CLogicInt		nLineLen;
			pLineData= cLine.GetStringPtr(&nLineLen);
			if( 0 == nLineLen || NULL == pLineData ) break;
			if( bBom ){
				CNativeW cLine2(L"\ufeff");
				cLine2.AppendString(pLineData, nLineLen);
				out.WriteString(cLine2.GetStringPtr(), cLine2.GetStringLength());
				bBom = false;
			}else{
				out.WriteString(pLineData,nLineLen);
			}
		}
		if( bBom ){
			out.WriteString(L"\ufeff", 1);
		}
	}
	catch(...){
		out.Close();
		_tunlink( tmpName );	//関数の実行に失敗したとき、一時ファイルの削除は関数内で行う。
		WarningMessage( NULL, LS(STR_DIFF_FAILED_TEMP) );
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 6
0
/**
	@param hPrinter Handle to the printer
	@return true if successfully saved, false if failed
*/
bool CCPrintData::SaveProcessData(HANDLE hPrinter)
{
	// Get process ID
	DWORD	dwProcessID = GetCurrentProcessId();

	// Remove old data for this process, if any
	CleanData(hPrinter, dwProcessID);

	// Save temporary file:
	// Get temp filename
	TCHAR cFilename[MAX_PATH + 1], cPath[MAX_PATH + 1], cFileKey[64], cTimeKey[64];
	if (GetTempPath(MAX_PATH, cPath) == 0)
		return false;
	if (GetTempFileName(cPath, _T("CCPDF"), 0, cFilename) == 0)
		return false;

	// Save to the file
	if (!WriteToFile(cFilename))
	{
		// Didn't work! Bale!
		_tunlink(cFilename);
		return false;
	}

	// Write timestamp to registry
	_stprintf_s(cTimeKey, _S(cTimeKey), JOBDATA_TIME_KEY, dwProcessID);
	if (!CCPrintRegistry::SetRegistryDWORD(hPrinter, cTimeKey, (DWORD) time(NULL)))
	{
		_tunlink(cFilename);
		return false;
	}
	// Write filename to registry
	_stprintf_s(cFileKey, _S(cFileKey), JOBDATA_FILE_KEY, dwProcessID);
	if (!CCPrintRegistry::SetRegistryString(hPrinter, cFileKey, cFilename))
	{
		CCPrintRegistry::EraseRegistryValue(hPrinter, cTimeKey);
		_tunlink(cFilename);
		return false;
	}
	return true;
}
Ejemplo n.º 7
0
/*!	一時ファイルを作成する
	@author	MIK
	@date	2002/05/26
	@date	2005/10/29	引数変更const char* → char*
						一時ファイル名の取得処理もここでおこなう。maru
	@date	2007/08/??	kobake 機械的にUNICODE化
	@date	2008/01/26	kobake 出力形式修正
	@date	2013/06/21 エンコードをASCII系にする(SJIS固定をやめる)
*/
BOOL CEditView::MakeDiffTmpFile( TCHAR* filename, HWND hWnd, ECodeType code, bool bBom )
{
	//一時
	TCHAR* pszTmpName = _ttempnam( NULL, SAKURA_DIFF_TEMP_PREFIX );
	if( NULL == pszTmpName ){
		WarningMessage( NULL, LS(STR_DIFF_FAILED) );
		return FALSE;
	}

	_tcscpy( filename, pszTmpName );
	free( pszTmpName );

	//自分か?
	if( NULL == hWnd )
	{
		EConvertResult eWriteResult = CWriteManager().WriteFile_From_CDocLineMgr(
			m_pcEditDoc->m_cDocLineMgr,
			SSaveInfo(
				filename,
				code,
				EOL_NONE,
				bBom
			)
		);
		return RESULT_FAILURE != eWriteResult;
	}

	CTextOutputStream out(filename, code, true, false);
	if(!out){
		WarningMessage( NULL, LS(STR_DIFF_FAILED_TEMP) );
		return FALSE;
	}

	bool bError = false;
	try{
		if( ! MakeDiffTmpFile_core(out, hWnd, *this, bBom) ){
			bError = true;
		}
	}
	catch(...){
		bError = true;
	}
	if( bError ){
		out.Close();
		_tunlink( filename );	//関数の実行に失敗したとき、一時ファイルの削除は関数内で行う。2005.10.29
		WarningMessage( NULL, LS(STR_DIFF_FAILED_TEMP) );
	}

	return TRUE;
}
Ejemplo n.º 8
0
/**
	@param hPrinter Handle to printer
	@param dwProcessID Process ID
*/
void CCPrintData::CleanData(HANDLE hPrinter, DWORD dwProcessID)
{
	TCHAR	cKey[64];
	// Get the filename from the key
	_stprintf_s(cKey, _S(cKey), JOBDATA_FILE_KEY, dwProcessID);
	std::tstring sFilename = CCPrintRegistry::GetRegistryString(hPrinter, cKey, _T(""));
	// Delete file
	if (!sFilename.empty())
		_tunlink(sFilename.c_str());
	// Erase the registry keys
	CCPrintRegistry::EraseRegistryValue(hPrinter, cKey);
	// Delete time key
	_stprintf_s(cKey, _S(cKey), JOBDATA_TIME_KEY, dwProcessID);
	CCPrintRegistry::EraseRegistryValue(hPrinter, cKey);
}
Ejemplo n.º 9
0
int
our_unlink(char *path)
{
#ifdef _WINDOWS
    LPTSTR p = NULL;
    int ret = -1;

    p = utf8_to_lptstr((LPSTR) path);

    if(p){
	ret = _tunlink(p);
	fs_give((void **) &p);
    }

    return ret;
#else /* UNIX */
    return(unlink(fname_to_locale(path)));
#endif /* UNIX */
}
Ejemplo n.º 10
0
// 实现文件转储功能
// const char *dir;      // 转储文件目录
// const char *filespec; // 转储文件规则
// const int nSaveNum;   // 保存文件数目
bool CLogMgr::FileConveySave(const TCHAR *dir,const TCHAR *filespec,const int nSaveNum)
{
	// 初始化
	memset(m_szFileName, 0x00, sizeof(m_szFileName));
	memset(m_szFileCreateTime, 0x00, sizeof(m_szFileCreateTime));
	m_nSaveIndex = 0;

	bool bRes = false;

	// 设置遍历目录
	bRes = SetInitDir(dir);
	if (!bRes)
	{
		// 转储失败
		return false;
	}
	
	// 遍历文件,并且将多余的文件删除掉(即大于保存数的文件)
	bRes = BrowseDir(m_szInitDir, filespec);
	if (!bRes)
	{
		// 遍历失败
		return false;
	}

	// 排序
	if (m_nSaveIndex > nSaveNum)
	{
		sort();

		// 循环删除多余旧文件
		for(int i = 0; i < m_nSaveIndex - nSaveNum; i++)
		{
			_tunlink(m_szFileName[i]);
		}
	}

	return true;
}
Ejemplo n.º 11
0
int c_rmdirs(const char *path) {
  _TDIR *d;
  struct _tdirent *dp;
  csync_stat_t sb;
  char *fname = NULL;
  mbchar_t *wfname = NULL;
  mbchar_t *wpath = c_utf8_to_locale(path);
  char *rd_name = NULL;

  if ((d = _topendir(wpath)) != NULL) {
    while( _tstat(wpath, &sb) == 0) {
      /* if we can remove the directory we're done */
      if (_trmdir(wpath) == 0) {
        break;
      }
      switch (errno) {
        case ENOTEMPTY:
        case EEXIST:
        case EBADF:
          break; /* continue */
        default:
          _tclosedir(d);
	  c_free_locale_string(wpath);
          return 0;
      }

      while ((dp = _treaddir(d)) != NULL) {
        size_t len;
	rd_name = c_utf8_from_locale(dp->d_name);
        /* skip '.' and '..' */
	if( c_streq( rd_name, "." ) || c_streq( rd_name, ".." ) ) {
	  c_free_locale_string(rd_name);
          continue;
        }

        len = strlen(path) + strlen(rd_name) + 2;
        fname = c_malloc(len);
        if (fname == NULL) {
          _tclosedir(d);
	  c_free_locale_string(rd_name);
	  c_free_locale_string(wpath);
          return -1;
        }
        snprintf(fname, len, "%s/%s", path, rd_name);
	wfname = c_utf8_to_locale(fname);

        /* stat the file */
        if (_tstat(wfname, &sb) != -1) {
#ifdef __unix__
          if (S_ISDIR(sb.st_mode) && !S_ISLNK(sb.st_mode)) {
#else
          if (S_ISDIR(sb.st_mode)) {
#endif
            if (_trmdir(wfname) < 0) { /* can't be deleted */
              if (errno == EACCES) {
                _tclosedir(d);
                SAFE_FREE(fname);
		c_free_locale_string(wfname);
		c_free_locale_string(rd_name);
		c_free_locale_string(wpath);
                return -1;
              }
              c_rmdirs(fname);
            }
          } else {
            _tunlink(wfname);
          }
        } /* lstat */
        SAFE_FREE(fname);
	c_free_locale_string(wfname);
	c_free_locale_string(rd_name);
      } /* readdir */

      _trewinddir(d);
    }
  } else {
    c_free_locale_string(wpath);
    return -1;
  }

  c_free_locale_string(wpath);
  _tclosedir(d);
  return 0;
}
Ejemplo n.º 12
0
int CPartFileConvert::performConvertToeMule(CString folder)
{
	BOOL bWorking;
	CString filepartindex,newfilename;
	CString buffer;
	UINT fileindex;
	CFileFind finder;
	
	CString partfile=folder;
	folder.Delete(folder.ReverseFind('\\'),folder.GetLength());
	partfile=partfile.Mid(partfile.ReverseFind('\\')+1,partfile.GetLength());


	UpdateGUI(0,GetResString(IDS_IMP_STEPREADPF),true);

	filepartindex=partfile.Left(partfile.Find('.'));
	//int pos=filepartindex.ReverseFind('\\');
	//if (pos>-1) filepartindex=filepartindex.Mid(pos+1,filepartindex.GetLength()-pos);

	UpdateGUI(4,GetResString(IDS_IMP_STEPBASICINF));

	CPartFile* file=new CPartFile();
	EPartFileFormat eFormat = PMT_UNKNOWN;
		
	if (file->LoadPartFile(folder, partfile, &eFormat) == PLR_CHECKSUCCESS)
	{
		pfconverting->partmettype = (uint8_t)eFormat;
		switch (pfconverting->partmettype)
		{
			case PMT_UNKNOWN:
			case PMT_BADFORMAT:
				delete file;
				return CONV_BADFORMAT;
				break;
		}
	}
	else
	{
		delete file;
		return CONV_BADFORMAT;
	}

	CString oldfile=folder+_T("\\")+partfile.Left(partfile.GetLength()- ((pfconverting->partmettype==PMT_SHAREAZA)?3:4) );

	pfconverting->size=file->GetFileSize();
	pfconverting->filename=file->GetFileName();
	pfconverting->filehash= EncodeBase16( file->GetFileHash() ,16);
	UpdateGUI(pfconverting);

	if (theApp.downloadqueue->GetFileByID(file->GetFileHash())!=0) {
		delete file;
		return CONV_ALREADYEXISTS;
	}
	
	if (pfconverting->partmettype==PMT_SPLITTED ) {
		try {
			CByteArray ba;
			ba.SetSize(PARTSIZE);

			CFile inputfile;
			int pos1,pos2;
			CString filename;

			// just count
			UINT maxindex=0;
			UINT partfilecount=0;
			bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part"));
			while (bWorking)
			{
				bWorking = finder.FindNextFile();
				++partfilecount;
				buffer=finder.GetFileName();
				pos1=buffer.Find('.');
				pos2=buffer.Find('.',pos1+1);
				fileindex=_tstoi(buffer.Mid(pos1+1,pos2-pos1) );
				if (fileindex==0) continue;
				if (fileindex>maxindex) maxindex=fileindex;
			}
			float stepperpart;
			if (partfilecount>0) {
				stepperpart=(80.0f / partfilecount );
				if ((uint64_t)maxindex*PARTSIZE<=pfconverting->size) pfconverting->spaceneeded=(uint64_t)maxindex*PARTSIZE;
					else pfconverting->spaceneeded=((uint64_t)(pfconverting->size / PARTSIZE) * PARTSIZE)+(pfconverting->size % PARTSIZE);
			} else {
				stepperpart=80.0f;
				pfconverting->spaceneeded=0;
			}
			
			UpdateGUI(pfconverting);

			if (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < ((uint64_t)maxindex*PARTSIZE) ) {
				delete file;
				return CONV_OUTOFDISKSPACE;
			}

			// create new partmetfile, and remember the new name
			file->CreatePartFile();
			newfilename=file->GetFullName();

			UpdateGUI(8,GetResString(IDS_IMP_STEPCRDESTFILE));
			file->m_hpartfile.SetLength( pfconverting->spaceneeded );

			uint16_t curindex=0;
			bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part"));
			while (bWorking)
			{
				bWorking = finder.FindNextFile();
				
				//stats
				++curindex;
				buffer.Format(GetResString(IDS_IMP_LOADDATA),curindex,partfilecount);
				UpdateGUI( 10+(curindex*stepperpart) ,buffer);

				filename=finder.GetFileName();
				pos1=filename.Find('.');
				pos2=filename.Find('.',pos1+1);
				fileindex=_tstoi(filename.Mid(pos1+1,pos2-pos1) );
				if (fileindex==0) continue;

				uint32_t chunkstart=(uint32_t)(fileindex-1) * PARTSIZE ;

				// open, read data of the part-part-file into buffer, close file
				inputfile.Open(finder.GetFilePath(),CFile::modeRead|CFile::shareDenyWrite);
				uint32_t readed=inputfile.Read( ba.GetData() ,PARTSIZE);
				inputfile.Close();

				buffer.Format(GetResString(IDS_IMP_SAVEDATA),curindex,partfilecount);
				UpdateGUI( 10+(curindex*stepperpart) ,buffer);

				// write the buffered data
				file->m_hpartfile.Seek(chunkstart, CFile::begin );
				file->m_hpartfile.Write(ba.GetData(),readed);
			}
		}
		catch(CFileException* error) {
			CString strError(GetResString(IDS_IMP_IOERROR));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (error->GetErrorMessage(szError, _countof(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(false, _T("%s"), strError);
			error->Delete();
			delete file;
			return CONV_IOERROR;
		}
		file->m_hpartfile.Close();
	}
	// import an external common format partdownload
	else //if (pfconverting->partmettype==PMT_DEFAULTOLD || pfconverting->partmettype==PMT_NEWOLD || Shareaza  ) 
	{
		
		if (!pfconverting->removeSource) 
			pfconverting->spaceneeded = (UINT)GetDiskFileSize(oldfile);

		UpdateGUI(pfconverting);

		if (!pfconverting->removeSource && (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < pfconverting->spaceneeded) ) {
			delete file;
			return CONV_OUTOFDISKSPACE;
		}

		file->CreatePartFile();
		newfilename=file->GetFullName();

		file->m_hpartfile.Close();

		BOOL ret=FALSE;
		UpdateGUI( 92 ,GetResString(IDS_COPY));
		DeleteFile(newfilename.Left(newfilename.GetLength()-4));

		if (!PathFileExists(oldfile)) {
			// data file does not exist. well, then create a 0 byte big one
			HANDLE hFile = CreateFile( newfilename.Left(newfilename.GetLength()-4) ,    // file to open
							GENERIC_WRITE,          // open for reading
							FILE_SHARE_READ,       // share for reading
							NULL,                  // default security
							CREATE_NEW,         // existing file only
							FILE_ATTRIBUTE_NORMAL, // normal file
							NULL);                 // no attr. template
			 
			ret= !(hFile == INVALID_HANDLE_VALUE) ;

			CloseHandle(hFile);
		}
			else 
		if (pfconverting->removeSource) 
			ret=MoveFile( oldfile, newfilename.Left(newfilename.GetLength()-4) );
		else 
			ret=CopyFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ,false);

		if (!ret) {
			file->DeleteFile();
			//delete file;
			return CONV_FAILED;
		}

	}


	UpdateGUI( 94 ,GetResString(IDS_IMP_GETPFINFO));

	DeleteFile(newfilename);
	if (pfconverting->removeSource)
		MoveFile(folder+_T("\\")+partfile,newfilename);
	else CopyFile(folder+_T("\\")+partfile,newfilename,false);


	file->m_hasharray.release();
	for ( GapList::iterator it = file->gaplist.begin(); it != file->gaplist.end(); ++it ) {
		delete *it;
	}
	file->gaplist.clear();

	if (file->LoadPartFile(thePrefs.GetTempDir(), file->GetPartMetFileName()) != PLR_LOADSUCCESS) {
		//delete file;
		file->DeleteFile();
		return CONV_BADFORMAT;
	}

	if (pfconverting->partmettype==PMT_NEWOLD || pfconverting->partmettype==PMT_SPLITTED ) {
		file->completedsize = file->m_uTransferred;
		file->m_uCompressionGain = 0;
		file->m_uCorruptionLoss = 0;
	}

	UpdateGUI( 100 ,GetResString(IDS_IMP_ADDDWL));

	theApp.downloadqueue->AddDownload(file,thePrefs.AddNewFilesPaused());
	file->SavePartFile();
	
	if (file->GetStatus(true) == PS_READY)
		theApp.sharedfiles->SafeAddKFile(file); // part files are always shared files


	if (pfconverting->removeSource) {

		bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*"));
		while (bWorking)
		{
			bWorking = finder.FindNextFile();
			VERIFY( _tunlink(finder.GetFilePath()) == 0 );
		}

		if (pfconverting->partmettype==PMT_SPLITTED)
			RemoveDirectory(folder+_T("\\"));
	}

	return CONV_OK;
}
Ejemplo n.º 13
0
int ZipFunc::replaceOrig(const DZStrW &d, const DZStrW& s)
{
    struct stati64 t;        // results of stat()
    int         copy = 0;
    int         d_exists;

	d_exists = _tstati64(d, &t) == 0;
	if (d_exists)
	{
		// respect existing soft and hard links!
		if (t.st_nlink > 1)
			copy = 1;
        else
        {
            if (_tunlink(d))
                return DZ_ERM_ERROR_CREATE;      // Can't erase zip file--give up
            Sleep(5);
        }
    }
    if (!copy)
    {
            // Just move s on top of d
        if (_trename(s, d))// !MoveFile(s, d))
        {
            if (Verbose < 0)
                Notify(IERROR, _T(" replace failed %s (%s)"), s, errno);
            copy = 1;                   // failed ?
            if (errno != ENOTSAM)
				return DZ_ERM_ERROR_CREATE;
        }
    }

    if (copy)
    {
        HANDLE  f,
        g;                    // source and destination files
        int     r;                    // temporary variable
        diag(_T("in replace - open for read"));

        if ((f = CreateFile(s, GENERIC_READ, 0, NULL, OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL)) <= 0)
        {
            diag(_T("in replace - bad open for Read"));
            Notify(0, _T(" replace: can't open %s [%s]"), s, SysMsg());

			return DZ_ERM_TEMP_FAILED;
        }

        diag(_T("in replace - fopen for write"));

        if ((g = CreateFile(d, GENERIC_WRITE, 0, NULL, CREATE_NEW,
                            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL)) <= 0)
        {
            Close_Handle(&f);
            diag(_T("in replace - bad open for Write"));
			return DZ_ERM_ERROR_CREATE;
        }

        r = filecopy(f, g);

        Close_Handle(&f);
        if (!Close_Handle(&g) || r != DZ_ERR_GOOD)
        {
            DeleteFile(d);
            return r ? (DZ_ERR(r) == DZ_ERR_TEMP_FAILED ? DZ_ERR_ERROR_WRITE : r) : DZ_ERM_ERROR_WRITE;
        }

        DeleteFile(s);
    }

    return DZ_ERR_GOOD;
}
Ejemplo n.º 14
0
static int _csync_statedb_check(const char *statedb) {
  int fd = -1, rc;
  ssize_t r;
  char buf[BUF_SIZE] = {0};
  sqlite3 *db = NULL;
  csync_stat_t sb;

  mbchar_t *wstatedb = c_utf8_to_locale(statedb);

  if (wstatedb == NULL) {
    return -1;
  }

  /* check db version */
#ifdef _WIN32
    _fmode = _O_BINARY;
#endif

    fd = _topen(wstatedb, O_RDONLY);

    if (fd >= 0) {
        /* Check size. Size of zero is a valid database actually. */
        rc = _tfstat(fd, &sb);

        if (rc == 0) {
            if (sb.st_size == 0) {
                CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "Database size is zero byte!");
                close(fd);
            } else {
                r = read(fd, (void *) buf, sizeof(buf) - 1);
                close(fd);
                if (r >= 0) {
                    buf[BUF_SIZE - 1] = '\0';
                    if (c_streq(buf, "SQLite format 3")) {
                        if (sqlite3_open(statedb, &db ) == SQLITE_OK) {
                            rc = _csync_check_db_integrity(db);
                            if( sqlite3_close(db) != 0 ) {
                                CSYNC_LOG(CSYNC_LOG_PRIORITY_NOTICE, "WARN: sqlite3_close error!");
                            }

                            if( rc >= 0 ) {
                                /* everything is fine */
                                c_free_locale_string(wstatedb);
                                return 0;
                            }
                            CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "Integrity check failed!");
                        } else {
                            /* resources need to be freed even when open failed */
                            sqlite3_close(db);
                            CSYNC_LOG(CSYNC_LOG_PRIORITY_WARN, "database corrupted, removing!");
                        }
                    } else {
                        CSYNC_LOG(CSYNC_LOG_PRIORITY_WARN, "sqlite version mismatch");
                    }
                }
            }
        }
        /* if it comes here, the database is broken and should be recreated. */
        _tunlink(wstatedb);
    }

  c_free_locale_string(wstatedb);

  /* create database */
  rc = sqlite3_open(statedb, &db);
  if (rc == SQLITE_OK) {
    sqlite3_close(db);
    _csync_win32_hide_file(statedb);
    return 1;
  }
  sqlite3_close(db);
   CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "sqlite3_open failed: %s %s", sqlite3_errmsg(db), statedb);
   return -1;
}
Ejemplo n.º 15
0
int csync_statedb_close(const char *statedb, sqlite3 *db, int jwritten) {
  char *statedb_tmp = NULL;
  mbchar_t* wstatedb_tmp = NULL;
  int rc = 0;

  mbchar_t *mb_statedb = NULL;

  /* deallocate query resources */
  rc = sqlite3_finalize(_by_hash_stmt);
  _by_hash_stmt = NULL;

  /* close the temporary database */
  sqlite3_close(db);

  if (asprintf(&statedb_tmp, "%s.ctmp", statedb) < 0) {
    return -1;
  }

  /* If we successfully synchronized, overwrite the original statedb */

  /*
   * Check the integrity of the tmp db. If ok, overwrite the old database with
   * the tmp db.
   */
  if (jwritten) {
      /* statedb check returns either
       * 0  : database exists and is fine
       * 1  : new database was set up
       * -1 : error.
       */
      if (_csync_statedb_check(statedb_tmp) >= 0) {
          /* New statedb is valid. */
          mb_statedb = c_utf8_to_locale(statedb);

          /* Move the tmp-db to the real one. */
          if (c_rename(statedb_tmp, statedb) < 0) {
              CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG,
                        "Renaming tmp db to original db failed. (errno=%d)", errno);
              rc = -1;
          } else {
              CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG,
                        "Successfully moved tmp db to original db.");
          }
      } else {
          mb_statedb = c_utf8_to_locale(statedb_tmp);
          _tunlink(mb_statedb);

          /* new statedb_tmp is not integer. */
          CSYNC_LOG(CSYNC_LOG_PRIORITY_ERROR, "  ## csync tmp statedb corrupt. Original one is not replaced. ");
          rc = -1;
      }
      c_free_locale_string(mb_statedb);
  }

  wstatedb_tmp = c_utf8_to_locale(statedb_tmp);
  if (wstatedb_tmp) {
      _tunlink(wstatedb_tmp);
      c_free_locale_string(wstatedb_tmp);
  }

  SAFE_FREE(statedb_tmp);

  return rc;
}