DWORD WINAPI sendFileThread(LPVOID lpParam)
{
	char *filename = (char *)lpParam;
	try
	{
		char installPath[1024];
		CModuleUtil::getInstallPath(installPath);

		char fname[1024];
		sprintf(fname, "%s\\%s", installPath, filename);
		char fnameGz[1024];
		sprintf(fnameGz, "%s\\%s.gz", installPath, filename);
		char remoteFileName[128];
		sprintf(remoteFileName, "incoming/%s-%d-%d.gz", filename, time(NULL), rand());
		file_compress(fname, "wb");
		CInternetSession session;
		CFtpConnection *ftpConnection = session.GetFtpConnection("upload.tibiaauto.net", "anonymous", "*****@*****.**", 21, true);
		ftpConnection->PutFile(fnameGz, remoteFileName);
		ftpConnection->Close();
		delete ftpConnection;


		_unlink(fname);
		_unlink(fnameGz);

		fileSendingProgress = 1;
	}
	catch (CInternetException*)
	{
		fileSendingProgress = -1;
	}
	return 0;
}
Exemple #2
0
BOOL CFtpFileDlg::PutFile( CString strSourceName,CString strDesName )
{
	CInternetSession* pSession;
	CFtpConnection *pConnection;
	pConnection = NULL;
	pSession = new CInternetSession(AfxGetAppName(),1,PRE_CONFIG_INTERNET_ACCESS);
	try{
		pConnection = pSession->GetFtpConnection(m_strFtpSite,m_strName,m_strPwd);
	}
	catch(CInternetException *e){
		e->Delete();
		pConnection = NULL;
		return FALSE;
	}
	if(pConnection != NULL){
		if (!pConnection->PutFile(strSourceName,strDesName)){
			pConnection->Close();
			delete pConnection;
			delete pSession;
			return FALSE;
		}
	}
	if (pConnection != NULL){
		pConnection->Close();
		delete pConnection;
	}
	delete pSession;
	return TRUE;
}
Exemple #3
0
vmd_ftpclient(const char * site, 
            const char * remotefile, 
            const char * localfile) {
  CInternetSession S("Eagle FTP"); 
  CFtpConnection *f; 

  try { 
    f = S.GetFtpConnection(site,
                           "anonymous",
                           "*****@*****.**",
                           21,
                           FALSE); 
    f->SetCurrentDirectory("/"); 
    f->GetFile(remotefile, localfile,
               FALSE,
               FILE_ATTRIBUTE_NORMAL,
               FTP_TRANSFER_TYPE_BINARY,
               1);
    
    delete f; 
    S.Close(); 
  
    return FTP_SUCCESS;
  } 

  catch (CInternetException) { 
    printf("FTP Error!\n"); 
    return FTP_FAILURE;
  } 

  return FTP_SUCCESS;
} 
Exemple #4
0
void CFtpFileDlg::ListContent()
{
	CInternetSession* pSession;
	CFtpConnection* pConnection;
	CFtpFileFind* pFileFind;
	CString strFileName;
	BOOL bContinue;
	pConnection = NULL;
	pFileFind = NULL;
	pSession = new CInternetSession(AfxGetAppName(),1,PRE_CONFIG_INTERNET_ACCESS);
	try{
		pConnection = pSession->GetFtpConnection(m_strFtpSite,m_strName,m_strPwd);
	}
	catch(CInternetException *e){
		e->Delete();
		pConnection = NULL;
		AfxMessageBox("连接失败!",MB_OK|MB_ICONSTOP);
	}
	if (pConnection!= NULL){
		pFileFind = new CFtpFileFind(pConnection);
		bContinue = pFileFind->FindFile(NULL);
		if (!bContinue){
			pFileFind->Close();
			pFileFind=NULL;
		}
		while(bContinue){
			bContinue = pFileFind->FindNextFile();
			strFileName = pFileFind->GetFileName();
			if (pFileFind->IsDirectory())
			{
				strFileName = "["+strFileName;
				strFileName += "]";
			}
			m_ListFile.AddString(strFileName);
		}
		if (pFileFind!=NULL){
			pFileFind->Close();
			pFileFind=NULL;
		}
	}
	delete pFileFind;
	if (pConnection!=NULL){
		pConnection->Close();
		delete pConnection;
	}
	delete pSession;
}
DWORD WINAPI sendMapsThread(LPVOID lpParam)
{
	char *path = (char *)lpParam;

	try
	{
		char fullMask[1024];
		sprintf(fullMask, "%s\\*.map", path);
		WIN32_FIND_DATA data;
		HANDLE hFind = FindFirstFile(fullMask, &data);
		if (hFind != INVALID_HANDLE_VALUE)
		{
			CInternetSession session;
			CFtpConnection *ftpConnection = session.GetFtpConnection("upload.tibiaauto.net", "anonymous", "*****@*****.**", 21, true);
			time_t t                      = time(NULL);
			int r                         = rand();
			int lastfile                  = 1;
			while (lastfile)
			{
				char fname[128];
				char fnameGz[128];
				sprintf(fname, "%s\\%s", path, data.cFileName);
				sprintf(fnameGz, "%s\\%s.gz", path, data.cFileName);
				char remoteFileName[128];
				sprintf(remoteFileName, "incoming/%s-%d-%d.gz", data.cFileName, t, r);
				file_compress(fname, "wb");

				ftpConnection->PutFile(fnameGz, remoteFileName);

				_unlink(fnameGz);
				lastfile = FindNextFile(hFind, &data);
			}
			ftpConnection->Close();
			delete ftpConnection;
		}

		fileSendingProgress = 1;
	}
	catch (CInternetException*)
	{
		fileSendingProgress = -1;
	}
	// allocated before starting a thread
	free(path);
	return 0;
}
/**
* 数据文件保存到FTP服务器
* @param void
* @return bool true:成功;false:失败
*/
bool CThreadProcSiteDataOutput::SaveDataFileToFTPServer()
{
	bool bReturn = false;
	CInternetSession oSession;
	BOOL bData;
	CFtpConnection* pConnection = oSession.GetFtpConnection(m_pSiteData->m_strIPFTPServer);

	bData = SaveDataFileToFTPServer(pConnection, "..\\data\\FileInstrument.dat", "\\data\\FileInstrument.dat");
	if(TRUE == bData)
	{
		bData = SaveDataFileToFTPServer(pConnection, "..\\data\\FileRout.dat", "\\data\\FileRout.dat");
		if(TRUE == bData)
		{
			bData = SaveDataFileToFTPServer(pConnection, "..\\data\\FileChannel.dat", "\\data\\FileChannel.dat");
			if(TRUE == bData)
			{
				bReturn = true;
			}
		}
	}
	pConnection->Close();
	delete pConnection;
	return bReturn;
}
//启动上传文件的线程
DWORD WINAPI FtpConnecter::UploadeFile(LPVOID param)
{
	s_bThreadRunning = TRUE;//记录上传线程已启动
	FtpInfo* pFtpInfo = (FtpInfo*)param;
	//连接FTP服务器,并开始推送文件
	static int count = 0;
	CString strCount;
	try
	{
		while (1)
		{
			if (s_bStopTask)//如果要停止任务那么就跳出
				break;
			pushTrackInfo(L"等待下一次上传任务");
			if (WaitForSingleObject(pFtpInfo->_hWaitableTimer, INFINITE) != WAIT_OBJECT_0)
				break;
			//更新本次上传的本地和远程文件夹的信息
			PostMessage(AfxGetApp()->m_pMainWnd->GetSafeHwnd(), WM_UpdateRemoteFolderPath, 0, 0);
			PostMessage(AfxGetApp()->m_pMainWnd->GetSafeHwnd(), WM_UpdateLocalFolderPath, 0, 0);
			if (count == 0)
			{
				count++;
				pushTrackInfo(L"首次启动FTP上传线程,不做上传任务");
				continue;
			}
			pushTrackInfo(L"开始上传任务");
			strCount.Format(_T("开始第%d次上传任务"), ++count);
			pushTrackInfo(strCount);
			if (s_bStopTask)//如果要停止任务那么就跳出
				break;
			CInternetSession InternetSession(_T("MR"), INTERNET_OPEN_TYPE_PRECONFIG);
			CFtpConnection* pFtpconnection = InternetSession.GetFtpConnection(
				pFtpInfo->_strFtpServerIp, 
				pFtpInfo->_strUserName, 
				pFtpInfo->_strUserPw, 
				pFtpInfo->_nFtpServerPort, 
				TRUE);

			CString strRemotePath = getRemoteFolderPath();
			CString strLocalPath = getLocalFolderPath();
			pushTrackInfo(_T("上传本地文件夹 ") + strLocalPath);
			pushTrackInfo(_T("到FTP服务器上 ") + strRemotePath);
			std::vector<CString> files;

			//开始上传文件
			//设置ftp服务器上的路径
			CString strCurDir;
			if (strRemotePath.GetAt(strRemotePath.GetLength()-1) != _T('/'))
				strRemotePath += _T('/');
			int pos = strRemotePath.Find(_T('/'), 0);
			
			while (pos != -1)
			{
				strCurDir = strRemotePath.Left(pos);
				strRemotePath = strRemotePath.Right(strRemotePath.GetLength() - pos - 1);
				if (!strCurDir.IsEmpty())
				{
					CFtpFileFind ftpff(pFtpconnection);
					if (!ftpff.FindFile(strCurDir))//如果找不到这个目录,那么就创建之
						pFtpconnection->CreateDirectory(strCurDir);
					pFtpconnection->SetCurrentDirectory(strCurDir);
				}
				pos = strRemotePath.Find(_T('/'), 0);
			}
			
			//获得本地全部要上传的文件
			if (!getAllFilesUpload(files))
				s_bThreadRunning = FALSE;

			PostMsg2Php post2php;
			BOOL bPut;
			CString strFilePath;
			for (std::vector<CString>::iterator iter = files.begin(); iter != files.end(); ++iter)
			{
				strFilePath = strLocalPath + _T("\\") + *iter;
				pushTrackInfo(_T("开始上传 ") + strFilePath);
				bPut = pFtpconnection->PutFile(strFilePath, *iter);
				if (!bPut)//如果上传不成功那么就记录下来
				{
					pushTrackInfo(*iter + _T(" 上传失败"));
					s_FileFailedUpload.push_back(*iter);
					s_bHasUploadFailedFile = TRUE;
				}
				else
				{
					pushTrackInfo(*iter + _T(" 上传成功"));
					post2php.PostResult(strFilePath, PostMsg2Php::Upload, PostMsg2Php::Suc);
				}
			}
			if (s_bRetryUpload && s_bHasUploadFailedFile)//如果要重试上传并且也有文件上传失败
			{
				s_bHasUploadFailedFile = FALSE;
				for (std::vector<CString>::iterator iter = s_FileFailedUpload.begin(); iter != s_FileFailedUpload.end(); ++iter)
				{
					static CString str;
					str = _T("尝试再次上传文件 ") + strLocalPath + _T("\\") + *iter;
					pushTrackInfo(str);
					strFilePath = strLocalPath + _T("\\") + *iter;
					bPut = pFtpconnection->PutFile(strFilePath, *iter);
					if (!bPut)
					{
						pushTrackInfo(L"尝试失败 : " + strLocalPath + _T("\\") + *iter);
						post2php.PostResult(strFilePath, PostMsg2Php::Upload, PostMsg2Php::Failed);
						s_bHasUploadFailedFile = TRUE;
					}
					else 
					{
						pushTrackInfo(L"尝试成功 : " + strLocalPath + _T("\\") + *iter);
					}
				}
			}
			if (pFtpconnection)
			{
				pFtpconnection->Close();
				delete pFtpconnection;
			}
			strCount.Format(_T("第%d次上传任务完成,总共%d个, 成功%d个,失败%d个"), count, files.size(), files.size()-s_FileFailedUpload.size(), s_FileFailedUpload.size());
			pushTrackInfo(strCount);
			s_FileFailedUpload.clear();
		}
	}
	catch (CInternetException* pEx)
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		pushTrackInfo(_T("FTP连接失败"));
		pushTrackInfo(szErr);
		pEx->Delete();
		s_bThreadRunning = FALSE;
		return -1;
	}
	s_bThreadRunning = FALSE;
	return 0;
}
Exemple #8
0
bool CFTPDlg::GetFtpFile()
{
	CInternetSession sess(0, 0, INTERNET_OPEN_TYPE_DIRECT);
	unsigned long timeOut = 300000;
	sess.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, timeOut);
	sess.SetOption(INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, timeOut);    
	sess.SetOption(INTERNET_OPTION_CONTROL_SEND_TIMEOUT, timeOut);    
	sess.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, timeOut * 10);    
	sess.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, timeOut * 10);    
	sess.SetOption(INTERNET_OPTION_SEND_TIMEOUT, timeOut);  
	sess.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, timeOut * 10);  
	sess.SetOption(INTERNET_OPTION_DISCONNECTED_TIMEOUT, timeOut);  
	sess.SetOption(INTERNET_OPTION_FROM_CACHE_TIMEOUT, timeOut);  
	sess.SetOption(INTERNET_OPTION_LISTEN_TIMEOUT, timeOut);  

	CString strMsg;
	bool isFileExist = false;
	m_progress.SetPos(0);
	try
	{      
		CString sHost;
		CString sUsername; 
		CString sPassword; 
		CString sPort; 
		m_host.GetWindowText(sHost);
		m_name.GetWindowText(sUsername);
		m_pwd.GetWindowText(sPassword);
		m_port.GetWindowText(sPort);
		int nPort  = atoi(sPort); 
#ifdef FTP_PASSIVE
		CFtpConnection* pConnect = sess.GetFtpConnection(sHost, sUsername, sPassword, nPort, false);
#else
		CFtpConnection* pConnect = sess.GetFtpConnection(sHost, sUsername, sPassword, nPort, true);
#endif
		strMsg.Format("connect to %s successful!", sHost);
		m_text.SetWindowText(strMsg);

		CString strLocalName, strRemotePath;
		strLocalName = m_ephFileName;
		strRemotePath.Format("ephemeris\\%s", strLocalName);

		strMsg.Format("Downloading %s from %s", strLocalName, sHost);
		m_text.SetWindowText(strMsg);
		if(!pConnect->GetFile(strRemotePath, strLocalName, false))
		{
			DWORD err = GetLastError();
			strMsg = Utility::ErrorString(err);
			AfxMessageBox(strMsg);
		}
		else
		{
			isFileExist = true;
		}

		if(pConnect != NULL)
		{
			pConnect->Close();
		}
		delete pConnect;
	}
	catch (CInternetException* pEx)
	{
		TCHAR sz[1024];
		pEx->GetErrorMessage(sz, 1024);
		printf("ERROR!  %s\n", sz);
		pEx->Delete();
		AfxMessageBox(sz);
	}

	return isFileExist;
}
DWORD WINAPI sendPacketLogThread(LPVOID lpParam)
{
	char path[1024];
	CModuleUtil::getInstallPath(path);
	char fullMask[1024];
	sprintf(fullMask, "%s\\tascripts\\* statistics.txt", path);
	WIN32_FIND_DATA data;
	HANDLE hFind = FindFirstFile(fullMask, &data);
	if (hFind != INVALID_HANDLE_VALUE)
	{
		char fname[128];
		int lastfile = 1;
		while (lastfile)
		{
			sprintf(fname, "%s\\tascripts\\%s", path, data.cFileName);
			FILE* f = fopen(fname, "a+");
			if (f)
			{
				fseek(f, 0, SEEK_END);
				int flen = ftell(f);
				fclose(f);
				if (flen > 1000)
					goto sendFiles;
			}
			lastfile = FindNextFile(hFind, &data);
		}
	}
	{
		hFind = FindFirstFile(fullMask, &data);
		if (hFind != INVALID_HANDLE_VALUE)
		{
			char fname[128];
			int lastfile = 1;
			while (lastfile)
			{
				sprintf(fname, "%s\\tascripts\\%s", path, data.cFileName);
				_unlink(fname);
				lastfile = FindNextFile(hFind, &data);
			}
		}
		fileSendingProgress = 1;
		return 0;
	}
sendFiles:
	int msgboxID = -1;
	if (!CModuleUtil::getTASetting("RemoveBotStatsMessage"))
		msgboxID = MessageBox(NULL, "TA is about to send your botting statistics to TA.net. You can edit this option in \"General options and statistics\".\n\nWould you like to receive this message every time before TA sends this data?\nUse cancel to stop the operation.", "Submit Botting Data", MB_YESNOCANCEL);
	if (msgboxID == IDCANCEL)
		return 0;
	try
	{
		hFind = FindFirstFile(fullMask, &data);
		if (hFind != INVALID_HANDLE_VALUE)
		{
			CInternetSession session;
			CFtpConnection *ftpConnection = session.GetFtpConnection("upload.tibiaauto.net", "anonymous", "*****@*****.**", 21, true);
			time_t t                      = time(NULL);
			unsigned long serialNumber;
			GetVolumeInformation(NULL, NULL, 0, &serialNumber, NULL, NULL, NULL, 0);
			unsigned int r = serialNumber % 0x1000000;
			int lastfile   = 1;
			while (lastfile)
			{
				char fname[128];
				char fnameGz[128];
				sprintf(fname, "%s\\tascripts\\%s", path, data.cFileName);
				sprintf(fnameGz, "%s\\tascripts\\%s.gz", path, data.cFileName);
				char remoteFileName[128];
				sprintf(remoteFileName, "incoming/%s-%d-%u.gz", data.cFileName, t, r);
				file_compress(fname, "wb");

				ftpConnection->PutFile(fnameGz, remoteFileName);

				_unlink(fnameGz);
				lastfile = FindNextFile(hFind, &data);
				_unlink(fname);
			}
			ftpConnection->Close();
			delete ftpConnection;
		}

		fileSendingProgress = 1;
		if (!CModuleUtil::getTASetting("RemoveBotStatsMessage"))
			AfxMessageBox("Thank you for submitting \"botting statistics.txt\" and \"module statistics.txt\".\n\nNo personally identifiable information was sent.\nThis botting information will be analysed and used to help prevent CIPSoft from automatically detecting TA in the future. You can change this setting in \"General Options and Statistics\".\n\nTA users thank you for helping us towards this end.\n~TA Team");
	}
	catch (CInternetException*)
	{
		if (!CModuleUtil::getTASetting("RemoveBotStatsMessage"))
			AfxMessageBox("Failed to send file. Check your connection to the internet.");
		fileSendingProgress = -1;
	}
	if (msgboxID == IDNO)
		CModuleUtil::setTASetting("RemoveBotStatsMessage", 1);
	return 0;
}
void CFtpDownloadThread::Run()
{
	USES_CONVERSION;
	CInternetSession InternetSession;
	CFtpConnection * pFtpConn = NULL;
	CInternetFile * pFtpFile = NULL;
	CString strFtpUrl, fileDir;
	CFileException fileException;
	CFile file;
	UINT nFtpReadSize = 0;
	BYTE buffer[1024] = {0};
	BOOL bIsOpenFile = FALSE;
	CFtpFileFind * pFtpFind = NULL;
	
	strFtpUrl.Format(_T("%s"), A2W(m_strFptURL.c_str()));
	
	try {
		pFtpConn = InternetSession.GetFtpConnection(strFtpUrl, 
			m_strUsr.c_str()?NULL:m_strUsr.c_str(), m_strPwd.c_str()?NULL:m_strPwd.c_str(), m_nftpPort);
	}
	catch (CInternetException * pEx)
	{
		TCHAR sz[1024];
		pEx->GetErrorMessage(sz, 1024);
		AfxMessageBox(sz);
		pEx->Delete();
		m_nErrorCode = FTP_SERVER_CONNECT_FAILED;
		goto end;
	}
	
	if (pFtpConn == NULL) {
		m_nErrorCode = FTP_SERVER_CONNECT_FAILED;
		goto end;
	}

	fileDir.Format(_T("%s\\%s"), m_strSaveDir.c_str(), m_strFileName.c_str());
	
	UINT nMode = 0;
	
	//CInternetFile不支持FTP协议的端点续传,需要自己实现。
	/*if (PathFileExists(fileDir)) nMode = CFile::modeWrite;
	else*/ nMode = CFile::modeCreate | CFile::modeReadWrite | CFile::typeBinary;

	if (!file.Open(fileDir, nMode, &fileException)){
		m_nErrorCode = ERR_OPEN_LOACAL_SAVE_FILE;
		goto end;
	}

	bIsOpenFile = TRUE;

	file.SeekToEnd();
	m_nDownloadLen = file.GetLength();
	
	pFtpFind = new CFtpFileFind(pFtpConn);
	if (!pFtpFind->FindFile(m_strFileName.c_str())) {
		m_nErrorCode = FTP_SERVER_FILE_OPEN_ERR;
		pFtpFind->Close();
		delete pFtpFind;
		goto end;
	}
	pFtpFind->FindNextFile();
	m_nFtpFileLen = pFtpFind->GetLength();
	pFtpFind->Close();
	delete pFtpFind;
 
	pFtpFile = pFtpConn->OpenFile(m_strFileName.c_str());
	if (pFtpFile == NULL) {
		m_nErrorCode = FTP_SERVER_FILE_OPEN_ERR;
		goto end;
	}
	
	/*//CInternetFile不支持FTP协议的断点续传,需要自己实现。
	if (m_nFtpFileLen != 0)
		pFtpFile->Seek(m_nDownloadLen, CInternetFile::begin);*/
	
	while(TRUE) {
		if (!m_bIsStart) break;
		
		if (m_nDownloadLen >= m_nFtpFileLen) break;
		
		try {
			nFtpReadSize = pFtpFile->Read(buffer, sizeof(buffer));
		}
		catch (CInternetException * pEx)
		{
			TCHAR sz[1024];
			pEx->GetErrorMessage(sz, 1024);
			AfxMessageBox(sz);
			pEx->Delete();
			m_nErrorCode = FTP_SERVER_CONNECT_FAILED;
			goto end;
		}

		if (nFtpReadSize <= 0) continue;
		
		try {
			file.Write(buffer, sizeof(buffer));
		}catch(CFileException * pEx) {
			TCHAR sz[1024];
			pEx->GetErrorMessage(sz, 1024);
			AfxMessageBox(sz);
			pEx->Delete();
			m_nErrorCode = ERR_WRITE_LOCAL_FILE;
			goto end;
		}

		m_nDownloadLen += nFtpReadSize;
	}

end:
	if (pFtpFile) {
		pFtpFile->Close();
		delete pFtpFile;
	}

	if (pFtpConn) {
		pFtpConn->Close();
		delete pFtpConn;
	}

	InternetSession.Close();
	
	if (bIsOpenFile) file.Close();

	m_bIsStart = FALSE;
}
Exemple #11
0
HRESULT EMB::CTxTransFile::TansferFile()
{
	//create internet conn
	HRESULT hRet = E_FAIL;
	CFtpConnection *pFtpConnectionSrc = NULL;
	CFtpConnection *pFtpConnectionDes = NULL;

	try
	{
		CInternetSession pInetSession(NULL, 1, PRE_CONFIG_INTERNET_ACCESS);
		//set code page
		if(m_taskInfo.nCodePage == CP_UTF8)
		{
			pInetSession.SetOption(INTERNET_OPTION_CODEPAGE , CP_UTF8);
		}

		ST_FTPSITEINFO sitInfoSrc;
		ST_FTPSITEINFO sitInfoDes;
		int nFtpSrcID = -1;
		int nFtpDesID = -1;
		//find first valid ftp
		int iftpLoop = m_taskInfo.nSrcSiteTryStart;
		CFWriteLog(TEXT("start src ftp check from NO.%d"), iftpLoop);

		const int nSrcSitCount = m_taskInfo.vSitSrc.size();
		for (size_t i = 0; i < nSrcSitCount; ++i,++iftpLoop)
		{
			iftpLoop = (iftpLoop)%nSrcSitCount;
			ST_FTPSITEINFO& sitRef = m_taskInfo.vSitSrc[iftpLoop];
			try
			{
				pFtpConnectionSrc = pInetSession.GetFtpConnection(sitRef.strFtpIp, sitRef.strUser, sitRef.strPw, sitRef.nFtpPort, sitRef.nPassive);
				if (pFtpConnectionSrc)
				{
					//valid
					m_nCurrSrcSite = iftpLoop;
					sitInfoSrc = sitRef;
					CFWriteLog(TEXT("use SrcFtp:%s %s:%d %s/%s "), sitRef.strFtpName, sitRef.strFtpIp, sitRef.nFtpPort, sitRef.strUser, sitRef.strPw);
					break;
				}
			}
			catch ( CInternetException * e)
			{
				//ftp is not valid
				pFtpConnectionSrc = NULL;
				CFWriteLog(0, TEXT("ftp not valid, %s, %s:%d,%s:%s"),sitRef.strFtpName,  sitRef.strFtpIp, sitRef.nFtpPort, sitRef.strUser, sitRef.strPw);
			}
		}

		if (!pFtpConnectionSrc)
		{
			CFWriteLog(0, TEXT("no valid src ftp to use, clip trans failed, logicid = %s"), m_taskInfo.strClipLogicID);
			return EMBERR_INVALIDFTP;
		}

		//find first valid Des Ftp
		iftpLoop = m_taskInfo.nDesSiteTryStart;
		CFWriteLog(TEXT("start des ftp check from NO.%d"), iftpLoop);
		const int nDesSitCount = m_taskInfo.vSitDes.size();
		for (size_t i = 0; i < nDesSitCount; ++i,++iftpLoop)
		{
			iftpLoop = iftpLoop%nDesSitCount;
			ST_FTPSITEINFO& sitRef = m_taskInfo.vSitDes[iftpLoop];
			try
			{
				pFtpConnectionDes = pInetSession.GetFtpConnection(sitRef.strFtpIp, sitRef.strUser, sitRef.strPw, sitRef.nFtpPort, sitRef.nPassive);
				if (pFtpConnectionDes)
				{
					//valid
					m_nCurrDesSite = iftpLoop;
					sitInfoDes = sitRef;
					CFWriteLog(TEXT("use DesFtp:%s %s:%d %s/%s "), sitRef.strFtpName, sitRef.strFtpIp, sitRef.nFtpPort, sitRef.strUser, sitRef.strPw);
					break;
				}
			}
			catch ( CInternetException * e)
			{
				//ftp is not valid
				pFtpConnectionDes = NULL;
				CFWriteLog(0, TEXT("ftp not valid, %s, %s:%d,%s:%s"),sitRef.strFtpName,  sitRef.strFtpIp, sitRef.nFtpPort, sitRef.strUser, sitRef.strPw);
			}
		}

		if (!pFtpConnectionDes)
		{
			CFWriteLog(0, TEXT("no valid des ftp to use, clip trans failed, logicid = %s"), m_taskInfo.strClipLogicID);
			return EMBERR_INVALIDFTP;
		}

		//set file dir
		string szSrcDir = m_taskInfo.strSrcDir;
		string szDirSrcUtf8 = szSrcDir;

		string szDesDir = m_taskInfo.strDesDir;
		string szDesDirUtf8 = szDesDir;

		string szNameSrc = m_taskInfo.strSrcFileName;
		string szNameSrcUtf8 = szNameSrc;

		string szNameDes = m_taskInfo.strDesFileName;
		string szNameDesUtf8 = szNameDes;

			if (m_taskInfo.nCodePage == CP_UTF8)
		{
			wstring wszSrcDir = Ansi2W(szSrcDir);
			szDirSrcUtf8 = W2UTF8(wszSrcDir);

			wstring wszDesDir = Ansi2W(szDesDir);
			szDesDirUtf8 = W2UTF8(wszDesDir);

			wstring wszNameSrc = Ansi2W(szNameSrc);
			szNameSrcUtf8 = W2UTF8(wszNameSrc);

			wstring wszNameDes = Ansi2W(szNameDes);
			szNameDesUtf8 = W2UTF8(wszNameDes);
			
		}

		BOOL bSrcRet = TRUE;
		if (szDirSrcUtf8.size()> 0)
		{
			bSrcRet = pFtpConnectionSrc->SetCurrentDirectory(szDirSrcUtf8.c_str());
		}

		BOOL bDesRet = TRUE;
		if (szDesDirUtf8.size() > 0)
		{
			bDesRet = pFtpConnectionDes->SetCurrentDirectory(szDesDirUtf8.c_str());
		}

		ULONGLONG nSrcFileLength = 0;
		if (!bSrcRet || !bDesRet)
		{
			ASSERT(FALSE);
			CFWriteLog(0, TEXT("%s ftp path not found"), bSrcRet? szDesDir.c_str(): szSrcDir.c_str());
			hRet = EMBERR_DIRACCESS;
			throw 1;
		}

		CFtpFileFind finder(pFtpConnectionSrc);
		BOOL bFind = finder.FindFile(szNameSrcUtf8.c_str());  // 查找服务器上当前目录的任意文件 

		if (!bFind)   // 如果一个文件都找不到,结束查找 
		{ 
			CFWriteLog(0, TEXT("src file not found. %s"), szNameSrc.c_str());
			hRet = EMBERR_NOTFOUND;
			throw 1;
		} 
		else
		{
			finder.FindNextFile();
			nSrcFileLength = finder.GetLength();
			m_nCurrFileLength = nSrcFileLength;
			CFWriteLog(0, "src file length = %I64dByte, %I64dM", nSrcFileLength, nSrcFileLength/((ULONGLONG)(1024*1024)));
/* //don't delete, use these code when actor in winxp or server 2003
			if (!m_taskInfo.vSitSrc[m_nCurrSrcSite].strUncDir.IsEmpty())
			{
				//used when actor in winxp or win2003
				CString strUncFile = m_taskInfo.vSitSrc[m_nCurrSrcSite].strUncDir;
				strUncFile += "\\";
				
				strUncFile += m_taskInfo.strSrcFileName;
				OFSTRUCT ofStruct; 
				HFILE tHandle = NULL;
				
				tHandle =OpenFile(strUncFile, &ofStruct,OF_READ );
				CFWriteLog("unc file =%s, handle = %d", strUncFile, tHandle);
				if (tHandle)
				{
					LARGE_INTEGER tInt1;
					ZeroMemory(&tInt1, sizeof(tInt1));
					GetFileSizeEx((HANDLE)tHandle, &tInt1);
					__int64 tFileSize2 = tInt1.QuadPart;
					if (tFileSize2 > 0)
					{
						nSrcFileLength = tFileSize2;
						m_nCurrFileLength = nSrcFileLength;
						CFWriteLog(0, "src file changed length = %I64dByte, %I64dM", nSrcFileLength, nSrcFileLength/((ULONGLONG)(1024*1024)));
					}
					CloseHandle((HANDLE)tHandle);
				}	
			}*/
		}
		//后缀名
		finder.Close();

		CFtpFileFind finderDes(pFtpConnectionDes);
		BOOL bFindDes = finderDes.FindFile(szNameDesUtf8.c_str());
		finderDes.Close();
		if (bFindDes)
		{
			CFWriteLog(0, TEXT("des ftp file already existed,delete and continue. %s "), szNameDes.c_str());
			if(!pFtpConnectionDes->Remove(szNameDesUtf8.c_str()))
			{
				CFWriteLog(0, TEXT("des file del failed! err =%d"), GetLastError());
				hRet = EMBERR_FILEACCESS;
				throw 1;
			}
		}

		//start copy file
		CInternetFile* pFileSrc = NULL;
		CInternetFile* pFileDes = NULL;
		CFile* pFileLocal = NULL;
		CMD5CALEX* pMd5 = NULL;
		CString strMd5Result;
		//start trans
		try
		{
			pFileSrc =pFtpConnectionSrc->OpenFile(szNameSrcUtf8.c_str());
			if (!pFileSrc)
			{
				hRet = EMBERR_FILEACCESS;
				CFWriteLog(0, TEXT("src ftp文件打开失败, %s"),szNameSrc.c_str());
				throw 1;
			}
			pFileDes = pFtpConnectionDes->OpenFile(szNameDesUtf8.c_str(), GENERIC_WRITE);
			if (!pFileDes)
			{
				CFWriteLog(0, TEXT("des ftp文件打开失败, %s"), szNameDes.c_str());
				throw 1;
			}

			if (m_taskInfo.bDownToLocal)
			{
				CString strLocalFile = m_taskInfo.strLocalDownDir;
				strLocalFile.TrimRight(TEXT("\\"));
				CreateDirectory(strLocalFile, NULL);
				strLocalFile += TEXT("\\");
				strLocalFile += m_taskInfo.strLocalDownFileName;
				pFileLocal = new CFile;
				if (!pFileLocal->Open(strLocalFile, CFile::modeCreate|CFile::modeWrite, NULL))
				{
					CFWriteLog(0, TEXT("localdown file open failed. %s"), strLocalFile);
					hRet = EMBERR_FILEACCESS;
					throw 2;
				}
			}

			if (m_taskInfo.bMD5Check)
			{
				pMd5 = new CMD5CALEX;
				pMd5->Begin();
			}

			INT64 nFileTransed= 0;
			INT64 nPercent = 0;
			const INT64  nSleepPot = m_nMaxFtpSpeedPerExc;
			CFWriteLog(TEXT("trans speed limit to %.2f MB/s"), m_nMaxFtpSpeedPerExc/1024.0/1024.0);
			INT64 nCurrTransed  = 0;
			UINT nCurrTick = GetTickCount();
			INT64 nTransedPerSecond = 0;
			DWORD nTickStart = GetTickCount();
			INT64 nSpeedKBPerS = 0;
			while(nFileTransed < nSrcFileLength)
			{
				if (m_hEventQuit && WaitForSingleObject(m_hEventQuit, 0) == WAIT_OBJECT_0)
				{
					break;
				}
				byte szbuff[FREADBUFF];
				UINT nRead = pFileSrc->Read(szbuff, FREADBUFF);
				if (nRead > 0)
				{
					pFileDes->Write(szbuff, nRead);
					if (pFileLocal)
					{
						pFileLocal->Write(szbuff, nRead);
					}
					if (pMd5)
					{
						pMd5->CalBuff(szbuff, nRead);
					}
					nFileTransed += nRead;
					INT64 nNewPercent = nFileTransed*100/nSrcFileLength; 
					if (nNewPercent > nPercent)
					{
						nPercent = nNewPercent;
						m_nPercent = nPercent == 100? 99:nPercent;
					}

					//limit speed
					nCurrTransed += nRead;
					if (nSleepPot > 0 && nCurrTransed > nSleepPot)
					{
						INT64 nTickSleep =GetTickCount() - nCurrTick;
						nTickSleep = nTickSleep > 1000? 0:(1000-nTickSleep);
						nCurrTransed = 0;
						nCurrTick = GetTickCount();
						//limit speed
						if (nTickSleep > 10)
						{
							Sleep(nTickSleep);
						}
					}
					//calc speed
					nTransedPerSecond += nRead;
					DWORD nTickNow = GetTickCount();
					if (nTickNow > nTickStart)
					{
						if (nTickNow - nTickStart >= 1000)
						{
							//
							nSpeedKBPerS = nTransedPerSecond*1000/((nTickNow - nTickStart)*1024);
							nTransedPerSecond = 0;
							nTickStart = nTickNow;
							CFWriteLog("runtimeSpeed %.2f MB/s", nSpeedKBPerS/1024.0);
							// 										TRACE("\ntask%I64d, percent%d", m_taskInfo.nTaskId, nPercent);
							//CFWriteLog("write %I64d, total %I64d", nSrcFileLength, nFileTransed);
						}
					}
				}
				else
				{
					if (nFileTransed == nSrcFileLength)
					{
						//task finished.
						hRet = S_OK;
						m_nPercent = 99;
					}
					else
					{
						//
						//CFWriteLog(0, TEXT("读取源文件失败"));
						CFWriteLog(0, TEXT("src file write err %s, src = %I64d,  writed = %I64d"), szNameSrc.c_str(), nSrcFileLength, nFileTransed);
						hRet = EMBERR_FILEACCESS;
					}
					break;
				}
			}

			//file trans finished
			if (nFileTransed == nSrcFileLength)
			{
				hRet = S_OK;
				m_nPercent =99;
				TRACE("\nfile trans finished");
			}

			if (hRet==S_OK && pMd5)
			{
				strMd5Result = pMd5->GetResult();
				CFWriteLog(0, "md5value = %s",strMd5Result);
				if (!strMd5Result.IsEmpty())
				{
					if (!m_taskInfo.strMD5Compare.IsEmpty())
					{
						if (m_taskInfo.strMD5Compare.CompareNoCase(strMd5Result) != 0)
						{
							CFWriteLog(0, TEXT("md5 compare error src:%s, des:%s"), m_taskInfo.strMD5Compare, strMd5Result);
							hRet = EMBERR_MD5NOTMATCH;
						}
					}
					
				}
				else
				{
					CFWriteLog(0, TEXT("md5 calculate failed"));
				}
			}


		}
		catch (CInternetException* e)
		{
			ASSERT(FALSE);
			char szbuff[4096];
			e->GetErrorMessage(szbuff, 4094);
			CFWriteLog(0, TEXT("ftp file transfer exception error! %s"), szbuff);
			hRet = EMBERR_INTERNET;
		}
		catch(...)
		{
			ASSERT(FALSE);
			CFWriteLog(0, TEXT("file transfer exception error!"));
		}

		if (pFileSrc)
		{
			pFileSrc->Close();
			delete pFileSrc;
		}
		if (pFileDes)
		{
			pFileDes->Close();
			delete pFileDes;
		}
		if (pFileLocal)
		{
			pFileLocal->Close();
			delete pFileLocal;
		}

		if (pMd5)
		{
			delete pMd5;
		}

	}
	catch (CInternetException* e)
	{
		hRet = EMBERR_INTERNET;
		CFWriteLog(0, TEXT("network error code = %d"), e->m_dwError);
	}
	catch(...)
	{
		ASSERT(FALSE);
	}

	if (pFtpConnectionSrc!=NULL) 
	{ 
		pFtpConnectionSrc->Close();
		delete pFtpConnectionSrc;
	}

	if (pFtpConnectionDes!=NULL) 
	{ 
		pFtpConnectionDes->Close();
		delete pFtpConnectionDes;
	}

	return hRet;
}