예제 #1
0
bool CBlockMatrix::LoadConfig()
{
#ifdef _FILESYSTEM
  char* fileName = "BlockMatrix.txt";
  if (!IsFileExist(fileName, TXT_PATH))
    copyFile(fileName, TXT_PATH);
  string fullFilePath = getFilePath(fileName, TXT_PATH);
  int fileLen = strlen(fullFilePath.c_str());
  if (!fileLen)
    return false;
  char buffer[256];  
  ifstream in(fullFilePath);  
  if (! in.is_open())  
  { 
    cout << "Error opening file BlockMatrix"; 
    return false; 
  }
  int Line = 0;
  while (EOF != in.peek() )  
  { 
    in.getline (buffer,256);
    GParse GP(buffer);
    BlockMap Item;
    Item.Idx = GP.getInt();
    Item.Id = GP.getInt();
    BlockMaps.push_back(Item);
  }
  return true;
#endif;
  /*
  char* fileName = "BlockMatrix.lua";
  if (!IsFileExist(fileName, LUA_PATH))
    copyFile(fileName, LUA_PATH);
  string fullFilePath = getFilePath(fileName, LUA_PATH);
  int fileLen = strlen(fullFilePath.c_str());
  if (!fileLen)
    return false;
  if (luaL_dofile(GLuaState, fullFilePath.c_str()))
  {
    CCLOG("BlockMatrix.lua file error!");
    return false;
  }
  CLuaObject LuaObject = CLuaObject("BlockMatrix", GLuaState);
  BEGIN_LUA(LuaObject)
  {
    BlockMap Item;
    Item.Idx = LuaObject.getInt("Idx");
    Item.Id = LuaObject.getInt("Id");
    BlockMaps.push_back(Item);
  }
  END_LUA(LuaObject)

  CLuaObject LuaProObject = CLuaObject("PropertySet", GLuaState);
  BEGIN_LUA(LuaProObject)
  {
    PropertySet Property;
    Property.Idx = LuaProObject.getInt("Idx");
    Property.Id = LuaProObject.getInt("Id");
    PropertySets.push_back(Property);
  }
  END_LUA(LuaProObject)*/
  return true;
}
예제 #2
0
BOOL CopyIMEFile(HINSTANCE hInstance, TCHAR* sImeFile)
{
	TCHAR	sModuleFile[MAX_PATH];
	TCHAR	sSrcDir[MAX_PATH], sDestDir[MAX_PATH];
	TCHAR	sSrc[MAX_PATH], sDest[MAX_PATH];


	//取得本文件执行路径。若用GetCurrentDirectory(400, sSrcDir)则可能是在别的目录执行。
	GetModuleFileName(hInstance, sModuleFile, sizeof(sModuleFile) - 1);
	GetFilePath(sModuleFile, sSrcDir);

	//取得windows系统目录
	GetSystemDirectory(sDestDir, sizeof(sDestDir) - 1);

	//复制文件
	lstrcpy(sSrc, sSrcDir);
	lstrcat(sSrc, "\\binary\\");
	lstrcat(sSrc, "freepy.hlp");
	lstrcpy(sDest, sDestDir);
	lstrcat(sDest, "\\");
	lstrcat(sDest, "freepy.hlp");
	if (CopyFile(sSrc, sDest, FALSE) == 0) {
		MessageBox(NULL,
			_T("输入法安装失败!\nfreepy.hlp复制失败。"),
			INST_TITLE,
			MB_OK | MB_ICONSTOP);
		return(FALSE);
	}

	//复制文件
	lstrcpy(sSrc, sSrcDir);
	lstrcat(sSrc, "\\binary\\");
	lstrcat(sSrc, "freepy.tab");
	lstrcpy(sDest, sDestDir);
	lstrcat(sDest, "\\");
	lstrcat(sDest, "freepy.tab");
	if(IsFileExist(sDest)) {
		if (MessageBox(NULL, _T("freepy.tab 已经存在, 您要覆盖它吗?\n"), INST_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON1) == IDYES) {
			if (CopyFile(sSrc, sDest, FALSE) == 0) {
				MessageBox(NULL,
					_T("输入法安装失败!\nfreepy.tab复制失败。"),
					INST_TITLE,
					MB_OK | MB_ICONSTOP);
				return(FALSE);
			}
		}
	}
	
	//复制文件
	lstrcpy(sSrc, sSrcDir);
	lstrcat(sSrc, "\\binary\\");
	lstrcat(sSrc, "freepysys.dic");
	lstrcpy(sDest, sDestDir);
	lstrcat(sDest, "\\");
	lstrcat(sDest, "freepysys.dic");
	if(IsFileExist(sDest)) {
		if (MessageBox(NULL, _T("freepysys.dic 已经存在, 您要覆盖它吗?\n"), INST_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON1) == IDYES) {
			if (CopyFile(sSrc, sDest, FALSE) == 0) {
				MessageBox(NULL,
					_T("输入法安装失败!\nfreepysys.dic复制失败。"),
					INST_TITLE,
					MB_OK | MB_ICONSTOP);
				return(FALSE);
			}
		}
	}
		
	//复制文件
	lstrcpy(sSrc, sSrcDir);
	lstrcat(sSrc, "\\binary\\");
	lstrcat(sSrc, "freepy.ime");
	lstrcpy(sDest, sDestDir);
	lstrcat(sDest, "\\");
	lstrcat(sDest, "freepy.ime");
	if(IsFileExist(sDest)) {
		if (MessageBox(NULL, _T("freepy.ime 已经存在, 您要覆盖它吗?\n"), INST_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON1) == IDYES) {
			if (CopyFile(sSrc, sDest, FALSE) == 0) {
				MessageBox(NULL,
					_T("输入法安装失败!\nfreepy.ime复制失败。"),
					INST_TITLE,
					MB_OK | MB_ICONSTOP);
				return(FALSE);
			}
		}
	}

	lstrcpy(sImeFile, sDest);
	return TRUE;
}
예제 #3
0
파일: main.cpp 프로젝트: hongwenjun/srgb
int main(int argc , char* argv[])
{
    if (88 == initial_arg(argc , argv))
        return 88;

    char AppPath[MAX_PATH] = {0};
    GetAppDir(AppPath);

    string date_txt = string(AppPath) + "\\date.txt";
    string listfile_txt = string(AppPath) + "\\listfile.txt";

    if (_chdir(Path_Argv.c_str())) {
        printf("无法找到的目录: %s\n\a\n\n", Path_Argv.c_str());
        print_help();
        if (argc == 1) getchar();
        return -1;
    } else if (!Direct_Datelog_Flag) {
        printf("正在扫描目录: %s\n", Path_Argv.c_str());
        // 获得文件名和路径数据输入文件 ,和差不多DIR . /S /AA /TW >\date.txt
        int file_sum = find_path_save_file(Path_Argv.c_str(), date_txt.c_str());
        printf("扫描文件总数量: %d 个文件\t" , file_sum);
    }

    ifstream datefile(date_txt.c_str());
    ofstream listfile(listfile_txt.c_str());

    string readline;    // 读取每行,然后使用正则搜索匹配
    smatch m;
    regex e(Reg_Argv);

    F_STRUCT d_file ;  // 简单的文件属性结构
    map<string, string> mss_date;
    size_t file_size_sum = 0 ;

    while (getline(datefile , readline)) {
        char buf[MAX_PATH * 2];
        char* pch = NULL;
        if (regex_search(readline, m, e)) {      // 符合条件的的文件列表存如容器
            //  sscanf(readline.c_str() + 32 , "%s | %s" ,  d_file.name, d_file.path);  // 不能处理路径和文件名中有空格
            sscanf(readline.c_str() + 20 , "%d" , &d_file.size);  file_size_sum += d_file.size;
            sprintf(buf, "%s", readline.c_str() + 32);

            pch = strchr(buf, '|'); // 查找分割标记
            if (pch != NULL) {
                *pch = '\0';
                strcpy(d_file.name , buf);
                strcpy(d_file.path , pch + 1);

                csTrim(d_file.name);  csTrim(d_file.path); // 删除前后空格
                mss_date.insert(make_pair(string(d_file.path) + "\\" + d_file.name  , string(d_file.name)));
            }
        }
    }
    printf("符合条件文件数量: %d 个文件  大小: %d字节\n" , mss_date.size() , file_size_sum);
    for (auto it = mss_date.begin() ; it != mss_date.end(); ++it)
        listfile << it->first.substr(it->first.find(":\\") + 2) << "\n"; // 输出结果

    datefile.close();  listfile.close();

    // 调用7z命令行打包文件,
    string pkcmd = string("7z.exe a -scsWIN  ") + Packfile_Argv + " @" + listfile_txt;

    if (IsFileExist((string(AppPath) + "\\res\\7z.exe").c_str()))
        pkcmd = string(AppPath) + "\\res\\" + pkcmd;
    if (Test_List_Flag) pkcmd = string("TYPE ") + listfile_txt;   // 只是显示 listfiel.txt, 不打包文件

    _chdir("\\"); system("COLOR F9");
    if (system(pkcmd.c_str()) != 0) {
        fprintf(stdout, "%s\t%s %s\n" , "调用打包命令:" , pkcmd.c_str(), "失败!请检查软件目录下是否有 7z.exe");
    }
    print_help();
    if (Delete_Datelog_Flag) {
        remove(date_txt.c_str());   remove(listfile_txt.c_str());
    }
    if (argc == 1) getchar();

    return 0;
}
예제 #4
0
BOOL CCheckRuleXMLParse::Save(const CString &strFilePath, const CheckRuleArray &arrCheckRuleList)
{
	// 删除老版本生成的未加密xml
	CString strOldXmlPath = strFilePath;
	strOldXmlPath.Replace(L".bpxml", L"xml");
	if (IsFileExist(strOldXmlPath))
		SafeDeleteFile(strOldXmlPath);

	// 删除新版本生成的加密bpxml
	if (IsFileExist(strFilePath))
		SafeDeleteFile(strFilePath);

	BOOL bResult = TRUE;

	// 初始化
	Init();

	// 创建xml文件
	if (!m_pXMLDocument->CreateDocument(L"CheckRule"))
		bResult = FALSE;

	// 存储数据
	if (bResult)
	{
		IBpXMLNode* pRootNode = m_pXMLDocument->GetRootElement();
		pRootNode->SetAttribute(L"version", L"1.1");
		DestroyXMLNode(pRootNode);
		CString strValue;	
		for (int i=0; i<arrCheckRuleList.GetSize(); i++)
		{
			IBpXMLNode* pRuleNode = m_pXMLDocument->CreateElementNode(L"node");
			IBpXMLNode* pChildNode = NULL;
			if (pRuleNode != NULL)
			{
				strValue.Format(L"%d", arrCheckRuleList[i].nID);
				pRuleNode->SetAttribute(L"id", strValue);
				strValue.Format(L"%d", arrCheckRuleList[i].nRuleType);
				pRuleNode->SetAttribute(L"ruletype", strValue);
				pChildNode = pRuleNode->AppendNewElementChild(L"ruledesc");
				pChildNode->SetText(arrCheckRuleList[i].strRuleDesc);
				DestroyXMLNode(pChildNode);
				pChildNode = pRuleNode->AppendNewElementChild(L"rulename");
				pChildNode->SetText(arrCheckRuleList[i].strRuleName);
				DestroyXMLNode(pChildNode);
				pChildNode = pRuleNode->AppendNewElementChild(L"rulecontent");

				for (int j=0; j<arrCheckRuleList[i].arrRuleContent.GetCount(); j++)
				{
					strValue.Format(L"rc%d", j);
					pChildNode->SetAttribute(strValue, arrCheckRuleList[i].arrRuleContent.GetAt(j));
				}
				DestroyXMLNode(pChildNode);
				pChildNode = pRuleNode->AppendNewElementChild(L"MdlFilter");
				strValue.Format(L"%d", arrCheckRuleList[i].dwMdlFilter);
				pChildNode->SetText(strValue);
				DestroyXMLNode(pChildNode);

				DestroyXMLNode(pRuleNode);
			}
		}
	}

	// 保存为临时xml文件
	CString strTempXMLFile;
	GetTempFile(strTempXMLFile, L"xml");
	m_pXMLDocument->SaveXML(strTempXMLFile);

	// xml文件加密
	bResult = EncodeFileEx(strTempXMLFile, strFilePath);
	SafeDeleteFile(strTempXMLFile);

	// 释放资源
	Uninit();
	return bResult;
}
예제 #5
0
void CMDecodePage::SaveConfig()
{
	if(!m_cfg)
		return;
	UpdateData(TRUE);
	if(!IsFileExist(m_program_dir + _T("codecs.ini")))
		m_last_extract =  inner;
	int vcodecs = m_codecs.GetCurSel();
	switch (vcodecs)
	{
	case external:
		m_cfg->SetValue(_T("cofing_codecs"), _T("1"), true , ex_meditor);
		if(m_last_extract !=  external)
			ExtractResource(MAKEINTRESOURCE(IDZ_CODECS_INI),TEXT("CODECS_INI"),
				m_program_dir+_T("codecs.ini"), true, true, _T("codecs.conf"));
		m_last_extract =  external;
		break;
	case coreavc:
		RegCoreCodec();
		m_cfg->SetValue(_T("cofing_codecs") , _T("2") , true , ex_meditor);
		if(m_last_extract !=  coreavc)
			ExtractResource(MAKEINTRESOURCE(IDZ_CODECS_INI),TEXT("CODECS_INI"),
				m_program_dir+_T("codecs.ini"), true, true, _T("codecs.coreavc.conf"));
		m_last_extract =  coreavc;
		break;
	case lavcuvid:
		RegCoreCodec();
		m_cfg->SetValue(_T("cofing_codecs") , _T("3") , true , ex_meditor);
		if(m_last_extract !=  lavcuvid)
			ExtractResource(MAKEINTRESOURCE(IDZ_CODECS_INI),TEXT("CODECS_INI"),
			m_program_dir+_T("codecs.ini"), true, true, _T("codecs.lavcuvid.conf"));
		m_last_extract =  lavcuvid;
		break;
	default:
		m_cfg->RemoveValue(_T("cofing_codecs"), true);
		DeleteFile(m_program_dir + _T("codecs.ini"));
		m_last_extract = inner;
		break;
	}

	if(m_dshow)
		m_cfg->SetValue(_T("dshow-demux"), _T("1"));
	else
		m_cfg->RemoveValue(_T("dshow-demux"));

	if(m_auto_threads) {
		m_cfg->RemoveValue(_T("auto-threads"));
		m_cfg->RemoveValue(_T("noauto-threads"));
	} else
		m_cfg->SetValue(_T("auto-threads"), _T("0"));

	m_vlist.LockWindowUpdate();
	m_alist.LockWindowUpdate();
	m_avlist.LockWindowUpdate();
	
	CString vc_str = _T("");
	CString vc_str_meditor = _T("");
	for(int i = 0; i < m_vlist.GetItemCount() ; i ++)
	{
		if(m_vlist.GetCheckbox(i, 0))
			vc_str +=  m_vlist.GetItemText(i, 1) + _T(",");
		else
			vc_str_meditor +=  m_vlist.GetItemText(i, 1) + _T(",");
	}
	if(vc_str.GetLength() > 2)
		m_cfg->SetValue(_T("vc"),  vc_str);
	else
	{
		m_cfg->SetValue(_T("vc"),  _T(""));
		m_cfg->RemoveValue(_T("vc"));
	}
	if(vc_str_meditor.GetLength() > 2)
		m_cfg->SetValue(_T("cofing_vc"),  vc_str_meditor,true , ex_meditor);
	else
		m_cfg->RemoveValue(_T("cofing_vc"),true);


	CString ac_str = _T("");
	CString ac_str_meditor = _T("");
	for(int j = 0; j < m_alist.GetItemCount() ; j ++)
	{
		if(m_alist.GetCheckbox(j, 0))
			ac_str +=  m_alist.GetItemText(j, 1) + _T(",");
		else
			ac_str_meditor +=  m_alist.GetItemText(j, 1) + _T(",");
	}	
	if(ac_str.GetLength() > 2)
		m_cfg->SetValue(_T("ac"),  ac_str);
	else
		m_cfg->RemoveValue(_T("ac"));
	if(ac_str_meditor.GetLength() > 2)
		m_cfg->SetValue(_T("cofing_ac"),  ac_str_meditor,true , ex_meditor);
	else
		m_cfg->RemoveValue(_T("cofing_ac"),true);

	if(m_avlist.GetCheckbox(xy, 0))
	{
		CString str = m_avlist.GetItemText(xy, 2);
		str.TrimLeft(_T(" "));
		str.TrimRight(_T(" "));
		int tr = _ttoi(str);
		if(tr > 0 && str.GetLength() >= 1)
			m_cfg->SetValue(_T("xy"),  str);
		else
			m_cfg->RemoveValue(_T("xy"));
	}
	else
		m_cfg->RemoveValue(_T("xy"));
	
	CString av_str = _T("");
	if(m_avlist.GetCheckbox(skiploopfilter, 0))
	{
		CString str = m_avlist.GetItemText(skiploopfilter, 2);
		str.TrimLeft(_T(" "));
		str.TrimRight(_T(" "));
		if(str == m_str_skip1)
			av_str += _T("skiploopfilter=default:") ;
		else if(str == m_str_skip2)
			av_str += _T("skiploopfilter=nonref:");
		else if(str == m_str_skip3)
			av_str += _T("skiploopfilter=bidir:");
		else if(str == m_str_skip4)
			av_str += _T("skiploopfilter=nonkey:");
		else
			av_str += _T("skiploopfilter=all:");
	}
	if(m_avlist.GetCheckbox(skipframe, 0))
	{
		CString str = m_avlist.GetItemText(skipframe, 2);
		str.TrimLeft(_T(" "));
		str.TrimRight(_T(" "));
		if(str == m_str_skip1)
			av_str += _T("skipframe=default:") ;
		else if(str == m_str_skip2)
			av_str += _T("skipframe=nonref:");
		else if(str == m_str_skip3)
			av_str += _T("skipframe=bidir:");
		else if(str == m_str_skip4)
			av_str += _T("skipframe=nonkey:");
		else
			av_str += _T("skipframe=all:");		
	}
	if(m_avlist.GetCheckbox(lowres, 0))
	{
		CString str = m_avlist.GetItemText(lowres, 2);
		str.TrimLeft(_T(" "));
		str.TrimRight(_T(" "));
		if(str.GetLength() > 0)
			av_str += _T("lowres=") + str + _T(":");
	}
	if(m_avlist.GetCheckbox(threads, 0))
	{
		CString str = m_avlist.GetItemText(threads, 2);
		str.TrimLeft(_T(" "));
		str.TrimRight(_T(" "));
		int tr = _ttoi(str);
		if(tr > 0 && tr < 9 && str.GetLength() == 1)
			av_str += _T("threads=") + str + _T(":");
	}
//	if(m_avlist.GetCheckbox(fast, 0))
//		av_str += _T("fast:");
//	if(m_avlist.GetCheckbox(gray, 0))
//		av_str += _T("gray:");
//	if(m_avlist.GetCheckbox(sb, 0))
//		av_str += _T("sb:");
//	if(m_avlist.GetCheckbox(st, 0))
//		av_str += _T("st:");
	av_str.TrimRight(_T(":"));
	if(av_str.GetLength() > 1)
		m_cfg->SetValue(_T("lavdopts"),  av_str);
	else
		m_cfg->RemoveValue(_T("lavdopts"));

	m_vlist.UnlockWindowUpdate();
	m_alist.UnlockWindowUpdate();
	m_avlist.UnlockWindowUpdate();

}
예제 #6
0
 bool IsFileExist(const string& strFileName)
 {
     return IsFileExist(strFileName.c_str());
 }
예제 #7
0
void CDHtmlMainDialog::InitThemeLang()
{
	TCHAR str[256];
	TCHAR *ptrEnd;

	WIN32_FIND_DATA findData;
	HANDLE hFind;
	CString langPath;
	int i = 0;
	WORD PrimaryLangID;
	CString PrimaryLang;

// Set Theme
	if(m_CurrentTheme.IsEmpty())
	{
#ifdef SUISHO_SHIZUKU_SUPPORT
	#ifdef KUREI_KEI_SUPPORT
		GetPrivateProfileString(_T("Setting"), _T("ThemeKureiKei"), _T("default"), str, 256, m_Ini);
	#else
		GetPrivateProfileString(_T("Setting"), _T("ThemeShizuku"), _T("default"), str, 256, m_Ini);
	#endif
#else
		GetPrivateProfileString(_T("Setting"), _T("Theme"), _T("default"), str, 256, m_Ini);
#endif
		m_CurrentTheme = str;
	}

// Set Language
	GetPrivateProfileString(_T("Setting"), _T("Language"), _T(""), str, 256, m_Ini);

	langPath.Format(_T("%s\\%s.lang"), m_LangDir, str);
	m_DefaultLangPath.Format(_T("%s\\%s.lang"), m_LangDir, _T("English"));

	if(_tcscmp(str, _T("")) != 0 && IsFileExist((const TCHAR*)langPath))
	{
		m_CurrentLang = str;
		m_CurrentLangPath.Format(_T("%s\\%s.lang"), m_LangDir, str);
	}
	else
	{
		m_CurrentLocalID.Format(_T("0x%04X"), GetUserDefaultLCID());
		PrimaryLangID = PRIMARYLANGID(GetUserDefaultLCID());

		langPath.Format(_T("%s\\*.lang"), m_LangDir);

		hFind = ::FindFirstFile(langPath, &findData);
		if(hFind != INVALID_HANDLE_VALUE)
		{
			do{
				if(findData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
				{
					i++;
					CString cstr;
					cstr.Format(_T("%s\\%s"), m_LangDir, findData.cFileName);
					GetPrivateProfileString(_T("Language"), _T("LOCALE_ID"), _T(""), str, 256, cstr);
					if((ptrEnd = _tcsrchr(findData.cFileName, '.')) != NULL){*ptrEnd = '\0';}

					if(_tcsstr(str, m_CurrentLocalID) != NULL)
					{
						m_CurrentLang = findData.cFileName;
						m_CurrentLangPath.Format(_T("%s\\%s.lang"), m_LangDir, findData.cFileName);
					}
					if(PrimaryLangID == PRIMARYLANGID(_tcstol(str, NULL, 16)))
					{
						PrimaryLang = findData.cFileName;
					}
				}
			}while(::FindNextFile(hFind, &findData) && i <= 0xFF);
		}
		FindClose(hFind);

		if(m_CurrentLang.IsEmpty())
		{
			if(PrimaryLang.IsEmpty())
			{
				m_CurrentLang = _T("English");
				m_CurrentLangPath.Format(_T("%s\\%s.lang"), m_LangDir, m_CurrentLang);
			}
			else
			{
				m_CurrentLang = PrimaryLang;
				m_CurrentLangPath.Format(_T("%s\\%s.lang"), m_LangDir, PrimaryLang);
			}	
		}
	}
}
예제 #8
0
int CClientSession::DoPutFile( const char* strSrc, const char* strDst, bool bOverwrite )
{
    char buf[MAXPATH+sizeof(CNcpMessage)];
    CNcpMessage* pMsg = (CNcpMessage*)buf;

    if( !IsFileExist( strSrc ) ) {
        return E_NOENT;
    }

    //step 1. request passive mode to get the data channel address
    short dataport = 0;

    int nRet = DoPassive( &dataport );
    if( FAILED(nRet) )return nRet;

    //step 2. send the put file command.
    pMsg->Init( CM_PUTFILE );
    pMsg->m_nParamRet = bOverwrite;
    strcpy( pMsg->GetData(), strDst );
    pMsg->SetDataSize( strlen(strDst)+1 );

    pMsg->Send( m_sock );

    //wait for the return code and check it
    if( !pMsg->Recv( m_sock, ELEMENTS(buf) ) ) {
        return E_BROKEN;		//broken connection
    }

    ASSERT( pMsg->IsAck() );
    if( pMsg->IsFailed() || pMsg->m_nParamRet==S_EXIST ) {
        return pMsg->GetRet();
    }

    //step 3. now the server agrees on the file transfer, connect the data channel and send file
    SOCKADDR_IN addr;
    socklen_t nlen = sizeof(SOCKADDR_IN);
    GetPeerName( m_sock, (SOCKADDR*)&addr, &nlen );
    addr.sin_port = htons( dataport );

    SOCKET sockdata;
    //import, must retry the socket initilization a few times.
    int i;
    for( i=0; i<MAXRETRY; i++ ) {
        sockdata = Socket( PF_INET, SOCK_STREAM, 0 );
        ASSERT( sockdata!=INVALID_SOCKET );

        if( ::connect( sockdata, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN) )==0 )break;
        closesocket( sockdata );
    }
    if( i>=MAXRETRY )throw new CSockException();

    int nLen = SendFileEx( sockdata, strSrc, m_nFileMode );
    closesocket( sockdata );

    //step 4. exchange the error code.
    pMsg->Init( CM_ACK, nLen );
    pMsg->Send( m_sock );

    //wait for the return code and check it
    if( !pMsg->Recv( m_sock, ELEMENTS(buf) ) ) {
        return E_BROKEN;		//broken connection
    }

    ASSERT( pMsg->IsAck() );
    return pMsg->GetRet();
}
예제 #9
0
FileState ReceiveFile(SOCKET socket, HWND hWrapperWnd, LPCTSTR strFilePathName, ULONGLONG llStartAt)
{

	PostMessage(hWrapperWnd, WM_FILE_OPERATE_BEGIN, 0, 0);

	FileState MyFileState = S_FileOK, YouFileState = S_FileOK;

	//open file
	CString strFileName = strFilePathName;
	CFile LocalFile;
	UINT uOpMode = llStartAt > 0 ? (CFile::modeReadWrite | CFile::typeBinary) : (CFile::modeCreate | CFile::modeReadWrite | CFile::typeBinary);

	if (IsFileExist(strFileName))
	{
		if (!DropReadOnly(strFileName))
			MyFileState = S_CreateFileFailed;
	}

	if(!LocalFile.Open(strFileName, uOpMode))
	{
		if(MyFileState == S_FileOK)
			MyFileState = S_CreateFileFailed;
	}

	if (MyFileState != S_CreateFileFailed)
	{
		ULONGLONG uSeeked = LocalFile.Seek(llStartAt, CFile::begin);
		if (uSeeked != llStartAt)
		{
			MyFileState = S_CreateFileFailed;
		}
	}

	//receive you file operate state
	if(!ReceiveData(socket, (char*)&YouFileState, sizeof(FileState)))
	{
		LocalFile.Close();
		return S_SocketError;
	}

	//send my file operate state
	if(!SendData(socket, (char*)&MyFileState, sizeof(FileState)))
	{
		if(MyFileState != S_CreateFileFailed)
			LocalFile.Close();
		return S_SocketError;
	}

	if(MyFileState != S_FileOK) return MyFileState;
	if(YouFileState != S_FileOK) return YouFileState;

	BasicFileInfo basicFileInfo;
	if(!ReceiveData(socket, (char*)(&basicFileInfo), sizeof(basicFileInfo)))
	{
		LocalFile.Close();
		//DeleteFile(strFilePathName);
		return S_SocketError;
	}
	
	ULONGLONG nTotalRead = llStartAt;
	ULONGLONG nDes = basicFileInfo.Size > 1024 * 1024 * 1024 ? 1024 * 1024 : 1024;
	PostMessage(hWrapperWnd, WM_FILE_SETRANGE_MESSAGE, (WPARAM)( basicFileInfo.Size / nDes), (LPARAM)0);

	PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nTotalRead / nDes), 0);
	ULONGLONG nRead = llStartAt;
	ULONGLONG nResCount = 0;
	ULONGLONG nRealRead = 0;

	FileDataEx fileData;

	if (gl_pLogger) gl_pLogger->log_info("ReceiveFile Begin to send: %s", strFilePathName);
	
	bool *pbstatus = NULL;
	SendMessage(hWrapperWnd, WM_GETSENDSTATE, 0, (LPARAM)&pbstatus);
	//receive loop
	while(1)
	{		
		if (!ReceiveData(socket, (char*)(&fileData), sizeof(fileData)))
			return S_SocketError;

		if (fileData.data.nLength == 0)
			break;

		if (fileData.state == S_IStop)
		{
			LocalFile.Close();
			//DeleteFile(strFilePathName);
			return S_OtherSideStop;
		}

		FileState MyState = S_FileOK;
		try{
			if (fileData.data.nLength > 0)
				LocalFile.Write(fileData.data.Buf, fileData.data.nLength);
		}
		catch(...){
			MyState = S_WriteFileFailed;
		}
		nRealRead = nRealRead + fileData.data.nLength;

		nTotalRead = nTotalRead + fileData.data.nLength;
		PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nTotalRead / nDes), 0);

		if(fileData.state == S_Finished)
		{
			if (nRealRead > 0)
				LocalFile.Flush();
			LocalFile.Close();
			return fileData.state;
		}
		
		if(fileData.state == S_ReadFileFailed)
		{
			LocalFile.Close();
			//DeleteFile(strFilePathName);
			return fileData.state;
		}


		nResCount++;
		if(nResCount % READWRITESTATUS == 0)
		{
			nResCount = 0;
			
			FileState MyState,YouState;

			MyState = (*pbstatus) ? S_FileContinue : S_IStop;
			//SendMessage(hWrapperWnd, WM_GETSENDSTATE, 0, (LPARAM)&MyState);
			
			if(!ReceiveData(socket, (char*)&YouState, sizeof(FileState)))
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_SocketError;
			}

			if(!SendData(socket, (char*)&MyState, sizeof(FileState)))
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_SocketError;
			}
			
			if(MyState == S_IStop)
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_IStop;
			}

			if(YouState == S_WriteFileFailed || YouState == S_IStop)
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				if(YouState == S_IStop) 
					YouState = S_OtherSideStop;
				return YouState;
			}
		}
	}

	return S_Finished;
}
예제 #10
0
void CMainFrame::OnAppUpgrade() 
{
	// TODO: Add your command handler code here
	
	CString myStr;
	BOOL myhasUpgrade = FALSE;
	CMyCommApp *myApp = (CMyCommApp *)AfxGetApp();
	CMainFrame * myMain = (CMainFrame *) myApp->GetMainWnd();
	CStdioFile myfile;
	CString vertext = myApp->m_AppDir + "\\version";

	if(!myMain->m_IsNewVertxt || !IsFileExist(vertext))
	{
		char s[256];
		_tcscpy(s,vertext.GetBuffer(vertext.GetLength())) ;
		if(!DonwLoadFile("https://github.com/liquanhai/LSDComm/version/ver.txt",s))
		{
			AfxMessageBox(_T("无法连接服务器。"));
			return;
		}
		myMain->m_IsNewVertxt = TRUE;
	}
	
		
	if(!myfile.Open(vertext,CFile::modeRead))
	{
		AfxMessageBox(_T("打开升级文件出错。"));
		return;
	}
	else{

		CString myverion;
		myfile.ReadString(myverion); //line:1
		myverion.TrimLeft();  myverion.TrimRight();
		if (atof(myApp->m_AppVersion)<atof(myverion))
		{
			//new version
			myhasUpgrade = TRUE;
			CMyCommView * myview = (CMyCommView *) myMain->GetActiveView();
			myStr = "最新版本:"+myverion+"\r\n";
			CString strLine;
			myfile.ReadString(strLine); // downfilename line:2
			myApp->m_downfileexefilename = strLine;
			while(myfile.ReadString(strLine))
			{
				if(strLine.GetLength()>2)
					if ((strLine[0] == '>') && (strLine[1]=='>'))
						myStr += strLine+"\r\n";
			} 
		}
		else{
			myStr = myApp->m_AppVersion + "版本已是最新了";
		}
		
	}
	myfile.Close();

	CUpgradeDlg dlg;
	dlg.m_strData = myStr;
	dlg.m_strdownfile  = myApp->m_downfileexefilename;
	dlg.m_StrLocalfile = myApp->m_AppDir + "\\exe";
	dlg.m_IsUpgrade = myhasUpgrade;
	if((dlg.DoModal()==IDOK) && myhasUpgrade)
	{
		if(!IsFileExist(myApp->m_AppDir + "\\exe"))	return;
		CStdioFile batfile;
		CString mybatFile;
		CString myAppDir;
		mybatFile = myApp->m_AppDir+"\\update.bat";
		if(!batfile.Open(mybatFile,CStdioFile::modeReadWrite|CStdioFile::modeCreate)) 
			return;

		myAppDir = DoGetShortFileName(myApp->m_AppDir);
		batfile.WriteString("@echo off\n\r");
		CString myexename;
		myexename = myAppDir + "\\LSDComm.exe";
					
		batfile.WriteString("del "+ myexename + "\n\r");
		batfile.WriteString("if exist "+ myexename +" goto loop" + "\n\r");
		batfile.WriteString("copy "+ myAppDir + "\\exe" + " " + myexename + "\n\r");
		batfile.WriteString("del "+ myAppDir + "\\exe" + "\n\r");
		batfile.WriteString(myexename+"\n\r");
		batfile.WriteString("del "+mybatFile+"\n\r");
		batfile.Close();

		ShellExecute(NULL,NULL,mybatFile,NULL,NULL,SW_HIDE);
		CFrameWnd::OnClose();
	};

}
예제 #11
0
short CHttpFileDownload::Download()
{
	//Issue the request to read the file
	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*");  
	ppszAcceptTypes[1] = NULL;
	DWORD dwFlags =INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION;
	
	//Now do the actual read of the file
//	DWORD dwStartTicks = ::GetTickCount();
//	DWORD dwCurrentTicks = dwStartTicks;
	DWORD dwBytesRead = 0;
	DWORD dwTotalBytesRead = 0;
	DWORD dwCurBytesRead = 0;
	DWORD dwLastTotalBytes = 0;
	BOOL bReboot = FALSE;
	CString strTmpDownFilePath;
	
		//Create the Internet session handle
		m_hInternetSession = ::InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);    
		if (m_hInternetSession == NULL){
			SetError(UPDATE_HTTP_FAIL_INTERNET_SESSION);
			return -601;
		}

		//Make the connection to the HTTP server          
		if(m_strLoginId != "" && m_strLoginPassword != ""){
			m_hHttpConnection = ::InternetConnect(m_hInternetSession, m_strServer, INTERNET_INVALID_PORT_NUMBER, m_strLoginId, 
												  m_strLoginPassword, INTERNET_SERVICE_HTTP, 0, (DWORD) this);
		}
		else{
			m_hHttpConnection = ::InternetConnect(m_hInternetSession, m_strServer, INTERNET_INVALID_PORT_NUMBER, NULL, 
												  NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
		}

		if (m_hHttpConnection == NULL){
			SetError(UPDATE_HTTP_FAIL_INTERNET_CONNECTION);
			return -602;
		}

		//Set any CInternetSession options we  may need
		int ntimeOut = 30;
		::InternetSetOption(m_hInternetSession, INTERNET_OPTION_CONNECT_TIMEOUT, (void*)(1000*ntimeOut), 0);
		::InternetSetOption(m_hInternetSession, INTERNET_OPTION_CONNECT_BACKOFF, (void*)(1000), 0);
		::InternetSetOption(m_hInternetSession, INTERNET_OPTION_CONNECT_RETRIES, (void*)(1), 0);
		
		//////////////////////////////////////////////////////////////////////////
		// 2004.11.4 by cabbage
		// 다운로드 중에 InternetReadFile()에서 응답이 없어서 멈춤 해결을 위해 
		// BUFFER_SIZE와 함께 수정
//		::InternetSetOption(m_hInternetSession, INTERNET_OPTION_SEND_TIMEOUT, (void*)(1000*5),0);
//		::InternetSetOption(m_hInternetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, (void*)(1000*5),0);
		//////////////////////////////////////////////////////////////////////////

		m_hHttpFile = ::HttpOpenRequest(m_hHttpConnection, NULL, m_strObject, _T("HTTP/1.1"), NULL, ppszAcceptTypes, dwFlags, (DWORD)this);
		if (m_hHttpFile == NULL){
			SetError(UPDATE_HTTP_FAIL_INTERNET_OPEN_REQUEST);
			return -603;
		}

		//Issue the request
		BOOL bSend = FALSE;
		bSend = ::HttpSendRequest(m_hHttpFile, NULL, 0, NULL, 0);
		if (!bSend){
			TRACE(_T("Failed in call to HttpSendRequest, Error:%d\n"), ::GetLastError());
			SetError(UPDATE_HTTP_FAIL_INTERNET_SEND_REQUEST);
			return -604;
		}

		//Check the HTTP status code
		TCHAR szStatusCode[32];
		DWORD dwInfoSize = 32;
		if (!::HttpQueryInfo(m_hHttpFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL)){
			TRACE(_T("Failed in call to HttpQueryInfo for HTTP query status code, Error:%d\n"), ::GetLastError());
			SetError(UPDATE_HTTP_FAIL_INTERNET_QUERY_STATUS_CODE);
			return -605;
		}
		else{
			//Get the HTTP status code
			long nStatusCode = _ttol(szStatusCode);
  			if (nStatusCode == HTTP_STATUS_OK){
				// Get the length of the file.            
				DWORD dwFileSize = 0;
				TCHAR szContentLength[32];
				DWORD dwtmpInfoSize = 32;
				if (::HttpQueryInfo(m_hHttpFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwtmpInfoSize, NULL)){
					//Set the progress control range
					dwFileSize = (DWORD) _ttol(szContentLength);
				}
				else{
					SetError(UPDATE_HTTP_FAIL_INTERNET_QUERY_CONTENT_LENGTH);
					return -605;
				}
			
				m_strDownFilePath = m_strDownPath + m_strFileName;		// Get Download file name;				

				DWORD dwCurBytesRead=0;
				HANDLE hFile = CreateFile(_T((LPCSTR)m_strDownFilePath),
											GENERIC_WRITE, FILE_SHARE_READ,
											NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

				if (hFile == INVALID_HANDLE_VALUE){
					bool bCreateError=false;
					switch(GetLastError())
					{
					case ERROR_ACCESS_DENIED:
					case ERROR_SHARING_VIOLATION:
					case ERROR_LOCK_VIOLATION:	bCreateError = true;	break;
					default:											break;
					}
				
					if(bCreateError){
						bool bSuccess = false;
						if(m_pNotiInfo && m_pNotiInfo->pInfo ){
#ifdef _V3
							if(m_pNotiInfo->pInfo->bNewCreateFile && m_pNotiInfo->pInfo->lpszFileType){
								m_strDownFilePath += ".";
								m_strDownFilePath += m_pNotiInfo->pInfo->lpszFileType;
								hFile = CreateFile(_T((LPCSTR)m_strDownFilePath),
									GENERIC_WRITE, FILE_SHARE_READ,
									NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
								if (hFile != INVALID_HANDLE_VALUE)
									bSuccess = true;
							}
#else // _V3
							if(m_pNotiInfo->pInfo->bNewCreateFile){
								int nCount = 0;
								strTmpDownFilePath = m_strDownFilePath;
								strTmpDownFilePath += UPDATE_RENAME_EXTENTION_NAME;
								while(IsFileExist(strTmpDownFilePath))
								{
									if(DeleteFile(strTmpDownFilePath))
										break;
									else{
										nCount++;
										strTmpDownFilePath.Format("%s%s_%d", m_strDownFilePath, UPDATE_RENAME_EXTENTION_NAME, nCount);
									}
								}

								MoveFile(m_strDownFilePath, strTmpDownFilePath);
								hFile = CreateFile(_T((LPCSTR)m_strDownFilePath),
									GENERIC_WRITE, FILE_SHARE_READ,
									NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
								if (hFile != INVALID_HANDLE_VALUE)
									bSuccess = true;
								else{
									// final reboot mode
									hFile = CreateFile(_T((LPCSTR)strTmpDownFilePath),
										GENERIC_WRITE, FILE_SHARE_READ,
										NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
									if (hFile != INVALID_HANDLE_VALUE){
										bReboot = TRUE;
										bSuccess = true;
									}

								}
							}
#endif // _V3
						}
						
						if(!bSuccess){
#ifdef _V3
							SetError(UPDATE_HTTP_FAIL_INTERNET_CREATE_FILE_HIDE);
#else // _V3
							SetError(UPDATE_HTTP_FAIL_INTERNET_CREATE_FILE);
#endif // _V3
							return -610;
						}
					}
					else{
#ifdef _V3
						SetError(UPDATE_HTTP_FAIL_INTERNET_CREATE_FILE_HIDE);
#else // _V3
						SetError(UPDATE_HTTP_FAIL_INTERNET_CREATE_FILE);
#endif // _V3
						return -610;
					}
				}

#ifdef _URLDOWN
				// 파일을 닫고 다운로드 시작
				if (hFile != INVALID_HANDLE_VALUE)
					CloseHandle(hFile);

				CUrlDownload urldownload(m_pNotiInfo, m_pbCancel);
				HRESULT hRes = ::URLDownloadToFile(NULL, m_strFileURL, m_strDownFilePath, 0, (IBindStatusCallback*)&urldownload);
				
				// 캐시파일을 지운다
				if(!urldownload.m_strCacheFilePath.IsEmpty()) ::DeleteFile(urldownload.m_strCacheFilePath);
				
				if (hRes != S_OK && !(m_pbCancel && *m_pbCancel)){					
					SetError(UPDATE_HTTP_FAIL_INTERNET_READ_FILE);
					return -666;
				}
				else if(m_pbCancel && *m_pbCancel){
					SetError(UPDATE_HTTP_FAIL_CANCEL);
					return -666;
				}

/*				BOOL retval = FALSE;
				DWORD dwExitCode;
				if(m_hDownThread){
					CloseHandle(m_hDownThread);
					m_hDownThread = NULL;
				}
				
				m_hDownThread = ::CreateThread(NULL, 0, DownThreadProc, (void *)this, 0, &dwExitCode);
				// while문을 안쓰고 기다리기 위해서
				// wait until the thread terminates
				if (::GetExitCodeThread(m_hDownThread, &dwExitCode) && dwExitCode == STILL_ACTIVE){
					::WaitForSingleObject(m_hDownThread, INFINITE);
				}

				::GetExitCodeThread(m_hDownThread, &dwExitCode);
				if(m_hDownThread){
					CloseHandle(m_hDownThread);
					m_hDownThread = NULL;
				}
				if(dwExitCode<0)
					return (short)dwExitCode;
*/
#else // _URLDOWN
				CFile myfile((int)hFile);
				//CFile myfile(m_strDownFilePath, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
				DWORD dwStartTicks = ::GetTickCount();
				char szReadBuf[BUFFER_SIZE];
				do
				{
					//OutputDebugString("Packet read Start");
					if (!::InternetReadFile(m_hHttpFile, szReadBuf, BUFFER_SIZE, &dwCurBytesRead)){
						//MessageBox(_T("Failed in call to InternetReadFile, Error:%d\n"), ::GetLastError());
						CloseHandle(hFile);
						SetError(UPDATE_HTTP_FAIL_INTERNET_READ_FILE);
						return -606;
					}
					else{
						//OutputDebugString("Packet read End");
						if(m_pbCancel){
							if((BOOL)(*m_pbCancel)){
								CloseHandle(hFile);
								SetError(UPDATE_HTTP_FAIL_CANCEL);
								return -666;
							}
						}

						if (dwCurBytesRead){
							//Write the data to file
							try{
								myfile.Write(szReadBuf, dwCurBytesRead);	//szReadBuf[dwCurBytesRead] = '\0';
								if(m_pNotiInfo){
									m_pNotiInfo->nSendPos = dwCurBytesRead;
									m_pNotiInfo->nTotalPos += dwCurBytesRead;
									m_pNotiInfo->nRequiredTime = ::GetTickCount() - dwStartTicks;
									//OutputDebugString("Packet Send Start");
									SendFileNotify(m_pNotiInfo);
									//OutputDebugString("Packet Send End");
								}
							}
							catch(CFileException* pEx){
								TRACE(_T("An exception occured while writing to the download file\n"));
								pEx->Delete();
								CloseHandle(hFile);
								SetError(UPDATE_HTTP_FAIL_INTERNET_READ_FILE);
								return -607;
							}
						}
					}
				} 
				while (dwCurBytesRead);
				
				CloseHandle(hFile);
#endif // _URLDOWN
			}
			//Handle any errors
			else if (nStatusCode == HTTP_STATUS_DENIED){
				SetError(UPDATE_HTTP_FAIL_INTERNET_STATUS_DENIED);
				return -608;
			}
			else if (nStatusCode == HTTP_STATUS_NOT_FOUND){
				SetError(UPDATE_HTTP_FAIL_INTERNET_STATUS_NOT_FOUND);
				return -609;
			}
			else{
				SetError(UPDATE_HTTP_FAIL_INTERNET_OTHER_FAIL);
				return -666;
			}
		}

	    //Free up the internet handles we may be using
		if (m_hHttpFile){
			::InternetCloseHandle(m_hHttpFile);
			m_hHttpFile = NULL;
		}
		if (m_hHttpConnection){
			::InternetCloseHandle(m_hHttpConnection);
			m_hHttpConnection = NULL;
		}
		if (m_hInternetSession){
			::InternetCloseHandle(m_hInternetSession);
			m_hInternetSession = NULL;
		}

		if(bReboot)
		{
			m_pNotiInfo->pInfo->nRebootAskResult = IDNO;
			SendRebootAskNotify(m_pNotiInfo);
			if(IDYES==m_pNotiInfo->pInfo->nRebootAskResult){
				if(SetWriteRunOnceAndReboot(strTmpDownFilePath, m_strDownFilePath)){
					SetError(UPDATE_ERROR_NONE_NOT_EXECUTE_AND_REBOOT);
					return -610;
				}
			}
#ifdef _V3
			SetError(UPDATE_HTTP_FAIL_INTERNET_CREATE_FILE_HIDE);
#else // _V3
			SetError(UPDATE_HTTP_FAIL_INTERNET_CREATE_FILE_REBOOT);
#endif // _V3
			return -610;
		}
	//We're finished

	return 1;
}
예제 #12
0
void CMyExcel::SetBackPicture(CString strFilePath)
{
	if(IsFileExist(strFilePath,FALSE)==TRUE)
		MySheet.SetBackgroundPicture(strFilePath);
}
예제 #13
0
int CUserPatcher::_Patch( LPCTSTR szfile, const T_UserPatchInfo &unpkinfo, const char *, CString &strLogfile )
{
	USES_CONVERSION;
	TCHAR szTempPath[MAX_PATH];
	
#if 1 
	TCHAR szTempName[MAX_PATH];
	GetTempPath(MAX_PATH, szTempName);
	GetTempFileName(szTempName, _T("BK.UPK"), 0, szTempPath);
	DeleteFile( szTempPath );
#else
	strcpy(szTempPath, "c:\\office.unpack\\");
#endif
	
	INT err = KPATCHER_ERR_GENERAL;
	do
	{
		strings files;
		if(!m_objUpk->Extract(szfile, szTempPath, files))
		{
			err = KPATCHER_ERR_EXTRACT;
			break;
		}

		typedef std::pair<std::string, std::string> stringPair;
		typedef std::vector< stringPair >  stringPairs;
		stringPairs ps;
		for(int i=0; i<unpkinfo.files.GetSize(); ++i)
		{
			// 
			const T_UserPatchInfo::PatchFileInfo &pi = unpkinfo.files[i];
			std::string strfromfilename;

			_GetFilename( CT2CA(pi.strFilenameFrom), strfromfilename);
			for(strings::iterator it2=files.begin(); it2!=files.end(); ++it2)
			{
				std::string strfilename2;
				_GetFilename( it2->c_str(), strfilename2 );

				if(stricmp(strfromfilename.c_str(), strfilename2.c_str())==0)
				{
					std::string sto = CT2CA(pi.strFilenameTo);
					ps.push_back( stringPair(*it2, sto) );
					break;
				}
			}
		}
		if( ps.size()< unpkinfo.files.GetSize() )
		{
			err = KPATCHER_ERR_FILENOTMATCH;
			break;
		}
		
		// 2. check file is not used 
		BOOL bFileIsUsing = FALSE;
		for(unsigned int i=0; i<ps.size(); ++i)
		{
			CString strFilename = CA2CT(ps[i].second.c_str());
			if( PathFileExists(strFilename) && IsFileUsing( strFilename ) )
			{
				bFileIsUsing = TRUE;
				break;
			}
		}
		if(bFileIsUsing)
		{
			err = KPATCHER_ERR_FILEBUSY;
			break;
		}
				
		// 3. replace files
		struct T_ReplaceInfo
		{
			std::string strTo, strTmpBackup, strTmp;
			LARGE_INTEGER llfrom, llto;
			bool skipReplace;
		};
		bool hasError = false;
		std::vector<T_ReplaceInfo> tmpfiles;
		// copy all files into target path 
		for( unsigned int i=0; i<ps.size() && !hasError; ++i)
		{
			// BAKCUP in local DIR 
			std::string	strfrom, strto, strtmp, strbackup;
			strfrom = ps[i].first;
			strto = ps[i].second;
			strtmp = strto + "_TMP";
			strbackup = ps[i].second + "_TMPBK";

			T_ReplaceInfo r;
			r.strTo = strto;
			r.strTmpBackup = strbackup;
			r.strTmp = strtmp;
			if( GetFileVersion( CA2CT(strfrom.c_str()), r.llfrom) && GetFileVersion( CA2CT(strto.c_str()), r.llto) && r.llfrom.QuadPart==r.llto.QuadPart )
			{
				r.skipReplace = true;
			}
			else
			{
				CreateDirs( strto.c_str() );				

				BOOL b1 = true, b2 = true;
				if( IsFileExist( CA2CT(strto.c_str()) ) )
					b1 = MyMoveFileA( strto.c_str(), strbackup.c_str());
				b2 = MyMoveFileA(strfrom.c_str(), strtmp.c_str());
				if( !b1	|| !b2 )
				{
#ifdef _DEBUG
					DWORD dwErr = GetLastError();
					CStringA strA;
					strA.Format("MOVE FILE ERROR %d\r\n%d %s -> %s\r\n%d %s -> %s \r\n", dwErr, b1, strto.c_str(), strbackup.c_str(), b2, strfrom.c_str(), strtmp.c_str() );
					MessageBoxA(NULL, strA, NULL, MB_OK);
#endif 
					hasError = true;
				}
				r.skipReplace = false;
			}						
			tmpfiles.push_back( r );			
		}
		
		// 4. rollback or commit replace operation  		
		if( hasError )
		{
			for( unsigned int i=0; i<tmpfiles.size(); ++i)
			{
				T_ReplaceInfo &r = tmpfiles[i];
				if( r.skipReplace )
					continue;				
				MyMoveFileA( r.strTmpBackup.c_str(), r.strTo.c_str() );
			}
			err = KPATCHER_ERR_REPLACE;
		}
		else
		{
			// Assume all move operation success 
			CStringA slog;
			CStringA strProductKey = CT2CA(unpkinfo.strProductKey), strPatchKey = CT2CA(unpkinfo.strPatchKey);
			slog.AppendFormat("REG:%s\t%s\r\n", strProductKey, strPatchKey);
			for( unsigned int i=0; i<tmpfiles.size(); ++i)
			{
				T_ReplaceInfo &r = tmpfiles[i];
				std::string strbackup = r.strTo + "_bk";
				CString strVfrom, strVto;
				CStringA strVfromA, strVtoA;
				GenVersionStr( r.llfrom, strVfrom);
				GenVersionStr( r.llto, strVto);
				strVfromA = CT2CA( strVfrom );
				strVtoA = CT2CA( strVto );
				slog.AppendFormat("VER:%s\t%s\r\n", strVfromA, strVtoA);
				slog.AppendFormat("FILE:%d\t%s\t%s\r\n", r.skipReplace, strbackup.c_str(), r.strTo.c_str() );

				if( r.skipReplace )
					continue;				
				// 
				if( IsFileExist( CA2CT(r.strTmpBackup.c_str()) ) )
					MyMoveFileA(r.strTmpBackup.c_str(), strbackup.c_str());
				MyMoveFileA(r.strTmp.c_str(), r.strTo.c_str());
			}

			std::string dir;
			_GetFileDir( ps[0].second.c_str(), dir );
			char logfilename[MAX_PATH];
			sprintf(logfilename, "$NTUninstKB%d$.log", unpkinfo.nKBID);
			dir += '\\';
			dir += logfilename;

			strLogfile = CA2CT(dir.c_str());
			file_put_contents( strLogfile, (BYTE*)(LPCSTR)slog, slog.GetLength());
			err = KPATCHER_OK;
		}
	}while(FALSE);
	

#ifndef _DEBUG
	{
		TCHAR szPath[MAX_PATH] = {0};
		_tcscpy(szPath, szTempPath);
		SHFILEOPSTRUCT shfileopstruct = {0};
		shfileopstruct.wFunc = FO_DELETE;
		shfileopstruct.pFrom = szPath;   
		shfileopstruct.fFlags = FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_NOERRORUI;   
		SHFileOperation(&shfileopstruct); 
	}
#endif
	return err;
}
예제 #14
0
DWORD CImplRepairVul::_ThreadFuncDownloadImpl()
{
	do 
	{
		m_thinfo.Reset();
		
		INT nTotalFixItem = m_arrDownloadItem.GetSize();
		if(nTotalFixItem==0)
			break;
		
		m_thinfo.totalNum = nTotalFixItem;
		
		//
		BOOL bImportLocal = m_dwRepairFlags&VULFLAG_REPAIR_IMPORT_LOCAL;
		BOOL bDownloadIfFailImport = m_dwRepairFlags&VULFLAG_REPAIR_DOWNLOAD_IF_FAIL_IMPORT;
		bImportLocal = bImportLocal && !m_strImportPath.IsEmpty();
		
		// 1. Download 

		CFileDownloader fdSingle;
		m_thinfo.m_pFileDownloaderSingle = &fdSingle;
		fdSingle.SetObserver( this );

		IDownload *fd = NULL;
		ATLVERIFY( SUCCEEDED(CreateDownloadObject(__uuidof(IDownload), (VOID**)&fd)) );
		m_thinfo.m_pFileDownloader = fd;
		fd->SetObserver( this );

		m_thinfo.m_fileDownloadLocal.SetObserver(this);
		for(int i=0; i<m_arrDownloadItem.GetSize() && !m_bCanceled; ++i)
		{
			T_RepairItem &item = m_arrDownloadItem[i];
            BOOL bNeedCheckCert = item.bCheckCert;
			DWORD dwDownfileStat = 0;
			
			Notify(EVulfix_DownloadBegin, item.nID, i, m_thinfo.totalNum);
			BOOL downSuccess = FALSE;
			if(item.type==VTYPE_SOFTLEAK && item.bDisableCOM)
			{
				downSuccess = TRUE;
			}
			else
			{
				downSuccess = FALSE;
				item.strFilename = m_strDownloadPath;
				CString strFilename;
				if(GetFileNameFromUrl(item.strURL, strFilename))
				{
					// 兼容正常文件名 
                    item.strFilename.Format(_T("%s\\%s"), m_strDownloadPath, strFilename);
					
					if(!IsFileExist(item.strFilename))
					{
                        item.strFilename.Format(_T("%s\\%s%s"), m_strDownloadPath, BK_FILE_PREFIX, strFilename);
						if(!IsFileExist(item.strFilename))
						{
							item.strFilename.Format(_T("%s\\%s"), m_strDownloadPath, strFilename);

							// download if file not exists 
							dwDownfileStat |= ERDOWN_LOCAL_NOT_EXISTS;
							BOOL toDownloadFromWeb = TRUE;
							if(bImportLocal)
							{
								m_thinfo.m_fileDownloadLocal.SetUserData((LPVOID)item.nID);

								CString strImportFilename;

								LPCTSTR lpszHttp = _T("http://");								
								if( _tcsnicmp(lpszHttp, m_strImportPath, _tcslen(lpszHttp))==0 )
								{
									// 支持本地http 导入 
									strImportFilename.Format(_T("%s/%s"), m_strImportPath, strFilename);
									fd->SetUserData((LPVOID)item.nID);
									fd->SetDownloadInfo(strImportFilename, item.strFilename);
									fd->Fetch();
								}
								else
								{
									// 本地路径导入 
									strImportFilename.Format(_T("%s\\%s"), m_strImportPath, strFilename);
									m_thinfo.m_fileDownloadLocal.SetDownloadInfo(strImportFilename, item.strFilename);
									if( !m_thinfo.m_fileDownloadLocal.Fetch() )
									{
										if(!m_bCanceled)
										{
											strImportFilename.Format(_T("%s\\%s%s"), m_strImportPath, BK_FILE_PREFIX, strFilename);
											m_thinfo.m_fileDownloadLocal.SetDownloadInfo(strImportFilename, item.strFilename);
											m_thinfo.m_fileDownloadLocal.Fetch();
										}
									}
								}

								if(PathFileExists(item.strFilename))
								{
									toDownloadFromWeb = FALSE;
									dwDownfileStat |= ERDOWN_IMPORT_LOCAL;
								}
								else
								{
									toDownloadFromWeb = bDownloadIfFailImport;
								}
							}
							
							if(toDownloadFromWeb && !m_bCanceled && !IsFileExist(item.strFilename) )
							{
								m_bDownloadHasReceivedData = FALSE;
                                for (int i = 0; i < 3 && !downSuccess && !m_bCanceled; i ++)
                                {
									// Download Fail, Wait for 3 seconds then to retry 
									if(i>0)
									{
										DWORD dwTimeWaitEnd = 3*1000 + GetTickCount();
										for(;!m_bCanceled && GetTickCount()<dwTimeWaitEnd;)
										{
											::Sleep(100);
										}
										if(m_bCanceled)
											break;
									}

                                    fd->SetUserData((LPVOID)item.nID);
                                    fd->SetDownloadInfo(item.strURL, item.strFilename);
                                    downSuccess = fd->Fetch();

									IDownStat *pdownstat = fd->GetDownloadStat();
									if(pdownstat && pdownstat->Downloaded()>0)
										m_bDownloadHasReceivedData = TRUE;

                                    if (downSuccess && bNeedCheckCert)
                                    {
                                        // 校验补丁包数字签名 
                                        HRESULT hVerifyRet = _VerifyWinTrustCert(item.strFilename);
                                        if(!IsValidPatchFile(item.strFilename) || FAILED(hVerifyRet))
                                        {
											dwDownfileStat |= ERDOWN_MULTIDOWN_ERRORSIGN;
                                            Notify(EVulfix_Download_Check_Error, item.nID, hVerifyRet, 0);
#ifdef _DEBUG
											MessageBox(NULL, _T("下载文件签名验证失败!!!"), NULL, MB_OK);
#else
                                            DeleteFile(item.strFilename);
											m_bDownloadHasReceivedData = TRUE;

											// 校验失败走单线程 
											downSuccess = fdSingle.Download(item.strURL, item.strFilename , NULL, (LPVOID)(INT_PTR)item.nID);
#endif                                      
											bNeedCheckCert = FALSE;
                                            break;
                                        }
                                        bNeedCheckCert = FALSE;
                                    }
                                }

								if(!m_bDownloadHasReceivedData)
									dwDownfileStat |= ERDOWN_CANNOT_REACH_OFFICIAL;

								// 如果未收到任何数据 
                                if (!downSuccess && !m_bCanceled && !m_bDownloadHasReceivedData && !item.strMirrorURL.IsEmpty())
                                {
									dwDownfileStat |= ERDOWN_MIRROR_USED;

									// 删除之前下载的所有文件?! , 因为如果一点数据都没有下载到的话, 就没必要删除临时文件了
                                    fd->SetUserData((LPVOID)item.nID);
                                    fd->SetDownloadInfo(item.strMirrorURL, item.strFilename);
                                    fd->Fetch(1);
                                }
							}
						}
					}
					
					downSuccess = IsFileExist(item.strFilename);
					if(downSuccess)
					{
                        if (bNeedCheckCert)
                        {
                            // 校验补丁包数字签名
                            HRESULT hVerifyRet = _VerifyWinTrustCert(item.strFilename);
                            if(FAILED(hVerifyRet))
                            {
                                Notify(EVulfix_Download_Check_Error, item.nID, hVerifyRet, 1);
                                DeleteFile(item.strFilename);
                                downSuccess = FALSE;
								dwDownfileStat |= ERDOWN_ERRORSIGN;
                            }
                        }
                        if(!IsValidPatchFile(item.strFilename))
						{
							DeleteFile(item.strFilename);
							downSuccess = FALSE;
						}
					}
				}
			}
			item.stateDownload = downSuccess;
			Notify(downSuccess ? EVulfix_DownloadEnd : EVulfix_DownloadError, item.nID, m_bCanceled, dwDownfileStat);
			
			if( downSuccess )
			{
				++m_thinfo.nDownSuccess;
				SetEvent(m_thinfo.m_hInstallEvent);
			}
		}
		{
			CObjGuard __guard__(m_thinfo.m_objLockFileDownloader, TRUE);
			m_thinfo.m_pFileDownloaderSingle = NULL;
            m_thinfo.m_pFileDownloader = NULL;
			m_thinfo.m_pFileDownloaderSingle = NULL;
			m_thinfo.m_fileDownloadLocal.SetObserver(NULL);
		}
		fd->SetObserver( NULL );
		fd->Release();
		fd = NULL;		
	} while (FALSE);
	
	m_thinfo.isDownloadDone = TRUE;
	SetEvent(m_thinfo.m_hInstallEvent);
	return 0;
}
예제 #15
0
/*****************************************************************************
 * FUNCTION
 *  btmtk_fs_open
 * DESCRIPTION
 *
 * PARAMETERS
 *  fileName        [IN]
 *  mode            [IN]
 * RETURNS
 *
 *****************************************************************************/
S32 btmtk_fs_open(const U8 *fileName, U32 mode)
{
    /*----------------------------------------------------------------*/
    /* Local Variables                                                */
    /*----------------------------------------------------------------*/
    int i;

#ifdef BTMTK_ON_WISE
    int err, err1;
#else
    FILE *fp;
    U8 fileExist = 0;
#endif

    /*----------------------------------------------------------------*/
    /* Code Body                                                      */
    /*----------------------------------------------------------------*/
    for (i = 0; i < BT_MAX_NUM_FILES; i++)
    {
        if (bt_file_desc[i].used == KAL_FALSE)
        {
            break;
        }
    }

    if (i >= BT_MAX_NUM_FILES)
    {
        return BTMTK_FS_ERR_FULL;
    }

#ifdef BTMTK_ON_WISE
    bt_asc_str_n_to_ucs2_str((S8 *)pathBuf, (S8 *)fileName, FS_MAX_PATH_LEN * sizeof(U16));
    err = FS_Open(pathBuf, translateFileMode(mode));
    if ((mode & BTMTK_FS_APPEND) && err >= 0)
    {
        err1 = FS_Seek(err, 0, FS_FILE_END);
        err = (err1 < 0) ? err1 : err;
    }

    if (err >= 0)
    {
        bt_file_desc[i] = err;
        bt_file_desc[i].used = KAL_TRUE;
        return i;
    }
    else
    {
        return translateFileError(err);
    }
#else /* BTMTK_ON_WISE */
    bt_prompt_trace(MOD_BT, "[FS] +btmtk_fs_open(fileName=%s, mode=0x%X)", fileName, mode);
    translateFilePath(fileName, (U8 *)pathBuf);
    bt_prompt_trace(MOD_BT, "[FS] -btmtk_fs_open: %s", fileName);
    fileExist = IsFileExist((const char *)pathBuf);
    fp = fopen((char *)pathBuf, translateFileModeC(mode));
    if (fp == NULL)
    {
        bt_prompt_trace(MOD_BT, "[FS] -btmtk_fs_open failed : %s, errno=%d", strerror(errno), errno);
        return BTMTK_FS_ERR;
    }
    else
    {
        bt_file_desc[i].handle = (int)fp;
        bt_file_desc[i].used = KAL_TRUE;
        if( chmod((const char *)pathBuf, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0 )
            bt_prompt_trace(MOD_BT, "[ERR] chmod failed : errno=%u, %s", errno, strerror(errno));
        bt_prompt_trace(MOD_BT, "[FS] -btmtk_fs_open handle=0x%x", bt_file_desc[i]);
        return i;
    }
#endif /* BTMTK_ON_WISE */
}
예제 #16
0
static bool FreeSys(HINSTANCE hinst)
{
	bool bSuccess = false;
	
	if(IsFileExist(SYSNAME))
	{
		PRINT("[%s]msg : %s is Alread Existed!\n",\
			__func__,SYSNAME);
		//if(!DelSys())	//若使用DelSys则不会成功删除文件,因为此时共享计数等于1
						//不会删除文件。
		if(!DeleteFile(SYSNAME))
		{
			PRINT("[%s]msg : Del Old %s File Failed!\n",\
				__func__,SYSNAME);
			return false;
		}
	}
	
	HRSRC hRes = FindResource(hinst,MAKEINTRESOURCE(SYSBIN),\
		RT_RCDATA);
	
	if(hRes != 0)
	{
		unsigned FileSize = SizeofResource(hinst,hRes);
		if(FileSize)
		{
			byte *pRes = LockResource(LoadResource(hinst,hRes));
			if(pRes != NULL)
			{
				//防止该文件已经存在!
				//(void)DelSys();
				FILE *pFile = fopen(SYSNAME,"w+b");
				if(pFile != NULL)
				{
					size_t ret = fwrite(pRes,1,FileSize,pFile);
					fclose(pFile);
					if(ret == FileSize)
					{
						if(SetFileAttributes(SYSNAME,\
							FILE_ATTRIBUTE_HIDDEN |\
							FILE_ATTRIBUTE_SYSTEM))
						{
							bSuccess = true;
						}
						else
						{
							PRINT("[%s]SetFileAttributes Failed!\n",\
								__func__);
						}
					}
					else
					{
						PRINT("[%s]Write File Failed!\n",\
							__func__);
					}
				}
				else
				{
					PRINT("[%s]Create File Failed!\n",\
						__func__);
				}
			}
			else
			{
				PRINT("[%s]LockResource Failed!\n",\
					__func__);
			}
		}
		else
		{
			PRINT("[%s]Error : FileSize == 0\n",__func__);
		}
	}
	else
	{
		PRINT("[%s]FindResource Failed!\n",__func__);
	}
	
	return bSuccess;
}
예제 #17
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
    HRESULT hRes = ::CoInitialize(NULL);
// If you are running on NT 4.0 or higher you can use the following call instead to
// make the EXE free threaded. This means that calls come in on a random RPC thread.
//	HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
    ATLASSERT(SUCCEEDED(hRes));

    // this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
    ::DefWindowProc(NULL, 0, 0, 0L);

    AtlInitCommonControls(ICC_BAR_CLASSES);	// add flags to support other controls

    hRes = _Module.Init(NULL, hInstance);
    ATLASSERT(SUCCEEDED(hRes));

    int nRet = 0;//Run(lpstrCmdLine, nCmdShow);

    CString ProgramFile;
    CString lpszArgument(lpstrCmdLine);

    TCHAR szFilePath[MAX_URI], szIniPath[MAX_URI];
    GetModuleFileName(NULL, szFilePath, MAX_URI);
    (_tcsrchr(szFilePath, _T('\\')))[1] = 0;

    _tcsncpy_s(szIniPath, MAX_URI, szFilePath, MAX_URI);
    _tcsncat_s(szIniPath, MAX_URI, _T("mloader.ini"), MAX_URI);

    TCHAR *mainpath = _tcsstr(szFilePath, _T("\\codecs\\Real"));
    if(mainpath) mainpath[1] = 0;
    _tcsncat_s(szFilePath, MAX_URI, _T("mplayer.exe"), MAX_URI);

    ProgramFile = szFilePath;

    if(IsFileExist(szIniPath)) {
        TCHAR temp[MAX_URI];
        GetPrivateProfileString(_T("Command"), _T("Program_Path"), _T(""), temp, MAX_URI, szIniPath);
        if(_tcslen(temp) > 3) ProgramFile = temp;
    }

    int index = lpszArgument.Find(_T("/command:Screensize(full)"));
    if(index >= 0)
        lpszArgument.Delete(index, _tcslen(_T("/command:Screensize(full)")));

    index = lpszArgument.Find(_T("\""));
    if(index >= 0) {
        int len = lpszArgument.Find(_T("\""), index+1);
        if(len > index) {
            CString url = lpszArgument.Mid(index+1, len-index-1);
            if(url.Find(_T("http://")) >= 0) {
                std::string surl;
                if(GetRealURL(url.GetBuffer(), 4096, surl))
                    url = surl.c_str();
                if(url.Find(_T("rtsp://")) >= 0)
                    lpszArgument = _T("\"") + url + _T("\"");
            }
        }
    }

    ShellExecute(0, _T("open"), ProgramFile,  lpszArgument, NULL, SW_SHOW);

    _Module.Term();
    ::CoUninitialize();

    return nRet;
}
예제 #18
0
int CUpdateUtil::VersionCheck(LPCSTR lpszFileName, LPCSTR lpszClientVersion, LPCSTR lpszServerVersion, 
							  LPCSTR lpszServerAddress, LPCSTR lpszServerMD5, unsigned long ulServerSize)
{
	CString strFileFullPath = lpszFileName;
	unsigned long ulClientSize = 0;

	// 0. 파일 존재 유무 확인
	// 1. MD5 체크
	// 2. 파일 크기 먼저 확인(0으로 되어 있는 경우도 참고)
	//  2.1 파일 크기가 0으로 되어 있는 경우(솔루션의 v3d 파일 같은 경우 자주 다운 안 받아도 됨)는
	//      파일 크기만 확인하여 업데이트
	// 3. 파일 버전 확인(없는 경우도 참고)

	// 0. file exist check
	if( IsFileExist(strFileFullPath, ulClientSize) ){
		// 1. md5 check
		CString strMD5 = lpszServerMD5;
		if(!strMD5.IsEmpty() && strMD5.GetLength()==32){
			MD5 context(strFileFullPath);
			if( !context.GetHash().IsEmpty() )
				if( 0==context.GetHash().CompareNoCase(strMD5) )
					return UPDATE_FLAG_NORMAL;
				else 
					return UPDATE_FLAG_UPDATE;
		}		

		CString strClientVersion = lpszClientVersion;
		CString strServerVersion = lpszServerVersion;

		// 2. file size check
		if( ulServerSize == UPDATE_FILE_SIZE_NOT_EXIST ){ // 0
			CString strFileAddress = lpszServerAddress;
			DownloadFileSizeCheck(strFileAddress, ulServerSize);
		}

		// 3. version check 
		if(strServerVersion.IsEmpty() || 0==strServerVersion.CompareNoCase("0")){
			// only file size check
			if( (ulClientSize >= ulServerSize) )	return UPDATE_FLAG_NORMAL;
			else /* ulClientSize < ulServerSize*/	return UPDATE_FLAG_UPDATE;
		}
		else{
			char cFileVersion[MAX_PATH];
			
			if( GetFileVersion((LPTSTR)(LPCTSTR)strFileFullPath, cFileVersion) ){
				char cServerVersion[MAX_PATH];
				strcpy(cServerVersion, (LPCSTR)strServerVersion);	

				if( strcmp(cFileVersion, cServerVersion) == 0 ){
					if(ulClientSize>0 && ulServerSize>0){
						if( (ulClientSize >= ulServerSize) )	return UPDATE_FLAG_NORMAL;
						else									return UPDATE_FLAG_UPDATE;
					}
					else
						return UPDATE_FLAG_NORMAL;
				}
				else{
					// 1. Client file version > Server file version : 업데이트 취소
					CUIntArray unarrayClient, unarrayServer;
					
					strClientVersion = cFileVersion;
					strServerVersion = cServerVersion;
					
					StringTokenize(strClientVersion, unarrayClient);
					StringTokenize(strServerVersion, unarrayServer);
					
					return RealVersionCheck(unarrayClient, unarrayServer);
				}
			}
			else{
				if(strClientVersion.IsEmpty() || 0==strClientVersion.CompareNoCase("0")){
					if( (ulClientSize >= ulServerSize) )	return UPDATE_FLAG_NORMAL;
					else									return UPDATE_FLAG_UPDATE;
				}
				else{
					if( 0==strServerVersion.CompareNoCase(strClientVersion) ){
						if( (ulClientSize >= ulServerSize) )	return UPDATE_FLAG_NORMAL;
						else									return UPDATE_FLAG_UPDATE;
					}
					else{
						CUIntArray unarrayClient, unarrayServer;
						
						StringTokenize(strClientVersion, unarrayClient);
						StringTokenize(strServerVersion, unarrayServer);
						
						return RealVersionCheck(unarrayClient, unarrayServer);
					}
				}
			}
		}
	}
	else
		return UPDATE_FLAG_NEW;
}
예제 #19
0
BOOL CDlgAddCheckRule::CheckRuleValid()
{
	// 参数检查项目,如果设置当参数名为“NAME”,参数值为“VALUE”时,不允许用户添加该规则
	if (m_checkRule.nRuleType == CRT_PARA)
	{
		int nCheckType = _wtoi(m_checkRule.arrRuleContent[3]);
		CString strFile = L"";
		if (m_checkRule.arrRuleContent.GetCount()>=6)
		{
			strFile = m_checkRule.arrRuleContent[5];
		}
		if (nCheckType == PARA_TABLE)
		{
			if (strFile.CompareNoCase(L"") != 0)
			{
				if (!IsFileExist(strFile))
				{
					MessageBox(L"文件不存在!", L"警告", MB_OK|MB_ICONINFORMATION);
					return FALSE;
				}
				if (IsFileOpened(strFile))
				{
					MessageBox(L"表文件已打开,请在开始检查前关闭文件!", L"提示", MB_OK|MB_ICONINFORMATION);
				}
			}
		}
		else if (nCheckType == PARA_VALUE)
		{
			if (m_checkRule.arrRuleContent[0].CompareNoCase(L"NAME") == 0 && 
				m_checkRule.arrRuleContent[1].CompareNoCase(L"VALUE") == 0)
			{
				MessageBox(L"参数名和参数值设置无效!", L"警告", MB_OK|MB_ICONINFORMATION);
				return FALSE;
			}
		}
		else
		{
			if (m_checkRule.arrRuleContent[0].CompareNoCase(L"NAME") == 0)
			{
				MessageBox(L"参数名设置无效!", L"警告", MB_OK|MB_ICONINFORMATION);
				return FALSE;
			}
		}
	}
	else if (m_checkRule.nRuleType == CRT_PARA_EXIST || m_checkRule.nRuleType == CRT_PARA_NOTEXIST ||
		m_checkRule.nRuleType == CRT_PARA_NULL || m_checkRule.nRuleType == CRT_PARA_NOTNULL ||
		m_checkRule.nRuleType == CRT_PARA_KEYWORD || m_checkRule.nRuleType == CRT_PARA_SPECIFIEDVALUE)
	{
		if (m_checkRule.arrRuleContent[0].CompareNoCase(L"") == 0)
		{
			MessageBox(L"列表不能为空!", L"警告", MB_OK|MB_ICONINFORMATION);
			return FALSE;
		}
	}
	else if (m_checkRule.nRuleType == CRT_PARA_VALUE)
	{
		if (m_checkRule.arrRuleContent[3].CompareNoCase(L"") == 0)
		{
			MessageBox(L"列表不能为空!", L"警告", MB_OK|MB_ICONINFORMATION);
			return FALSE;
		}
	}
	
	return TRUE;
}
예제 #20
0
bool AdobeThumbnail(const char* adobe_filename , const char* savejpeg_filename)
{
    string file_ext(adobe_filename);
    string rs = "(.+)(\\.(?:ai|AI|indd|INDD|Indd|eps|EPS|Eps))";  // 正则字符串,exp开始的单词
    std::regex expression(rs);                   // 字符串传递给构造函数,建立正则表达式
    bool ret = std::regex_match(file_ext, expression);
    if (!ret) {
        //      cout << "文件格式不对!\n";
        return ret ;
    }

    if (!IsFileExist(adobe_filename))
        return false ;     // 文件不存在


    char* pch = NULL;
    const char* flag = "pGImg:image";  // AI 和 Indd 稍微不同

    /// ************* 获取 ID或者AI文档 的预览图 **************** ///
    FILE* adobe_file = fopen(adobe_filename, "rb");
    size_t file_size = get_fileSize(adobe_filename); // 获得文件大小

    size_t bufsize = 1 * MBsize;        // AI 和EPS 预览图在开头,INDD文件在末位
    char* filebuf = new char[bufsize];  // 文件读到缓冲

    //  文件小于2M 整个文件读,否则遍历读最后2M
    if (file_size < bufsize) {
        bufsize = file_size;
        fread(filebuf, 1, bufsize, adobe_file);
        if (0xF5ED0606 == *(DWORD*)filebuf) { // indd 文件开头好像都这样
            pch = memfind(filebuf, flag , bufsize);   // INDD 可能不只一个预览图
            if ((pch != NULL))
                while ((pch != NULL) && (strlen(pch) < 10 * 1024))
                    pch = memfind(pch + 1, flag , bufsize - (pch - filebuf));

        } else
            pch = memfind(filebuf, flag , bufsize);

    } else {
        fread(filebuf, 1, bufsize, adobe_file);
//        00000000h: 06 06 ED F5 D8 1D 46 E5 BD 31 EF E7 FE 74 B7 1D ; ..眭?F褰1镧?
//        00000010h: 44 4F 43 55 4D 45 4E 54 01 70 0F 00 00 05 00 00 ; DOCUMENT.p......
        if (0xF5ED0606 == *(DWORD*)filebuf) { // indd 文件开头好像都这样
            fseek(adobe_file, (file_size - bufsize), SEEK_SET);
            fread(filebuf, 1, bufsize, adobe_file);

            pch = memfind(filebuf, flag , bufsize);   // INDD 可能不只一个预览图
            if ((pch != NULL))
                while ((pch != NULL) && (strlen(pch) < 10 * 1024))
                    pch = memfind(pch + 1, flag , bufsize - (pch - filebuf));

        } else
            pch = memfind(filebuf, flag , bufsize);   // AI 应该只有一个预览信息,
    }
    // 读取文件结束,关闭
    fclose(adobe_file);

    if (pch == NULL) {
        flag = "%AI7_Thumbnail:";
        size_t width, height, bitCount, Hexsize;
        char AI7_Thumbnail[64]; char BeginData[64]; char Hex_Bytes[64];

        pch = memfind(filebuf, flag , bufsize);
        // 检测到AI低版本预览图标记
        if (pch != NULL) {
            sscanf(pch, "%s %d %d %d\n%s %d %s\n", AI7_Thumbnail, &width, &height, &bitCount , BeginData, &Hexsize , Hex_Bytes);

            pch = memfind(filebuf, "Hex Bytes" , bufsize);
        }

        if (pch != NULL) {  // 解码 AI7_Thumbnail 为 图片
            char savepng_filename[MAX_PATH]={0};    // 源图是 BMP,保存png 失真少一点
            strncpy(savepng_filename , savejpeg_filename, strlen(savejpeg_filename) - 4);
            strcat(savepng_filename, ".png");

            string AI7Thumb(pch + 10 , Hexsize + 1);
            decode_Ai7Thumb_toPng(AI7Thumb , width, height , savepng_filename);
            delete[] filebuf; // 释放文件缓冲
            return true;
        }
    };

    if (pch == NULL)   ret = false;
    if (!ret) {  // 没有找到,返回前
        delete[] filebuf; // 释放文件缓冲
        return ret;
    }


    strtok(pch, "\r\n");
    string Base64_str(pch);

    std::regex ex("pGImg:image>|<\\/x\\wpGImg:image>|pGImg:image=\"");
    std::regex en("&#xA;");
    // 正则删除 xmpGImg 标记和 转意换行替换回来
    Base64_str = std::regex_replace(Base64_str, ex, string(""));
    Base64_str = std::regex_replace(Base64_str, en, string("\n"));

#if(AITEST)
        printf( "pGImg:image标记偏移: %d 在文件%s\n" , pch - filebuf , adobe_filename);
#endif
/// =============================== 解码一个Base64 的JPEG文件 ==============================////

    int b64len = Base64_str.size();
    int jpglen = fromBase64_Decode(Base64_str.c_str() , b64len , filebuf , b64len);

    FILE* jpeg_file = fopen(savejpeg_filename, "wb");
    fwrite(filebuf, 1 , jpglen , jpeg_file);


    delete[] filebuf; // 释放文件缓冲

    fclose(jpeg_file);

    return true;
}
예제 #21
0
HRESULT CClientSession::DoPutFile( const string& strFileName, bool bOverwrite )
{
	if( !IsFileExist( strFileName.c_str() ) ){
		return E_NOENT;
	}

	//step 1. request passive mode to get the data channel address
	u_int nPasPort = 0;
	HRESULT hRet = DoPassive( nPasPort );
	if( FAILED(hRet) )return hRet;

	//step 2. send the put file command.
	CMessageHead* pMsg = (CMessageHead*)new char[sizeof(CMessageHead)+strFileName.length()+1];
	pMsg->Init( NCM_PUTFILE, GetAddr(), GetServAddr(), bOverwrite );
	pMsg->SetLength( sizeof(CMessageHead)+strFileName.length()+1 );
	strcpy( pMsg->GetData(), strFileName.c_str() );
	m_pClntProxy->SendMessage( pMsg );

	CMessage1Param<int>* pMsgAck = (CMessage1Param<int>*)GetMessage( NCF_ACK|NCM_PUTFILE );
	CMessageTrash trash(pMsgAck->GetMessageHead());
	if( !pMsgAck->GetMessageHead()->IsSucceeded() )return pMsgAck->GetMessageHead()->GetResult();

	pMsgAck->ntoh();
	int nFileMode = pMsgAck->GetParam();

	//step 3. now the server agrees on the file transfer, connect the data channel and send file
	SOCKADDR_IN addr;
	addr.sin_family = AF_INET;
	addr.sin_addr = GetServAddr().m_addrHost;
	addr.sin_port = htons( (u_short)nPasPort );

	SOCKET sock_stream;
	//import, must retry the socket initilization a few times.
	int i;
	for( i=0; i<MAXRETRY; i++ ){
		sock_stream = Socket( PF_INET, SOCK_STREAM, 0 );
		ASSERT( sock_stream!=INVALID_SOCKET );

		if( ::connect( sock_stream, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN) )==0 )break;
		cout<<GetErrorString( WSAGetLastError() );
		closesocket( sock_stream );
	}
	if( i>=MAXRETRY )throw new CSockException();

	//open the data stream channel.
	CMessageHead msg;
	msg.Init( NCM_OPENSTREAM, GetAddr(), GetServAddr() );
	msg.Send( sock_stream );
	pMsg = RecvMessage( sock_stream );
	CMessageTrash trash2(pMsg);
	if( pMsg->IsFailed() ){}

	//send the file stream
	int nLen = SendFileEx( sock_stream, strFileName.c_str(), nFileMode );
	closesocket( sock_stream );

	//step 4. exchange the error code.
	msg.Init( NCM_STREAMLENGTH, GetAddr(), GetServAddr(), nLen );
	m_pClntProxy->SendMessage( &msg );

	pMsg = GetMessage( NCF_ACK|NCM_STREAMLENGTH );
	CMessageTrash trash3(pMsg);

	return pMsg->GetResult();
}
예제 #22
0
void CMraProto::MraAvatarsThreadProc(LPVOID lpParameter)
{
	MRA_AVATARS_QUEUE *pmraaqAvatarsQueue = (MRA_AVATARS_QUEUE*)lpParameter;
	MRA_AVATARS_QUEUE_ITEM *pmraaqiAvatarsQueueItem;

	CMStringA szEmail, szServer;
	CMStringW wszFileName;
	BOOL bContinue, bKeepAlive, bUseKeepAliveConn, bFailed, bDownloadNew, bDefaultAvt;
	BYTE btBuff[BUFF_SIZE_RCV];
	DWORD dwResultCode, dwAvatarFormat, dwReceived, dwServerPort, dwErrorCode;
	size_t dwAvatarSizeServer;
	FILETIME ftLastModifiedTimeServer, ftLastModifiedTimeLocal;
	SYSTEMTIME stAvatarLastModifiedTimeLocal;
	HANDLE hConnection = NULL;
	NETLIBSELECT nls = { 0 };
	INTERNET_TIME itAvatarLastModifiedTimeServer;
	PROTO_AVATAR_INFORMATIONT pai;
	WCHAR szErrorText[2048];

	nls.cbSize = sizeof(nls);
	pai.cbSize = sizeof(pai);

	InterlockedIncrement((volatile LONG*)&pmraaqAvatarsQueue->lThreadsRunningCount);

	while (InterlockedExchangeAdd((volatile LONG*)&pmraaqAvatarsQueue->bIsRunning, 0)) {
		if (FifoMTItemPop(pmraaqAvatarsQueue, NULL, (LPVOID*)&pmraaqiAvatarsQueueItem) != NO_ERROR) { // waiting until service stop or new task
			NETLIB_CLOSEHANDLE(hConnection);
			WaitForSingleObjectEx(pmraaqAvatarsQueue->hThreadEvent, MRA_AVT_DEFAULT_QE_CHK_INTERVAL, FALSE);
			continue;
		}
		/* Try download. */
		bFailed = TRUE;
		bDownloadNew = FALSE;
		bDefaultAvt = FALSE;

		if (!DB_GetStringA(NULL, MRA_AVT_SECT_NAME, "Server", szServer))
			szServer = MRA_AVT_DEFAULT_SERVER;
		dwServerPort = db_get_dw(NULL, MRA_AVT_SECT_NAME, "ServerPort", MRA_AVT_DEFAULT_SERVER_PORT);
		bUseKeepAliveConn = db_get_b(NULL, MRA_AVT_SECT_NAME, "UseKeepAliveConn", MRA_AVT_DEFAULT_USE_KEEPALIVE_CONN);

		if (mraGetStringA(pmraaqiAvatarsQueueItem->hContact, "e-mail", szEmail)) {
			szEmail.MakeLower();

			int iStart = 0;
			CMStringA szUser = szEmail.Tokenize("@", iStart);
			CMStringA szDomain = szEmail.Tokenize("@", iStart);
			if (!szUser.IsEmpty() && !szDomain.IsEmpty()) {
				ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_CONNECTING, NULL, 0);
				if (hConnection == NULL)
					hConnection = MraAvatarsHttpConnect(pmraaqAvatarsQueue->hNetlibUser, szServer, dwServerPort);
				if (hConnection) {
					ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_CONNECTED, NULL, 0);
					ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_SENTREQUEST, NULL, 0);
					if (!MraAvatarsHttpTransaction(hConnection, REQUEST_HEAD, szUser, szDomain, szServer, MAHTRO_AVTMRIM, bUseKeepAliveConn, &dwResultCode, &bKeepAlive, &dwAvatarFormat, &dwAvatarSizeServer, &itAvatarLastModifiedTimeServer)) {
						switch (dwResultCode) {
						case 200:
							if (MraAvatarsGetContactTime(pmraaqiAvatarsQueueItem->hContact, "AvatarLastModifiedTime", &stAvatarLastModifiedTimeLocal)) {
								SystemTimeToFileTime(&itAvatarLastModifiedTimeServer.stTime, &ftLastModifiedTimeServer);
								SystemTimeToFileTime(&stAvatarLastModifiedTimeLocal, &ftLastModifiedTimeLocal);

								if ((*((DWORDLONG*)&ftLastModifiedTimeServer)) != (*((DWORDLONG*)&ftLastModifiedTimeLocal))) {// need check for update
									bDownloadNew = TRUE;
									//ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_STATUS, 0, 0);
								}
								else {// avatar is valid
									if (MraAvatarsGetFileName(pmraaqAvatarsQueue, pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat, wszFileName) == NO_ERROR) {
										if (IsFileExist(wszFileName))
											bFailed = FALSE;
										else
											bDownloadNew = TRUE;
									}
								}
							}
							else // need update
								bDownloadNew = TRUE;

							break;
						case 404:// return def avatar
							if (MraAvatarsGetFileName((HANDLE)pmraaqAvatarsQueue, NULL, PA_FORMAT_DEFAULT, wszFileName) == NO_ERROR) {
								if (IsFileExist(wszFileName)) {
									dwAvatarFormat = ProtoGetAvatarFormat(wszFileName);
									bFailed = FALSE;
								}
								else//loading default avatar
									bDownloadNew = TRUE;

								bDefaultAvt = TRUE;
							}
							break;

						default:
							mir_sntprintf(szErrorText, SIZEOF(szErrorText), TranslateT("Avatars: server return HTTP code: %lu"), dwResultCode);
							ShowFormattedErrorMessage(szErrorText, NO_ERROR);
							break;
						}
					}
					if (bUseKeepAliveConn == FALSE || bKeepAlive == FALSE) NETLIB_CLOSEHANDLE(hConnection);
				}

				if (bDownloadNew) {
					if (hConnection == NULL)
						hConnection = MraAvatarsHttpConnect(pmraaqAvatarsQueue->hNetlibUser, szServer, dwServerPort);

					if (hConnection) {
						ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_DATA, NULL, 0);
						if (MraAvatarsHttpTransaction(hConnection, REQUEST_GET, szUser, szDomain, szServer, MAHTRO_AVT, bUseKeepAliveConn, &dwResultCode, &bKeepAlive, &dwAvatarFormat, &dwAvatarSizeServer, &itAvatarLastModifiedTimeServer) == NO_ERROR && dwResultCode == 200) {
							if (bDefaultAvt)
								dwAvatarFormat = PA_FORMAT_DEFAULT;

							if (!MraAvatarsGetFileName(pmraaqAvatarsQueue, pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat, wszFileName)) {
								HANDLE hFile = CreateFile(wszFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
								if (hFile != INVALID_HANDLE_VALUE) {
									DWORD dwWritten = 0;
									bContinue = TRUE;
									nls.dwTimeout = (1000 * db_get_dw(NULL, MRA_AVT_SECT_NAME, "TimeOutReceive", MRA_AVT_DEFAULT_TIMEOUT_RECV));
									nls.hReadConns[0] = hConnection;

									while (bContinue) {
										switch (CallService(MS_NETLIB_SELECT, 0, (LPARAM)&nls)) {
										case SOCKET_ERROR:
										case 0:// Time out
											dwErrorCode = GetLastError();
											ShowFormattedErrorMessage(L"Avatars: error on receive file data", dwErrorCode);
											bContinue = FALSE;
											break;
										case 1:
											dwReceived = Netlib_Recv(hConnection, (LPSTR)&btBuff, SIZEOF(btBuff), 0);
											if (dwReceived == 0 || dwReceived == SOCKET_ERROR) {
												dwErrorCode = GetLastError();
												ShowFormattedErrorMessage(L"Avatars: error on receive file data", dwErrorCode);
												bContinue = FALSE;
											}
											else {
												if (WriteFile(hFile, (LPVOID)&btBuff, dwReceived, &dwReceived, NULL)) {
													dwWritten += dwReceived;
													if (dwWritten >= dwAvatarSizeServer)
														bContinue = FALSE;
												}
												else {
													dwErrorCode = GetLastError();
													ShowFormattedErrorMessage(L"Avatars: cant write file data, error", dwErrorCode);
													bContinue = FALSE;
												}
											}
											break;
										}
									}
									CloseHandle(hFile);
									bFailed = FALSE;
								}
								else {
									dwErrorCode = GetLastError();
									mir_sntprintf(szErrorText, SIZEOF(szErrorText), TranslateT("Avatars: can't open file %s, error"), wszFileName);
									ShowFormattedErrorMessage(szErrorText, dwErrorCode);
								}
							}
						}
						else _CrtDbgBreak();

						if (bUseKeepAliveConn == FALSE || bKeepAlive == FALSE)
							NETLIB_CLOSEHANDLE(hConnection);
					}
				}
			}
		}

		if (bFailed) {
			DeleteFile(wszFileName);
			pai.hContact = pmraaqiAvatarsQueueItem->hContact;
			pai.format = PA_FORMAT_UNKNOWN;
			pai.filename[0] = 0;
			ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_FAILED, (HANDLE)&pai, 0);
		}
		else {
			pai.hContact = pmraaqiAvatarsQueueItem->hContact;
			pai.format = dwAvatarFormat;
			if (db_get_b(NULL, MRA_AVT_SECT_NAME, "ReturnAbsolutePath", MRA_AVT_DEFAULT_RET_ABC_PATH))
				lstrcpyn(pai.filename, wszFileName, SIZEOF(pai.filename));
			else
				PathToRelativeT(wszFileName, pai.filename);

			if (bDefaultAvt) dwAvatarFormat = PA_FORMAT_DEFAULT;
			SetContactAvatarFormat(pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat);
			MraAvatarsSetContactTime(pmraaqiAvatarsQueueItem->hContact, "AvatarLastModifiedTime", &itAvatarLastModifiedTimeServer.stTime);
			// write owner avatar file name to DB
			if (pmraaqiAvatarsQueueItem->hContact == NULL) // proto avatar
				CallService(MS_AV_REPORTMYAVATARCHANGED, (WPARAM)m_szModuleName, 0);

			ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_SUCCESS, (HANDLE)&pai, 0);
		}
		mir_free(pmraaqiAvatarsQueueItem);
	}

	InterlockedDecrement((volatile LONG*)&pmraaqAvatarsQueue->lThreadsRunningCount);
}
예제 #23
0
int CClientSession::DoPutFile( const char* strSrc, const char* strDst, bool bOverwrite )
{
	char buf[MAXPATH+sizeof(CNcpMessage)];
	CNcpMessage* pMsg = (CNcpMessage*)buf;

	if( !IsFileExist( strSrc ) ){
		return E_NOENT;
	}

	//step 1. request passive mode to get the data channel address
	unsigned short dataport = 0;

	int nRet = DoPassive( (short*)&dataport );
	if( FAILED(nRet) )return nRet;

	//step 2. send the put file command.
	pMsg->Init( CM_PUTFILE );
	pMsg->m_nParamRet = bOverwrite;
	strcpy( pMsg->GetData(), strDst );
	pMsg->SetDataSize( strlen(strDst)+1 );

	pMsg->Send( m_sock );

	//wait for the return code and check it
	if( !pMsg->Recv( m_sock, ELEMENTS(buf) ) ){
		return E_BROKEN;		//broken connection
	}

	ASSERT( pMsg->IsAck() );
	if( pMsg->IsFailed() || pMsg->m_nParamRet==S_EXIST ){
		return pMsg->GetRet();
	}

	//step 3. now the server agrees on the file transfer, connect the data channel and send file
	SOCKADDR_IN addr;
	socklen_t nlen = sizeof(SOCKADDR_IN);
	GetPeerName( m_sock, (SOCKADDR*)&addr, &nlen );
	addr.sin_port = htons( dataport );

	SOCKET sockdata;
	//import, must retry the socket initilization a few times. 
	for( int i=0; i<MAXRETRY; i++ ){
		sockdata = Socket( PF_INET, SOCK_STREAM, 0 );
		ASSERT( sockdata!=INVALID_SOCKET );

		if( ::connect( sockdata, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN) )==0 )break;
		closesocket( sockdata );
	}
	if( i>=MAXRETRY )throw new CSockException();

/*	for( int i=0; i<5; i++ ){
		sockdata = Socket( PF_INET, SOCK_STREAM, 0 );
		ASSERT( sockdata!=INVALID_SOCKET );

		struct hostent * phent = gethostbyaddr( (char*)&addr.sin_addr, sizeof(IN_ADDR), AF_INET );
		cdump<<lock<<(int)sockdata<<" connecting data channel at "<<phent->h_name<<"("<<addr.sin_addr.S_un.S_addr<<","<<dataport<<"), "<<endl<<unlock;
		if( ::connect( sockdata, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN) )==0 ){
			break;
		}

		cdump<<lock<<phent->h_name<<" connect failed "<<i<<"\t error:"<<WSAGetLastError()<<endl<<unlock;
		closesocket( sockdata );
	}

	if( i<5 ){
		cdump<<lock<<"connected!"<<endl<<unlock;
	}else{
		throw new CSockException();
	}*/

/*	SOCKET sockdata;
	sockdata = Socket( PF_INET, SOCK_STREAM, 0 );
	ASSERT( sockdata!=INVALID_SOCKET );

	for( int i=0; i<5; i++ ){
		struct hostent * phent = gethostbyaddr( (char*)&addr.sin_addr, sizeof(IN_ADDR), AF_INET );
		cdump<<lock<<(int)sockdata<<" connecting data channel at "<<phent->h_name<<"("<<addr.sin_addr.S_un.S_addr<<","<<dataport<<"), "<<endl<<unlock;
		int nrt = 0;
		if( (nrt=::connect( sockdata, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN) ))==0 ){
			break;
		}
		cdump<<lock<<phent->h_name<<" connect failed "<<i<<"\t error:"<<nrt<<","<<WSAGetLastError()<<endl<<unlock;

		closesocket( sockdata );
		Sleep( 1000*10*(i+1) );

		sockdata = Socket( PF_INET, SOCK_STREAM, 0 );
		ASSERT( sockdata!=INVALID_SOCKET );
	}
	if( i>=5 ){
		struct hostent * phent = gethostbyaddr( (char*)&addr.sin_addr, sizeof(IN_ADDR), AF_INET );
		cdump<<lock<<"connecting data channel at "<<phent->h_name<<"("<<addr.sin_addr.S_un.S_addr<<","<<dataport<<"), "<<endl<<unlock;
		::Connect( sockdata, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN) );
	}
	cdump<<lock<<"connected!"<<endl<<unlock;*/

//	struct hostent * phent = gethostbyaddr( (char*)&addr.sin_addr, sizeof(IN_ADDR), AF_INET );
//	cdump<<lock<<"connecting data channel at "<<phent->h_name<<"("<<addr.sin_addr.S_un.S_addr<<","<<dataport<<"), "<<unlock;
//	::Connect( sockdata, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN) );
//	cdump<<lock<<"connected!"<<endl<<unlock;

	int nLen = SendFileEx( sockdata, strSrc, m_nFileMode );
	closesocket( sockdata );

	//step 4. exchange the error code.
	pMsg->Init( CM_ACK, nLen );
	pMsg->Send( m_sock );

	//wait for the return code and check it
	if( !pMsg->Recv( m_sock, ELEMENTS(buf) ) ){
		return E_BROKEN;		//broken connection
	}

	ASSERT( pMsg->IsAck() );
	return pMsg->GetRet();
}
예제 #24
0
DWORD CFileDownloader::Download( LPCTSTR lpszURL, LPCTSTR lpszFilename, LPCTSTR lpszRefererUrl, LPVOID pUserData, BOOL bUseCache, BOOL bUseProxyConfig )
{
	m_Stopped = FALSE;
	if(!SplitDownloadUrl( lpszURL, m_strHostname, m_strHostPath, m_strHostFilename ))
		return FALSE;
	
	m_pUserData = pUserData;
	m_strDownloadURL = lpszURL;
	m_strDownloadFile = lpszFilename;

	// Check the tmp file 
	m_strDownloadFileTemp = m_strDownloadFile + _T(".tmp");
	m_strDownloadFileInfo = m_strDownloadFile + _T(".nfo");		
	
	// Check if file exists 
	if( bUseCache && IsFileExist(m_strDownloadFile) )
	{
		return TRUE;
	}
	else if(!bUseCache)
	{
		DeleteFile(m_strDownloadFileTemp);
		DeleteFile(m_strDownloadFileInfo);
		DeleteFile(m_strDownloadFile);
	}
	
	CPubConfig::T_ProxySetting proxyconfig;
	CPubConfig pubconfig;
	pubconfig.LoadProxyConfig(proxyconfig);	
	SetProxySetting(proxyconfig);


	INT64 lContentSize = 0;
	INT64 lFileSize = 0;
	if( IsFileExist(m_strDownloadFileTemp) && IsFileExist(m_strDownloadFileInfo) )
	{
		CString strLastModified;
		BOOL notModified = FALSE;
		if( file_get_contents(m_strDownloadFileInfo, strLastModified) )		
		{
			LPCTSTR lpszLengthTag = _T("; length=");
			LPCTSTR pszLen = _tcsstr(strLastModified, lpszLengthTag);
			if(pszLen)
			{
				pszLen+= _tcslen(lpszLengthTag);
				lContentSize = _ttoi64(pszLen);
			}

			// 检查文件是否完全下载完成了 
			lFileSize = file_get_size( m_strDownloadFileTemp );
			if(lFileSize>0 && lFileSize==lContentSize)
			{
				MoveFile(m_strDownloadFileTemp, m_strDownloadFile);
				DeleteFile(m_strDownloadFileInfo);
				return TRUE;
			}

			if( _CheckIfModifiedSince(lpszURL, strLastModified, bUseProxyConfig, notModified) && notModified )
			{
			}
			else
			{
				lFileSize = 0;
			}
		}
	}
	// 如果文件已经过期, 或者文件的信息文件不存在, 都删除旧下载临时文件 
	if(lFileSize==0)
	{
		DeleteFile(m_strDownloadFileTemp);
		DeleteFile(m_strDownloadFileInfo);
	}
	
	// Prepare file 
	_CloseFileHandler();
	m_hFile = CreateFile(m_strDownloadFileTemp, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if( m_hFile==INVALID_HANDLE_VALUE )
		return FALSE;
	SetFilePointer( m_hFile, lFileSize, 0, FILE_BEGIN );
	
	if(m_pBuffer==NULL)
		m_pBuffer = new BYTE[HTTP_BUFFER_SIZE];	
	INT nRetry = HTTP_DEFAULT_RETYR;
	INT nRetried = 0;
	do 
	{
		INT iRet = _DownloadFileFrom(lFileSize, lContentSize, bUseProxyConfig);
		DEBUG_TRACE(_T("FD:_DownloadFileFrom %I64d/%I64d LastError:%d Ret:%d"), lFileSize, lContentSize, GetLastError(), iRet);
		_Cleanup();

		if(iRet>0)
		{
			// 考虑socket 被主动关闭 
			if(lFileSize>=lContentSize)
				break;
			nRetry = HTTP_DEFAULT_RETYR;
		}
		else if(iRet==0)
		{
			--nRetry;
		}
		else if(iRet==-1)
		{
			// 文件长度不匹配! 需要删了文件, 然后重新下载 
			_CloseFileHandler();
			DeleteFile(m_strDownloadFileTemp);
			DeleteFile(m_strDownloadFileInfo);
			lFileSize = lContentSize = 0;
			
			m_hFile = CreateFile(m_strDownloadFileTemp, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			if( m_hFile==INVALID_HANDLE_VALUE )
				break;
			--nRetry;
		}
		else if(iRet==-2)
		{
			// 写入文件失败, 直接返回
			break;
		}
		else
		{
			ATLASSERT(FALSE);
			break;
		}
		++ nRetried;
	} while (!m_Stopped && nRetry>0 && nRetried<HTTP_DEFAULT_MAXRETYR);
	
	_CloseFileHandler();
	BOOL bFileDone = FALSE;
	if(lContentSize==0)
	{
		// 163.com 等页面
		if(lFileSize==0)
		{
			DeleteFile(m_strDownloadFileTemp);
		}
		else if(!m_Stopped)
		{
			bFileDone = TRUE;
		}
	}
	else
	{
		bFileDone = lFileSize>=lContentSize;
	}
	if(bFileDone)
	{
		MoveFile(m_strDownloadFileTemp, m_strDownloadFile);
		DeleteFile(m_strDownloadFileInfo);
	}
	BOOL bRet = PathFileExists(m_strDownloadFile);
	_FireFileDownloaderEvent(bRet ? IFileDownloaderObserver::DOWNLOAD_COMPLETE : IFileDownloaderObserver::DOWNLOAD_ERROR);
	return bRet;
}
예제 #25
0
// 支持version = 1.1 版本
BOOL CCheckRuleXMLParse::LoadNew(const CString &strFilePath, 
							  CheckRuleArray &arrCheckRuleList)
{
	arrCheckRuleList.RemoveAll();

	if (!IsFileExist(strFilePath))
		return FALSE;

	BOOL bResult = TRUE;

	// 初始化
	Init();

	// 打开xml文件
	if (!m_pXMLDocument->OpenXMLForDocument(strFilePath))
		bResult = FALSE;

	// 读取数据
	if (bResult)
	{
		CheckRule checkRule;
		CString strValue, strIndex;
		IBpXMLNode* pRootNode = m_pXMLDocument->GetRootElement();
		pRootNode->GetName(strValue);
		if (strValue.Compare(L"CheckRule") == 0)
		{
			IBpXMLNode *pChildNode = NULL;
			int nNodeCount = pRootNode->GetElementCount(), nAttrCount;
			for (int i = 1; i <= nNodeCount; i++)
			{
				IBpXMLNode *pRuleNode = pRootNode->GetElementChildByIndex(i);
				if (pRuleNode->GetElementCount() >= 3)
				{
					pRuleNode->GetAttributeByName(L"id", strValue);
					checkRule.nID = _wtoi(strValue);
					// 检查类型
					pRuleNode->GetAttributeByName(L"ruletype", strValue);
					checkRule.nRuleType = _wtoi(strValue);
					// 检查描述
					pChildNode = pRuleNode->GetElementChildByIndex(1);
					pChildNode->GetText(checkRule.strRuleDesc);
					DestroyXMLNode(pChildNode);
					// 检查名称
					pChildNode = pRuleNode->GetElementChildByIndex(2);
					pChildNode->GetText(checkRule.strRuleName);
					DestroyXMLNode(pChildNode);
					// 检查内容
					pChildNode = pRuleNode->GetElementChildByIndex(3);
					nAttrCount = pChildNode->GetAttributeCount();
					checkRule.arrRuleContent.SetSize(nAttrCount);
					for (int j = 0; j < nAttrCount; j++)
					{
						strIndex.Format(L"rc%d", j);
						pChildNode->GetAttributeByName(strIndex, strValue);
						checkRule.arrRuleContent.SetAt(j, strValue);
					}
					DestroyXMLNode(pChildNode);

					if (pRuleNode->GetElementCount() >= 4)
					{
						// 检查模型过滤
						pChildNode = pRuleNode->GetElementChildByIndex(4);
						pChildNode->GetText(strValue);
						checkRule.dwMdlFilter = _wtoi(strValue);
						DestroyXMLNode(pChildNode);
					}
					arrCheckRuleList.Add(checkRule);
				}
				DestroyXMLNode(pRuleNode);
			}
		}
		else
		{
			AfxMessageBox(L"XML文件不匹配!");
			bResult = FALSE;
		}
		DestroyXMLNode(pRootNode);
	}

	// 释放资源
	Uninit();
	return bResult;
}