Exemple #1
0
CString CSZCommandLineEx::FormatParamUsage(
    LPCTSTR         lpszParamName,
    CParamUsage&    usage, 
    int             nParamNameWidth,
    int             nValueNameWidth)
{
    assert(0 <= nParamNameWidth && nParamNameWidth <= 80);
    assert(0 <= nValueNameWidth && nValueNameWidth <= 80);


    CString strParamUsage;

    if (nValueNameWidth)
        nValueNameWidth += 3;   // for :<>

    // indent
    int nTruncateLength = 4;
    strParamUsage.AppendChar(_T(' '));
    strParamUsage.AppendChar(_T(' '));
    strParamUsage.AppendChar(_T(' '));
    strParamUsage.AppendChar(_T('-'));

    // param name
    nTruncateLength += nParamNameWidth;
    strParamUsage.Append(lpszParamName);
    for (int i = strParamUsage.GetLength(); i <= nTruncateLength; ++i)
    {
        strParamUsage.AppendChar(_T(' '));
    }
    strParamUsage.Truncate(nTruncateLength);


    // space
    nTruncateLength += 2;
    strParamUsage.AppendChar(_T(' '));
    strParamUsage.AppendChar(_T(' '));


    // param value
    nTruncateLength += nValueNameWidth;
    if (!usage.m_strParamValueName.IsEmpty())
        strParamUsage.AppendFormat(_T(":<%s>"), usage.m_strParamValueName);
    for (int i = strParamUsage.GetLength(); i <= nTruncateLength; ++i)
    {
        strParamUsage.AppendChar(_T(' '));
    }
    strParamUsage.Truncate(nTruncateLength);


    // space
    nTruncateLength += 4;
    strParamUsage.AppendChar(_T(' '));
    strParamUsage.AppendChar(_T(' '));
    strParamUsage.AppendChar(_T(' '));
    strParamUsage.AppendChar(_T(' '));


    // param usage
    strParamUsage.Append(usage.m_strUsage);
    return strParamUsage;
}
Exemple #2
0
bool CServerSocket::ProcessPacket(const BYTE* packet, uint32 size, uint8 opcode)
{
	try
	{
		switch (opcode)
		{
			case OP_SERVERMESSAGE:{
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_ServerMessage\n"));

				CServer* pServer = cur_server ? theApp.serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort()) : NULL;
				CSafeMemFile data(packet, size);
				CString strMessages(data.ReadString(pServer ? pServer->GetUnicodeSupport() : false));

				if (thePrefs.GetDebugServerTCPLevel() > 0){
					UINT uAddData = (UINT)(data.GetLength() - data.GetPosition());
					if (uAddData > 0){
						Debug(_T("*** NOTE: OP_ServerMessage: ***AddData: %u bytes\n"), uAddData);
						DebugHexDump(packet + data.GetPosition(), uAddData);
					}
				}

				// 16.40 servers do not send separate OP_SERVERMESSAGE packets for each line;
				// instead of this they are sending all text lines with one OP_SERVERMESSAGE packet.
				int iPos = 0;
				CString message = strMessages.Tokenize(_T("\r\n"), iPos);
				while (!message.IsEmpty())
				{
					bool bOutputMessage = true;
					if (_tcsnicmp(message, _T("server version"), 14) == 0){
						CString strVer = message.Mid(14);
						strVer.Trim();
						strVer = strVer.Left(64); // truncate string to avoid misuse by servers in showing ads
						if (pServer){
							UINT nVerMaj, nVerMin;
							if (_stscanf(strVer, _T("%u.%u"), &nVerMaj, &nVerMin) == 2)
								strVer.Format(_T("%u.%02u"), nVerMaj, nVerMin);
							pServer->SetVersion(strVer);
							theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
							theApp.emuledlg->serverwnd->UpdateMyInfo();
						}
						if (thePrefs.GetDebugServerTCPLevel() > 0)
							Debug(_T("%s\n"), message);
					}
					else if (_tcsncmp(message, _T("ERROR"), 5) == 0){
						LogError(LOG_STATUSBAR, _T("%s %s (%s:%u) - %s"), 
							GetResString(IDS_ERROR),
							pServer ? pServer->GetListName() : GetResString(IDS_PW_SERVER), 
							cur_server ? cur_server->GetAddress() : _T(""), 
							cur_server ? cur_server->GetPort() : 0, message.Mid(5).Trim(_T(" :")));
						bOutputMessage = false;
					}
					else if (_tcsncmp(message, _T("WARNING"), 7) == 0){
						LogWarning(LOG_STATUSBAR, _T("%s %s (%s:%u) - %s"), 
							GetResString(IDS_WARNING),
							pServer ? pServer->GetListName() : GetResString(IDS_PW_SERVER), 
							cur_server ? cur_server->GetAddress() : _T(""),
							cur_server ? cur_server->GetPort() : 0, message.Mid(7).Trim(_T(" :")));
						bOutputMessage = false;
					}

					if (message.Find(_T("[emDynIP: ")) != -1 && message.Find(_T("]")) != -1 && message.Find(_T("[emDynIP: ")) < message.Find(_T("]"))){
						CString dynip = message.Mid(message.Find(_T("[emDynIP: ")) + 10, message.Find(_T("]")) - (message.Find(_T("[emDynIP: ")) + 10));
						dynip.Trim();
						if (dynip.GetLength() && dynip.GetLength() < 51){
							// Verify that we really received a DN.
							if (pServer && inet_addr(CStringA(dynip)) == INADDR_NONE){
								// Update the dynIP of this server, but do not reset it's IP
								// which we just determined during connecting.
								CString strOldDynIP = pServer->GetDynIP();
								pServer->SetDynIP(dynip);
								// If a dynIP-server changed its address or, if this is the
								// first time we get the dynIP-address for a server which we
								// already have as non-dynIP in our list, we need to remove
								// an already available server with the same 'dynIP:port'.
								if (strOldDynIP.CompareNoCase(pServer->GetDynIP()) != 0)
									theApp.serverlist->RemoveDuplicatesByAddress(pServer);
								if (cur_server)
									cur_server->SetDynIP(dynip);
								theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
								theApp.emuledlg->serverwnd->UpdateMyInfo();
							}
						}
					}

					if (bOutputMessage) {
						if (m_bStartNewMessageLog) {
							m_bStartNewMessageLog = false;
							theApp.emuledlg->AddServerMessageLine(LOG_INFO, _T(""));
							if (cur_server) {
								CString strMsg;
								if (IsObfusicating())
									strMsg.Format(_T("%s: ") + GetResString(IDS_CONNECTEDTOOBFUSCATED) + _T(" (%s:%u)"), CTime::GetCurrentTime().Format(thePrefs.GetDateTimeFormat4Log()), cur_server->GetListName(), cur_server->GetAddress(), cur_server->GetObfuscationPortTCP());
								else
									strMsg.Format(_T("%s: ") + GetResString(IDS_CONNECTEDTO) + _T(" (%s:%u)"), CTime::GetCurrentTime().Format(thePrefs.GetDateTimeFormat4Log()), cur_server->GetListName(), cur_server->GetAddress(), cur_server->GetPort());
								theApp.emuledlg->AddServerMessageLine(LOG_SUCCESS, strMsg);
							}
						}
						theApp.emuledlg->AddServerMessageLine(LOG_INFO, message);
					}

					message = strMessages.Tokenize(_T("\r\n"), iPos);
				}
				break;
			}
			case OP_IDCHANGE:{
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_IDChange\n"));
				if (size < sizeof(LoginAnswer_Struct)){
					throw GetResString(IDS_ERR_BADSERVERREPLY);
				}
				LoginAnswer_Struct* la = (LoginAnswer_Struct*)packet;

				// save TCP flags in 'cur_server'
				CServer* pServer = NULL;
				ASSERT( cur_server );
				if (cur_server){
					if (size >= sizeof(LoginAnswer_Struct)+4){
						DWORD dwFlags = *((uint32*)(packet + sizeof(LoginAnswer_Struct)));
						if (thePrefs.GetDebugServerTCPLevel() > 0){
							CString strInfo;
							strInfo.AppendFormat(_T("  TCP Flags=0x%08x"), dwFlags);
							const DWORD dwKnownBits = SRV_TCPFLG_COMPRESSION | SRV_TCPFLG_NEWTAGS | SRV_TCPFLG_UNICODE | SRV_TCPFLG_RELATEDSEARCH | SRV_TCPFLG_TYPETAGINTEGER | SRV_TCPFLG_LARGEFILES | SRV_TCPFLG_TCPOBFUSCATION;
							if (dwFlags & ~dwKnownBits)
								strInfo.AppendFormat(_T("  ***UnkBits=0x%08x"), dwFlags & ~dwKnownBits);
							if (dwFlags & SRV_TCPFLG_COMPRESSION)
								strInfo.AppendFormat(_T("  Compression=1"));
							if (dwFlags & SRV_TCPFLG_NEWTAGS)
								strInfo.AppendFormat(_T("  NewTags=1"));
							if (dwFlags & SRV_TCPFLG_UNICODE)
								strInfo.AppendFormat(_T("  Unicode=1"));
							if (dwFlags & SRV_TCPFLG_RELATEDSEARCH)
								strInfo.AppendFormat(_T("  RelatedSearch=1"));
							if (dwFlags & SRV_TCPFLG_TYPETAGINTEGER)
								strInfo.AppendFormat(_T("  IntTypeTags=1"));
							if (dwFlags & SRV_TCPFLG_LARGEFILES)
								strInfo.AppendFormat(_T("  LargeFiles=1"));
							if (dwFlags & SRV_TCPFLG_TCPOBFUSCATION)
								strInfo.AppendFormat(_T("  TCP_Obfscation=1"));
							Debug(_T("%s\n"), strInfo);
						}
						cur_server->SetTCPFlags(dwFlags);
					}
					else
						cur_server->SetTCPFlags(0);

					// copy TCP flags into the server in the server list
					pServer = theApp.serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort());
					if (pServer)
						pServer->SetTCPFlags(cur_server->GetTCPFlags());
				}

				uint32 dwServerReportedIP = 0;
				uint32 dwObfuscationTCPPort = 0;
				if (size >= 20){
					dwServerReportedIP = *((uint32*)(packet + 12));
					if (::IsLowID(dwServerReportedIP)){
						ASSERT( false );
						dwServerReportedIP = 0;
					}
					ASSERT( dwServerReportedIP == la->clientid || ::IsLowID(la->clientid) );
					dwObfuscationTCPPort = *((uint32*)(packet + 16));
					if (cur_server != NULL && dwObfuscationTCPPort != 0)
						cur_server->SetObfuscationPortTCP((uint16)dwObfuscationTCPPort);
					if (pServer != NULL && dwObfuscationTCPPort != 0)
						pServer->SetObfuscationPortTCP((uint16)dwObfuscationTCPPort);

				}

				//Xman
				// Maella -Activate Smart Low ID check-
				/*
				if (la->clientid == 0)
				{
					uint8 state = thePrefs.GetSmartIdState();
					if ( state > 0 )
					{
						if (state == 1)
							theApp.emuledlg->RefreshUPnP(false); // refresh the UPnP mappings once
						state++;
						if( state > 2 )
							thePrefs.SetSmartIdState(0);
						else
							thePrefs.SetSmartIdState(state);
					}
					break;
				}
				if( thePrefs.GetSmartIdCheck() ){
					if (!IsLowID(la->clientid))
						thePrefs.SetSmartIdState(1);
					else{
						uint8 state = thePrefs.GetSmartIdState();
						if ( state > 0 )
						{
							if (state == 1)
								theApp.emuledlg->RefreshUPnP(false); // refresh the UPnP mappings once
							state++;
							if( state > 2 )
								thePrefs.SetSmartIdState(0);
							else
								thePrefs.SetSmartIdState(state);

							if (!m_bManualSingleConnect)
								break; // if this is a connect to any/multiple server connection try, disconnect and try another one
						}
					}
				}
				*/
				if(la->clientid == 0){
					// Reset attempts counter
					thePrefs.SetSmartIdState(0);
				}
				else if(la->clientid >= 16777216){
					// High ID => reset attempts counter
					thePrefs.SetSmartIdState(0);
				}
				else if(thePrefs.GetSmartIdCheck() == true){
					// Low ID => Check and increment attempts counter
					uint8 attempts = thePrefs.GetSmartIdState();
					if(attempts < 3){
						//zz_fly :: not needed, rebind upnp on ipchange :: start
						//Official UPNP
						/*
						if (!thePrefs.m_bUseACATUPnPCurrent && (attempts == 1))
							theApp.emuledlg->RefreshUPnP(false); // refresh the UPnP mappings once
						*/
						//zz_fly :: end
						SetConnectionState(CS_ERROR);
						thePrefs.SetSmartIdState(++attempts);
						AddLogLine(true, _T("LowID -- Trying Again (attempts %i)"), attempts);
						break; // Retries
					}
					else if (!m_bManualSingleConnect)
						break; // if this is a connect to any/multiple server connection try, disconnect and try another one
				}
				//Xman end
				
				// we need to know our client's HighID when sending our shared files (done indirectly on SetConnectionState)
				serverconnect->clientid = la->clientid;

				if (connectionstate != CS_CONNECTED) {
					SetConnectionState(CS_CONNECTED);
					theApp.OnlineSig();       // Added By Bouc7 
				}
				serverconnect->SetClientID(la->clientid);
				if (::IsLowID(la->clientid) && dwServerReportedIP != 0)
					theApp.SetPublicIP(dwServerReportedIP);
				AddLogLine(false, GetResString(IDS_NEWCLIENTID), la->clientid);

				//Xman -Reask sources after IP change- v4
				if(serverconnect->GetClientID() != 0 && theApp.last_valid_ip != 0
				   && serverconnect->GetClientID() != theApp.last_valid_ip 
				   && serverconnect->GetClientID() != theApp.last_valid_serverid)
				{
					//remark: this code doesn't trigger when changing low->hidh-ID and we already had
					//a session with this HighID-IP. This is because we don't know when this last lowID-session was.
					//but there is no need to trigger when changing low to high-id but keeping the IP, we can'tt loose the waiting-position!

					{
						// Public IP has been changed, it's necessary to inform all sources about it
						// All sources would be informed during their next session refresh (with TCP)
						// about the new IP.
						// ==> Quick start [TPT] - Max
						if(thePrefs.GetQuickStart() && thePrefs.GetQuickStartAfterIPChange())
						{
							theApp.downloadqueue->quickflag = 0;
							theApp.downloadqueue->quickflags = 0;
						}
						// <== Quick start [TPT] - Max
						if(GetTickCount() - theApp.last_ip_change > FILEREASKTIME + 60000){
							theApp.clientlist->TrigReaskForDownload(true);
							theApp.last_ip_change=::GetTickCount();
							theApp.m_bneedpublicIP=false;
							AddLogLine(false, _T("Change from %u (%s ID) to %u (%s ID) detected%s"), 
								theApp.last_valid_serverid,
								(theApp.last_valid_serverid < 16777216) ? _T("low") : _T("high"),
								serverconnect->GetClientID(),
								(serverconnect->GetClientID() < 16777216)  ? _T("low") : _T("high"),
								_T(", all sources will be reasked immediately"));
						}
						else {
							theApp.clientlist->TrigReaskForDownload(false);
							theApp.last_ip_change=::GetTickCount();
							theApp.m_bneedpublicIP=false;
							AddLogLine(false, _T("Change from %u (%s ID) to %u (%s ID) detected%s"), 
								theApp.last_valid_serverid,
								(theApp.last_valid_serverid < 16777216) ? _T("low") : _T("high"),
								serverconnect->GetClientID(),
								(serverconnect->GetClientID() < 16777216)  ? _T("low") : _T("high"),
								_T(", all sources will be reasked within the next 10 minutes"));
						}
						// ==> UPnP support [MoNKi] - leuk_he
						/*
						// official UPNP
						theApp.emuledlg->RefreshUPnP(false); // refresh the UPnP mappings once
						// official UPNP
						*/
						theApp.RebindUPnP();
						// <== UPnP support [MoNKi] - leuk_he
					}
				}
				if(serverconnect->GetClientID() != 0 && theApp.last_ip_change==0)
					theApp.last_ip_change=::GetTickCount();
				if(serverconnect->GetClientID() != 0 && serverconnect->GetClientID() != theApp.last_valid_serverid){
					// Keep track of a change of the global IP
					theApp.last_valid_serverid = serverconnect->GetClientID();
				}
				theApp.last_valid_ip=theApp.GetPublicIP(true); //can also be 0

				theApp.last_traffic_reception=::GetTickCount();
				theApp.internetmaybedown=false; //we have to reopen here if we are using server only
				// Xman end

				theApp.downloadqueue->ResetLocalServerRequests();
				break;
			}
			case OP_SEARCHRESULT:{
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_SearchResult\n"));
				CServer* cur_srv = (serverconnect) ? serverconnect->GetCurrentServer() : NULL;
				CServer* pServer = cur_srv ? theApp.serverlist->GetServerByAddress(cur_srv->GetAddress(), cur_srv->GetPort()) : NULL;
				(void)pServer;
				bool bMoreResultsAvailable;
				UINT uSearchResults = theApp.searchlist->ProcessSearchAnswer(packet, size, true/*pServer ? pServer->GetUnicodeSupport() : false*/, cur_srv ? cur_srv->GetIP() : 0, cur_srv ? cur_srv->GetPort() : (uint16)0, &bMoreResultsAvailable);
				theApp.emuledlg->searchwnd->LocalEd2kSearchEnd(uSearchResults, bMoreResultsAvailable);
				break;
			}
			case OP_FOUNDSOURCES_OBFU:
			case OP_FOUNDSOURCES:{
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_FoundSources%s; Sources=%u  %s\n"), (opcode == OP_FOUNDSOURCES_OBFU) ? _T("_OBFU") : _T(""), (UINT)packet[16], DbgGetFileInfo(packet));

				ASSERT( cur_server );
				if (cur_server)
				{
				    CSafeMemFile sources(packet, size);
					uchar fileid[16];
					sources.ReadHash16(fileid);
					if (CPartFile* file = theApp.downloadqueue->GetFileByID(fileid))
						file->AddSources(&sources,cur_server->GetIP(), cur_server->GetPort(), (opcode == OP_FOUNDSOURCES_OBFU));
				}
				break;
			}
			case OP_SERVERSTATUS:{
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_ServerStatus\n"));
				// FIXME some statuspackets have a different size -> why? structur?
				if (size < 8)
					break;//throw "Invalid status packet";
				uint32 cur_user = PeekUInt32(packet);
				uint32 cur_files = PeekUInt32(packet+4);
				CServer* pServer = cur_server ? theApp.serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort()) : NULL;
				if (pServer){
					pServer->SetUserCount(cur_user);
					pServer->SetFileCount(cur_files);
					theApp.emuledlg->ShowUserCount();
					theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
					theApp.emuledlg->serverwnd->UpdateMyInfo();
				}
				if (thePrefs.GetDebugServerTCPLevel() > 0){
					if (size > 8){
						Debug(_T("*** NOTE: OP_ServerStatus: ***AddData: %u bytes\n"), size - 8);
						DebugHexDump(packet + 8, size - 8);
					}
				}
				break;
			}
			case OP_SERVERIDENT:{
				// OP_SERVERIDENT - this is sent by the server only if we send a OP_GETSERVERLIST
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_ServerIdent\n"));
				if (size<16+4+2+4){
					if (thePrefs.GetVerbose())
						DebugLogError(_T("%s"), GetResString(IDS_ERR_KNOWNSERVERINFOREC));
					break;// throw "Invalid server info received"; 
				} 

				CServer* pServer = cur_server ? theApp.serverlist->GetServerByAddress(cur_server->GetAddress(),cur_server->GetPort()) : NULL;
				CString strInfo;
				CSafeMemFile data(packet, size);
				
				uint8 aucHash[16];
				data.ReadHash16(aucHash);
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					strInfo.AppendFormat(_T("Hash=%s (%s)"), md4str(aucHash), DbgGetHashTypeString(aucHash));
				uint32 nServerIP = data.ReadUInt32();
				uint16 nServerPort = data.ReadUInt16();
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					strInfo.AppendFormat(_T("  IP=%s:%u"), ipstr(nServerIP), nServerPort);
				UINT nTags = data.ReadUInt32();
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					strInfo.AppendFormat(_T("  Tags=%u"), nTags);

				CString strName;
				CString strDescription;
				for (UINT i = 0; i < nTags; i++){
					CTag tag(&data, pServer ? pServer->GetUnicodeSupport() : false);
					if (tag.GetNameID() == ST_SERVERNAME){
						if (tag.IsStr()){
							strName = tag.GetStr();
							if (thePrefs.GetDebugServerTCPLevel() > 0)
								strInfo.AppendFormat(_T("  Name=%s"), strName);
						}
					}
					else if (tag.GetNameID() == ST_DESCRIPTION){
						if (tag.IsStr()){
							strDescription = tag.GetStr();
							if (thePrefs.GetDebugServerTCPLevel() > 0)
								strInfo.AppendFormat(_T("  Desc=%s"), strDescription);
						}
					}
					else if (thePrefs.GetDebugServerTCPLevel() > 0)
						strInfo.AppendFormat(_T("  ***UnkTag: 0x%02x=%u"), tag.GetNameID(), tag.GetInt());
				}
				if (thePrefs.GetDebugServerTCPLevel() > 0){
					strInfo += _T('\n');
					Debug(_T("%s"), strInfo);

					UINT uAddData = (UINT)(data.GetLength() - data.GetPosition());
					if (uAddData > 0){
						Debug(_T("*** NOTE: OP_ServerIdent: ***AddData: %u bytes\n"), uAddData);
						DebugHexDump(packet + data.GetPosition(), uAddData);
					}
				}

				if (pServer){
					pServer->SetListName(strName);
					pServer->SetDescription(strDescription);
					if (((uint32*)aucHash)[0] == 0x2A2A2A2A){
						const CString& rstrVersion = pServer->GetVersion();
						if (!rstrVersion.IsEmpty())
							pServer->SetVersion(_T("eFarm ") + rstrVersion);
						else
							pServer->SetVersion(_T("eFarm"));
					}
					theApp.emuledlg->ShowConnectionState(); 
					theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer); 
				}
				break;
			} 
			// tecxx 1609 2002 - add server's serverlist to own serverlist
			case OP_SERVERLIST:{
				if (!thePrefs.GetAddServersFromServer())
					break;
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_ServerList\n"));
				try{
					CSafeMemFile servers(packet, size);
					UINT count = servers.ReadUInt8();
					// check if packet is valid
					if (1 + count*(4+2) > size)
						count = 0;
					int addcount = 0;
					while(count)
					{
						uint32 ip = servers.ReadUInt32();
						uint16 port = servers.ReadUInt16();
						CServer* srv = new CServer(port, ipstr(ip));
						srv->SetListName(srv->GetFullIP());
						srv->SetPreference(SRV_PR_LOW);
						if (!theApp.emuledlg->serverwnd->serverlistctrl.AddServer(srv, true))
							delete srv;
						else
							addcount++;
						count--;
					}
					if (addcount)
						AddLogLine(false, GetResString(IDS_NEWSERVERS), addcount);
					if (thePrefs.GetDebugServerTCPLevel() > 0){
						UINT uAddData = (UINT)(servers.GetLength() - servers.GetPosition());
						if (uAddData > 0){
							Debug(_T("*** NOTE: OP_ServerList: ***AddData: %u bytes\n"), uAddData);
							DebugHexDump(packet + servers.GetPosition(), uAddData);
						}
					}
				}
				catch(CFileException* error){
					if (thePrefs.GetVerbose())
						DebugLogError(_T("%s"), GetResString(IDS_ERR_BADSERVERLISTRECEIVED));
					error->Delete();
				}
				break;
			}
			case OP_CALLBACKREQUESTED:{
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_CallbackRequested: %s\n"), (size >= 23) ? _T("With Cryptflag and Userhash") : _T("Without Cryptflag and Userhash"));
				if (size >= 6)
				{
					uint32 dwIP = PeekUInt32(packet);

					if (theApp.ipfilter->IsFiltered(dwIP)){
						theStats.filteredclients++;
						if (thePrefs.GetLogFilteredIPs())
							AddDebugLogLine(false, _T("Ignored callback request (IP=%s) - IP filter (%s)"), ipstr(dwIP), theApp.ipfilter->GetLastHit());
						break;
					}

					if (theApp.clientlist->IsBannedClient(dwIP)){
						if (thePrefs.GetLogBannedClients()){
							CUpDownClient* pClient = theApp.clientlist->FindClientByIP(dwIP);
							//Xman Code Fix
							/*
							AddDebugLogLine(false, _T("Ignored callback request from banned client %s; %s"), ipstr(dwIP), pClient->DbgGetClientInfo());
							*/
							AddDebugLogLine(false, _T("Ignored callback request from banned client %s; %s"), ipstr(dwIP), pClient ? pClient->DbgGetClientInfo() : _T("unknown"));
							//Xman end
						}
						break;
					}

					uint16 nPort = PeekUInt16(packet+4);
					uint8 byCryptOptions = 0;
					uchar achUserHash[16];
					if (size >= 23){
						byCryptOptions = packet[6];
						md4cpy(achUserHash, packet + 7);
					}
					
					CUpDownClient* client = theApp.clientlist->FindClientByIP(dwIP,nPort);
					if (client == NULL)
					{
						client = new CUpDownClient(0,nPort,dwIP,0,0,true);
						//Xman Code Improvement don't search new generated clients in lists
						/*
						theApp.clientlist->AddClient(client);
						*/
						theApp.clientlist->AddClient(client, true);
						//Xman end
					}
					if (size >= 23 && client->HasValidHash()){
						if (md4cmp(client->GetUserHash(), achUserHash) != 0){
							DebugLogError(_T("Reported Userhash from OP_CALLBACKREQUESTED differs with our stored hash"));
							// disable crypt support since we dont know which hash is true
							client->SetCryptLayerRequest(false);
							client->SetCryptLayerSupport(false);
							client->SetCryptLayerRequires(false);
						}
						else{
							client->SetConnectOptions(byCryptOptions, true, false);
							client->SetDirectUDPCallbackSupport(false);
						}
					}
					else if (size >= 23){
						client->SetUserHash(achUserHash);
						client->SetCryptLayerSupport((byCryptOptions & 0x01) != 0);
						client->SetCryptLayerRequest((byCryptOptions & 0x02) != 0);
						client->SetCryptLayerRequires((byCryptOptions & 0x04) != 0);
						client->SetDirectUDPCallbackSupport(false);
					}
					client->TryToConnect();
				}
				break;
			}
			case OP_CALLBACK_FAIL:{
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_Callback_Fail %s\n"), DbgGetHexDump(packet, size));
				break;
			}
			case OP_REJECT:{
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("ServerMsg - OP_Reject %s\n"), DbgGetHexDump(packet, size));
				// this could happen if we send a command with the wrong protocol (e.g. sending a compressed packet to
				// a server which does not support that protocol).
				if (thePrefs.GetVerbose())
					DebugLogError(_T("Server rejected last command"));
				break;
			}
			default:
				if (thePrefs.GetDebugServerTCPLevel() > 0)
					Debug(_T("***NOTE: ServerMsg - Unknown message; opcode=0x%02x  %s\n"), opcode, DbgGetHexDump(packet, size));
				;
		}

		return true;
	}
	catch(CFileException* error)
	{
		if (thePrefs.GetVerbose())
		{
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			error->m_strFileName = _T("server packet");
			error->GetErrorMessage(szError, ARRSIZE(szError));
			ProcessPacketError(size, opcode, szError);
		}
		ASSERT(0);
		error->Delete();
		if (opcode==OP_SEARCHRESULT || opcode==OP_FOUNDSOURCES)
			return true;
	}
	catch(CMemoryException* error)
	{
		ProcessPacketError(size, opcode, _T("CMemoryException"));
		ASSERT(0);
		error->Delete();
		if (opcode==OP_SEARCHRESULT || opcode==OP_FOUNDSOURCES)
			return true;
	}
	catch(CString error)
	{
		ProcessPacketError(size, opcode, error);
		ASSERT(0);
	}
#ifndef _DEBUG
	catch(...)
	{
		ProcessPacketError(size, opcode, _T("Unknown exception"));
		ASSERT(0);
	}
#endif

	SetConnectionState(CS_DISCONNECTED);
	return false;
}
void AccountDlg::OnBnClickedOk()
{
	CEdit* edit;
	CString str;
	CComboBox *combobox;
	int i;

	edit = (CEdit*)GetDlgItem(IDC_EDIT_SERVER);
	edit->GetWindowText(str);
	m_Account.server=str.Trim();

	edit = (CEdit*)GetDlgItem(IDC_EDIT_PROXY);
	edit->GetWindowText(str);
	m_Account.proxy=str.Trim();

	edit = (CEdit*)GetDlgItem(IDC_EDIT_DOMAIN);
	edit->GetWindowText(str);
	m_Account.domain=str.Trim();

	edit = (CEdit*)GetDlgItem(IDC_EDIT_AUTHID);
	edit->GetWindowText(str);
	m_Account.authID=str.Trim();

	edit = (CEdit*)GetDlgItem(IDC_EDIT_USERNAME);
	edit->GetWindowText(str);
	m_Account.username=str.Trim();

	edit = (CEdit*)GetDlgItem(IDC_EDIT_PASSWORD);
	edit->GetWindowText(str);
	m_Account.password=str.Trim();

	edit = (CEdit*)GetDlgItem(IDC_EDIT_DISPLAYNAME);
	edit->GetWindowText(str);
	m_Account.displayName=str.Trim();

	combobox= (CComboBox*)GetDlgItem(IDC_TRANSPORT);
	i = combobox->GetCurSel();
	switch (i) {
		case 1:
			m_Account.transport=_T("udp");
			break;
		case 2:
			m_Account.transport=_T("tcp");
			break;
		case 3:
			m_Account.transport=_T("tls");
			break;
		default:
			m_Account.transport=_T("");
	}

	edit = (CEdit*)GetDlgItem(IDC_STUN);
	edit->GetWindowText(str);
	m_Account.stun=str.Trim();

	m_Account.rememberPassword = 1;

	combobox= (CComboBox*)GetDlgItem(IDC_SRTP);
	i = combobox->GetCurSel();
	switch (i) {
		case 1:
			m_Account.srtp=_T("optional");
			break;
		case 2:
			m_Account.srtp=_T("mandatory");
			break;
		default:
			m_Account.srtp=_T("");
	}

	m_Account.publish = ((CButton*)GetDlgItem(IDC_PUBLISH))->GetCheck();

	m_Account.ice = ((CButton*)GetDlgItem(IDC_ICE))->GetCheck();

	m_Account.allowRewrite = ((CButton*)GetDlgItem(IDC_REWRITE))->GetCheck();

	combobox= (CComboBox*)GetDlgItem(IDC_PUBLIC_ADDR);
	i = combobox->GetCurSel();
	combobox->GetWindowText(m_Account.publicAddr);
	if (m_Account.publicAddr==Translate(_T("Auto")))
	{
		m_Account.publicAddr = _T("");
	}

	if (
		m_Account.domain.IsEmpty() ||
		m_Account.username.IsEmpty()) {
		CString str;
		str.Append(Translate(_T("Please fill out at least the required fields marked with *.")));
		str.AppendFormat(_T(" %s"),Translate(_T("Ask your SIP provider how to configure the account correctly.")));
		AfxMessageBox(str);
		return;
	}

	this->ShowWindow(SW_HIDE);

	if (!accountId) {
		Account dummy;
		int i = 1;
		while (true) {
			if (!accountSettings.AccountLoad(i,&dummy)) {
				break;
			}
			i++;
		}
		accountId = i;
	}

	accountSettings.AccountSave(accountId,&m_Account);
	
	if (accountSettings.accountId) {
		mainDlg->PJAccountDelete();
	}

	accountSettings.accountId = accountId;
	accountSettings.AccountLoad(accountSettings.accountId,&accountSettings.account);
	accountSettings.SettingsSave();
	mainDlg->PJAccountAdd();
	OnClose();
}
Exemple #4
0
BOOL CPPageYoutube::OnInitDialog()
{
	__super::OnInitDialog();

	SetHandCursor(m_hWnd, IDC_COMBO1);

	AppSettings& s = AfxGetAppSettings();

	m_iYoutubeFormatCtrl.Clear();

	for (size_t i = 0; i < _countof(youtubeProfiles); i++) {
		CString fmt;
		switch (youtubeProfiles[i].type) {
		case y_mp4:
			fmt = L"MP4";
			break;
		case y_webm:
			fmt = L"WebM";
			break;
		case y_flv:
			fmt = L"FLV";
			break;
		case y_3gp:
			fmt = L"3GP";
			break;
#if ENABLE_YOUTUBE_3D
		case y_3d_mp4:
			fmt = L"3D MP4";
			break;
		case y_3d_webm:
			fmt = L"3D WebM";
			break;
#endif
#if ENABLE_YOUTUBE_DASH
		case y_dash_mp4_video:
			fmt = L"DASH MP4";
			break;
		case y_dash_webm_video:
			fmt = L"DASH WebM";
			break;
#endif
		default:
			continue;
		}
		fmt.AppendFormat(_T("@%dp"), youtubeProfiles[i].quality);

		m_iYoutubeFormatCtrl.AddString(fmt);
		m_iYoutubeFormatCtrl.SetItemData(i, youtubeProfiles[i].iTag);
	}

	int j = 0;
	for (j = 0; j < m_iYoutubeFormatCtrl.GetCount(); j++) {
		if (m_iYoutubeFormatCtrl.GetItemData(j) == s.iYoutubeTag) {
			m_iYoutubeFormatCtrl.SetCurSel(j);
			break;
		}
	}
	if (j >= m_iYoutubeFormatCtrl.GetCount()) {
		m_iYoutubeFormatCtrl.SetCurSel(0);
	}

	m_chkYoutubeLoadPlaylist.SetCheck(s.bYoutubeLoadPlaylist);

	m_nPercentMemoryCtrl.SetRange(1, 100);
	m_nMbMemoryCtrl.SetRange(1, 128);

	m_iYoutubeSourceType	= s.iYoutubeSource ? 1 : 0;
	m_iYoutubeMemoryType	= s.iYoutubeMemoryType ? 1 : 0;
	m_iYoutubePercentMemory	= s.iYoutubePercentMemory;
	m_iYoutubeMbMemory		= s.iYoutubeMbMemory;

	UpdateData(FALSE);

	UpdateMemoryCtrl();

	return TRUE;
}
void CServerListCtrl::RefreshServer(const CServer* server)
{
	if (!server || !theApp.emuledlg->IsRunning())
		return;

	LVFINDINFO find;
	find.flags = LVFI_PARAM;
	find.lParam = (LPARAM)server;
	int itemnr = FindItem(&find);
	if (itemnr == -1)
		return;

	CString temp;
	temp.Format(_T("%s : %i"), server->GetAddress(), server->GetPort());
	SetItemText(itemnr, 1, temp);
	SetItemText(itemnr, 0, server->GetListName());
	SetItemText(itemnr, 2, server->GetDescription());

	// Ping
	if (server->GetPing()) {
		temp.Format(_T("%i"), server->GetPing());
		SetItemText(itemnr, 3, temp);
	}
	else
		SetItemText(itemnr, 3, _T(""));

	// Users
	if (server->GetUsers())
		SetItemText(itemnr, 4, CastItoIShort(server->GetUsers()));
	else
		SetItemText(itemnr, 4, _T(""));

	// Max Users
	if (server->GetMaxUsers())
		SetItemText(itemnr, 5, CastItoIShort(server->GetMaxUsers()));
	else
		SetItemText(itemnr, 5, _T(""));

	// Files
	if (server->GetFiles())
		SetItemText(itemnr, 6, CastItoIShort(server->GetFiles()));
	else
		SetItemText(itemnr, 6, _T(""));

	switch (server->GetPreference()) {
		case SRV_PR_LOW:
			SetItemText(itemnr, 7, GetResString(IDS_PRIOLOW));
			break;
		case SRV_PR_NORMAL:
			SetItemText(itemnr, 7, GetResString(IDS_PRIONORMAL));
			break;
		case SRV_PR_HIGH:
			SetItemText(itemnr, 7, GetResString(IDS_PRIOHIGH));
			break;
		default:
			SetItemText(itemnr, 7, GetResString(IDS_PRIONOPREF));
	}
	
	// Failed Count
	temp.Format(_T("%i"), server->GetFailedCount());
	SetItemText(itemnr, 8, temp);

	// Static server
	if (server->IsStaticMember())
		SetItemText(itemnr, 9, GetResString(IDS_YES)); 
	else
		SetItemText(itemnr, 9, GetResString(IDS_NO));

	// Soft Files
	if (server->GetSoftFiles())
		SetItemText(itemnr, 10, CastItoIShort(server->GetSoftFiles()));
	else
		SetItemText(itemnr, 10, _T(""));

	// Hard Files
	if (server->GetHardFiles())
		SetItemText(itemnr, 11, CastItoIShort(server->GetHardFiles()));
	else
		SetItemText(itemnr, 11, _T(""));

	temp = server->GetVersion();
	if (thePrefs.GetDebugServerUDPLevel() > 0) {
		if (server->GetUDPFlags() != 0) {
			if (!temp.IsEmpty())
				temp += _T("; ");
			temp.AppendFormat(_T("ExtUDP=%x"), server->GetUDPFlags());
		}
	}
	if (thePrefs.GetDebugServerTCPLevel() > 0) {
		if (server->GetTCPFlags() != 0) {
			if (!temp.IsEmpty())
				temp += _T("; ");
			temp.AppendFormat(_T("ExtTCP=%x"), server->GetTCPFlags());
		}
	}
	SetItemText(itemnr, 12, temp);

	// LowID Users
	if (server->GetLowIDUsers())
		SetItemText(itemnr, 13, CastItoIShort(server->GetLowIDUsers()));
	else
		SetItemText(itemnr, 13, _T(""));

	// Obfuscation
	if (server->SupportsObfuscationTCP() && server->GetObfuscationPortTCP() != 0)
		SetItemText(itemnr, 14, GetResString(IDS_YES));
	else
		SetItemText(itemnr, 14, GetResString(IDS_NO));
}
Exemple #6
0
int CProgStatusBar::ShowProgressCtrl(){
	CPostMsg postmsg;
	if (!theApp.m_UimsgQueue.pop(postmsg))
	{
		return 1;
	}
	
	uistruct::BLOCKCHANGED_t pBlockchanged; 
	string strTemp = postmsg.GetData();
	pBlockchanged.JsonToStruct(strTemp.c_str());
	LogPrint("CProgStatusBar", "MSG_USER_UP_PROGRESS WM_CONNECTNET 更新进度条消息:%s\n",strTemp.c_str());
	if (pBlockchanged.tips <= 0)
	{
		return 1;
	}

	//// blocktip高度
	theApp.blocktipheight = pBlockchanged.tips ;
	if (!m_bProgressType)
	{
		string strTemp = "";
		strTemp = strprintf("%s%s",netStr , UiFun::UI_LoadString("PROGSTATUS_MODULE"  , "PROGSTATUS_NETWORK_SYNING",theApp.gsLanguage ));
		m_strNeting.SetWindowText(strTemp.c_str());
		m_strNeting.ShowWindow(SW_HIDE);
		m_strNeting.ShowWindow(SW_SHOW);

		m_progress.SetRange32( 0 , 100); 
		int  setpos =(int)((pBlockchanged.high*1.0/pBlockchanged.tips)*100) ;
		setpos = setpos>100?100:setpos;
		//设置进度条的值
		m_progress.SetPos(setpos);
		CString strText;
		strText.AppendFormat("%s ~%d", UiFun::UI_LoadString("PROGSTATUS_MODULE"  , "PROGSTATUS_SURPLUS",theApp.gsLanguage ) , pBlockchanged.tips-pBlockchanged.high);
		strText.AppendFormat(" %s",UiFun::UI_LoadString("PROGSTATUS_MODULE"  , "PROGSTATUS_SYNLOCAL",theApp.gsLanguage ));
		m_progress.SetDefinedStr(strText);
		m_bProgressType = TRUE;
		m_nSigIndex =pBlockchanged.connections>3?3:pBlockchanged.connections;

		m_connectCount = pBlockchanged.connections;

		if (pBlockchanged.tips==pBlockchanged.high)
		{
			theApp.IsSyncAppTx = TRUE;             /// 同步app交易
		}

		if ((pBlockchanged.tips-pBlockchanged.high)<10 && !m_walletui)
		{
			TRACE("ok:%s\r\n","OnShowProgressCtrl");
			//// 发送钱包同步完毕
			CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET);
			theApp.m_MsgQueue.pushFront(postblockmsg); 
			LoadGifing(false);
			m_walletui = true;
			theApp.IsSyncBlock = true;
		}
		Invalidate(); 
		//InvalidateRect(m_bmpsig);
		//		return 1;
	}

	m_nSigIndex = pBlockchanged.connections>3?3:pBlockchanged.connections;
	int  setpos =(int) ((pBlockchanged.high*1.0/pBlockchanged.tips)*100) ;
	setpos = setpos>100?100:setpos;
	//设置进度条的值
	m_progress.SetPos(setpos);
	CString strText;
	strText.AppendFormat("%s ~%d", UiFun::UI_LoadString("PROGSTATUS_MODULE"  , "PROGSTATUS_SURPLUS",theApp.gsLanguage ) , pBlockchanged.tips-pBlockchanged.high);
	strText.AppendFormat(" %s",UiFun::UI_LoadString("PROGSTATUS_MODULE"  , "PROGSTATUS_SYNLOCAL",theApp.gsLanguage ));
	m_progress.SetDefinedStr(strText);
	m_progress.Invalidate();

	if (pBlockchanged.tips==pBlockchanged.high)
	{
		theApp.IsSyncAppTx = TRUE;             /// 同步app交易
	}
	if ((pBlockchanged.tips-pBlockchanged.high)<10&& !m_walletui)
	{
		TRACE("ok:%s\r\n","OnShowProgressCtrl");
		//// 发送钱包同步完毕
		CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET);
		theApp.m_MsgQueue.pushFront(postblockmsg); 
		LoadGifing(false);
		m_walletui = true;
		theApp.IsSyncBlock = true;
	}
	if ( m_walletui && !m_prosshiden) {
		string strTemp = "";
		strTemp =strprintf("%s%s",netStr , UiFun::UI_LoadString("PROGSTATUS_MODULE"  , "PROGSTATUS_NET",theApp.gsLanguage ) );
		m_strNeting.SetWindowText(strTemp.c_str()) ;
		m_strNeting.ShowWindow(SW_HIDE);
		m_strNeting.ShowWindow(SW_SHOW);

		m_progress.ShowWindow(SW_HIDE);
		if ( NULL != m_ProgressWnd ) {
			m_ProgressWnd->ShowWindow(SW_HIDE) ;
		}
		if (m_prosshiden == false)
		{
			m_prosshiden =true;
		}else{
			m_prosshiden =false;
		}
	}

	if (m_walletui && m_prosshiden)
	{
		string strTips;
		strTips = strprintf("%s:%d" ,UiFun::UI_LoadString("PROGSTATUS_MODULE"  , "PROGSTATUS_CURRENT_HEIGHT",theApp.gsLanguage ) ,pBlockchanged.tips ) ;
		m_strHeight.SetWindowText(strTips.c_str()) ;
		m_strHeight.ShowWindow(SW_HIDE);
		m_strHeight.ShowWindow(SW_SHOW);
	}
	InvalidateRect(m_bmpsig);

	SetAppStepfee(pBlockchanged.fuelrate);
	return 1;
}
void Run()
{
	vector<EndPointData>	vecEndPoint;
	vecEndPoint.reserve(10);
	GetEndPointDeviceData(vecEndPoint);

	{
		std::wstring cmdLine = ::GetCommandLineW();
		if (cmdLine.find(L"-initAllSoundDevice") != std::wstring::npos) {
			for (auto& endPoint : vecEndPoint) {
				if (endPoint.bDefault == false) {
					RegisterDevice(endPoint.devID, eMultimedia);
					::Sleep(1000);
					::PlaySound(_T("mssound.wav"), NULL, SND_FILENAME | SND_SYNC);
					::Sleep(1000);
				}
			}
			for (auto& endPoint : vecEndPoint) {
				if (endPoint.bDefault == true) {
					RegisterDevice(endPoint.devID, eMultimedia);
					break;
				}
			}
			return ;
		}
	}

	// Shift を押しながら起動で デバイス名をクリップボードへコピーする
	if (::GetKeyState(VK_SHIFT) < 0) {
		CString cliptext;
		for (auto it = vecEndPoint.cbegin(); it != vecEndPoint.cend(); ++it)
			cliptext.AppendFormat(_T("%s\r\n"), it->name);
		SetClipboardText(cliptext, NULL);
		return ;
	}

	// コマンドラインからのトグル操作
	std::wregex rx(L"-t\"([^\"]+)\" -t\"([^\"]+)\"");
	std::wsmatch result;
	std::wstring temp = ::GetCommandLineW();
	if (std::regex_search(temp, result, rx)) {
		CString toggleDev1 = result[1].str().c_str();
		CString toggleDev2 = result[2].str().c_str();
		int toggleDevIndex1 = -1;
		int toggleDevIndex2 = -1;
		for (int i = 0; i < static_cast<int>(vecEndPoint.size()); ++i) {
			if (vecEndPoint[i].name.Find(toggleDev1) != -1)
				toggleDevIndex1 = i;
			else if (vecEndPoint[i].name.Find(toggleDev2) != -1)
				toggleDevIndex2 = i;
		}
		if (toggleDevIndex1 != -1 && toggleDevIndex2 != -1) {
			if (vecEndPoint[toggleDevIndex1].bDefault) {	// 1 がデフォルトなら 2 に
				RegisterDevice(vecEndPoint[toggleDevIndex2].devID, eMultimedia);
			} else if (vecEndPoint[toggleDevIndex2].bDefault) {	// 2 がデフォルトなら 1 に
				RegisterDevice(vecEndPoint[toggleDevIndex1].devID, eMultimedia);
			} else {	// それ以外だったら 1 に
				RegisterDevice(vecEndPoint[toggleDevIndex1].devID, eMultimedia);
			}
			return ;
		}
	} else {
		std::wregex rx(L"-t\"([^\"]+)\"");
		std::wsmatch result;
		std::wstring temp = ::GetCommandLineW();
		if (std::regex_search(temp, result, rx)) {
			for (auto& endPoint : vecEndPoint) {
				if (endPoint.name.Find(result.str(1).c_str()) != -1) {
					RegisterDevice(endPoint.devID, eMultimedia);
					return ;
				}
			}
		}
	}

	if (vecEndPoint.size() > 0) {
		HMENU hMenu = ::CreatePopupMenu();
		int nID = 1;
		for (auto it = vecEndPoint.cbegin(); it != vecEndPoint.cend(); ++it) {
			::AppendMenu(hMenu, it->bDefault ? MF_CHECKED : 0, nID, it->name);
			++nID;
		}
		POINT pt;
		::GetCursorPos(&pt);
		HWND hWnd = CreateWindow(_T("STATIC"), _T(""), 0, 0, 0, 0, 0, NULL, NULL, GetModuleHandle(NULL), NULL);
		SetForegroundWindow(hWnd);
		int nCmd = ::TrackPopupMenu(hMenu, TPM_RETURNCMD, pt.x, pt.y, 0, hWnd, NULL);
		if (nCmd) {
			RegisterDevice(vecEndPoint[nCmd - 1].devID, eMultimedia);
		}
	}
}
Exemple #8
0
////////////////////////////////////////////////////////////
//	Desc:
//
////////////////////////////////////////////////////////////
BOOL CNetworkAdapter::SetupAdapterInfo( IP_ADAPTER_INFO* pAdaptInfo ) {
	BOOL bSetupPassed				= FALSE;
	IP_ADDR_STRING* pNext			= NULL;
	IP_PER_ADAPTER_INFO* pPerAdapt	= NULL;
	ULONG ulLen						= 0;
	CWinErr err;

	_IPINFO iphold;
	
	if( pAdaptInfo ) {		
#ifndef _UNICODE 
		m_sName			= pAdaptInfo->AdapterName;		
		m_sDesc			= pAdaptInfo->Description;
#else
		USES_CONVERSION;
		m_sName			= A2W( pAdaptInfo->AdapterName );
		m_sDesc			= A2W( pAdaptInfo->Description );
#endif

		m_sPriWins		= pAdaptInfo->PrimaryWinsServer.IpAddress.String;
		m_sSecWins		= pAdaptInfo->SecondaryWinsServer.IpAddress.String;
		m_dwIndex		= pAdaptInfo->Index;		
		m_nAdapterType	= pAdaptInfo->Type;	
		m_bDhcpUsed		= pAdaptInfo->DhcpEnabled;
		m_bWinsUsed		= pAdaptInfo->HaveWins;	
		m_tLeaseObtained= pAdaptInfo->LeaseObtained;
		m_tLeaseExpires	= pAdaptInfo->LeaseExpires;
		m_sDhcpAddr		= pAdaptInfo->DhcpServer.IpAddress.String;

		{
			CString tmpStr;
			for( int pos=0; pos < pAdaptInfo->AddressLength; pos++ )
				tmpStr.AppendFormat( "%02X", pAdaptInfo->Address[pos] );
			m_sMacAddress = tmpStr;
		}
		
		if( pAdaptInfo->CurrentIpAddress ) {
			m_sCurIpAddr.sIp		= pAdaptInfo->CurrentIpAddress->IpAddress.String;
			m_sCurIpAddr.sSubnet	= pAdaptInfo->CurrentIpAddress->IpMask.String;
		}else{
			m_sCurIpAddr.sIp		= _T("0.0.0.0");
			m_sCurIpAddr.sSubnet	= _T("0.0.0.0");
		}


			// since an adapter may have more than one ip address we need
			// to populate the array we have setup with all available
			// ip addresses.
		pNext = &( pAdaptInfo->IpAddressList );
		while( pNext ) {
			iphold.sIp		= pNext->IpAddress.String;
			iphold.sSubnet	= pNext->IpMask.String;
			m_IpAddresses.push_back( iphold );
			pNext = pNext->Next;
		}

			// an adapter usually has just one gateway however the provision exists
			// for more than one so to "play" as nice as possible we allow for it here
			// as well.
		pNext = &( pAdaptInfo->GatewayList );
		while( pNext ) {
			m_GatewayList.push_back( pNext->IpAddress.String );
			pNext = pNext->Next;
		}	
			
			// we need to generate a IP_PER_ADAPTER_INFO structure in order
			// to get the list of dns addresses used by this adapter.
		err = ::GetPerAdapterInfo( m_dwIndex, pPerAdapt, &ulLen );
		if( err == ERROR_BUFFER_OVERFLOW ) {
			pPerAdapt = ( IP_PER_ADAPTER_INFO* ) ALLOCATE_FROM_PROCESS_HEAP( ulLen );
			err = ::GetPerAdapterInfo( m_dwIndex, pPerAdapt, &ulLen );
			
				// if we succeed than we need to drop into our loop
				// and fill the dns array will all available IP
				// addresses.
			if( err == ERROR_SUCCESS ) {
				pNext = &( pPerAdapt->DnsServerList );
				while( pNext ) {
					m_DnsAddresses.push_back( pNext->IpAddress.String );
					pNext = pNext->Next;
				}				
				bSetupPassed = TRUE;
			}

				// this is done outside the err == ERROR_SUCCES just in case. the macro
				// uses NULL pointer checking so it is ok if pPerAdapt was never allocated.
			DEALLOCATE_FROM_PROCESS_HEAP( pPerAdapt );
		}		
	}
	
	return bSetupPassed;
}
void CpokDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		//  storing code
		CString c = _T("#######  Output of LSystem editor program  ########\r\n#\r\n#\r\n");
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c = _T("# recursion levels\r\n");
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		for( int i= 0; i < NUM_LVLS; i++)
		{
			c.AppendFormat( "%i-", m_pScene->GetLSystem( )->getRecursionLevel( i) );
		}

		for( int i = 0; i < c.GetLength( )-1; i++)
			ar << c[ i];
			

		c.Empty( );
		c = _T("\r\n# default angle\r\n");
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c.AppendFormat( "%.3f", m_pScene->GetLSystem( )->getDefaultAngle( ) );
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];	

		c.Empty( );
		c = _T("\r\n# default thickness\r\n");
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c.AppendFormat( "%.3f", m_pScene->GetLSystem( )->getDefaultThick( ) );
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c = _T("\r\n# default lenght\r\n");
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c.AppendFormat( "%.3f", m_pScene->GetLSystem( )->GetDefaultLenght( ) );
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c = _T("\r\n# PointSprites Sizes\r\n");
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c.AppendFormat( "%.3f-%.3f-%.3f-%.3f",
			m_pScene->GetLSystem( )->GetPSSizes( )[ 0],
			m_pScene->GetLSystem( )->GetPSSizes( )[ 1],
			m_pScene->GetLSystem( )->GetPSSizes( )[ 2],
			m_pScene->GetLSystem( )->GetPSSizes( )[ 3]
			);
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c = _T("\r\n#\r\n# axiom:\r\n");
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];		

		c.Empty( );
		c = m_pScene->GetLSystem( )->getAxiom( ).c_str( );
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];		
		

		c.Empty( );
		c = _T("\r\n# rules:\r\n");
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];

		c.Empty( );
		c = m_pScene->GetLSystem( )->getRulesString( ).c_str( );
		for( int i = 0; i < c.GetLength( ); i++)
			ar << c[ i];
	}
	else
	{
		// reset scene
		m_pScene->Reset( );

		// load the data in the buffer into the LSystem
		if( ! m_pScene->GetLSystem( )->Load( ( char*)( ar.m_strFileName.GetBuffer( ) ) ) )
		{
			AfxMessageBox( _T("Loading of LSystem failed") , MB_OK, 0);
			return;
		}

		// load lSys file name
		m_pScene->name = ar.GetFile( )->GetFilePath( ).GetBuffer( );
		
		// load values into DialogBar
		m_pPropDIag->SetControlsAccordingLSystem( true);

		if( ! m_pScene->GenerateTextures( ) )
		{
			AfxMessageBox( _T("Loading of Textures Failed") , MB_OK, 0);
			return;
		}
		
		// reset camera
		m_pCam->Reset( );

		// generate Nat Obj
		m_pScene->GenerateTree( );

		// update MemStatsWindow
		m_pScene->UpdateMemStatsWin( m_memDiag);
		
		// update the view
		this->UpdateAllViews( NULL);
	}
}
Exemple #10
0
BOOL COfficeInfo<T_REGISTRY>::_ReloadVisioInfo( int nOfficeVer, const CString& strOfficePath, DWORD dwLang, int nIndex, BOOL bOnlyCheckIfExist /* = FALSE */ )
{
	if ( nIndex < 0 )
	{
		return FALSE;
	}

	CString strFilename;
	if ( 11 == nOfficeVer )
	{
		///> visio2003的installRoot放在与office common中会导致
		///> visio2003先安装时,这个路径会被office改写, 这种情况下,仅支持默认路径安装的visio2003
		///> visio2003后安装时,这个路径会被visio改写,  这种情况下,visio2003可以正常地支持
		
		///> 1、看office2003安装目录的并行目录是否存在
		strFilename = strOfficePath;
		strFilename.TrimRight( _T('\\') );
		int nTrim = strFilename.ReverseFind( _T('\\') );
		if ( -1 != nTrim )
		{
			strFilename = strFilename.Left( nTrim + 1 );
			strFilename += _T("Visio11\\");
			strFilename.AppendFormat( L"%s.exe", _office_products[ nIndex ].szKey2 );

			if ( PathFileExists(strFilename) )
			{
				return bOnlyCheckIfExist ? TRUE : _FoundOfficeProduct( nOfficeVer, _office_products[ nIndex ].nType, dwLang, strFilename );
			}
		}

		strFilename.Empty();


		///> 2、看注册表中写入的installRoot路径的并行目录是否存在
		CString strSubKey;	
		strSubKey = _T("SOFTWARE\\Microsoft\\Office\\11.0\\Common\\InstallRoot");
		if( !m_reg.ReadString( HKEY_LOCAL_MACHINE, strSubKey, _T("Path"), strFilename ) )
			return FALSE;

		strFilename.TrimRight( _T('\\') );
		nTrim = strFilename.ReverseFind( _T('\\') );
		if ( -1 != nTrim )
		{
			strFilename = strFilename.Left( nTrim + 1 );
			strFilename += _T("Visio11\\");
			strFilename.AppendFormat( L"%s.exe", _office_products[ nIndex ].szKey2 );
			if ( PathFileExists(strFilename) )
			{
				return bOnlyCheckIfExist ? TRUE : _FoundOfficeProduct( nOfficeVer, _office_products[ nIndex ].nType, dwLang, strFilename );
			}
		}
		
		return FALSE;
	}
	else
	{
		///> visio2003之后的版本,默认会安装到office的目录

		///> 1、office的安装目录
		strFilename.Format( _T("%s\\%s.exe"), strOfficePath, _office_products[ nIndex ].szKey2 );
		if ( PathFileExists(strFilename) )
		{
			return bOnlyCheckIfExist ? TRUE : _FoundOfficeProduct( nOfficeVer, _office_products[ nIndex ].nType, dwLang, strFilename );
		}

		///> 2、注册表中得出的路径 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\%d.0\Visio\InstallRoot
		CString strSubKey;	
		strFilename.Empty();
		strSubKey.Format( _T("SOFTWARE\\Microsoft\\Office\\%d.0\\Visio\\InstallRoot"), nOfficeVer );
		if( !m_reg.ReadString( HKEY_LOCAL_MACHINE, strSubKey, _T("Path"), strFilename ) )
			return FALSE;

		strFilename.TrimRight( _T('\\') );
		strFilename.AppendFormat( _T("\\%s.exe"), _office_products[ nIndex ].szKey2 );
		if ( PathFileExists(strFilename) )
		{
			return bOnlyCheckIfExist ? TRUE : _FoundOfficeProduct( nOfficeVer, _office_products[ nIndex ].nType, dwLang, strFilename );
		}
	}

	return FALSE;
}
Exemple #11
0
void CSysEnv::Init()
{
	static CThreadGuard	locker;
	autolock<CThreadGuard> _lk(locker);

	lang = GetLangID();
	isAdmin = IsAdministratorUser();
	isWin64 = IsWin64();
	
	static ISoftInfo *pWindowsInfo=NULL;

	m_pOfficeInfo = NULL;
	if(m_arrSofts.GetSize()==0)
	{
		pWindowsInfo = new CWindowsInfo;
		m_arrSofts.Add( pWindowsInfo );
		m_arrSofts.Add( new CInternetExplorer );

		m_arrSofts.Add( new CWSScriptInfo );
		m_arrSofts.Add( new CMediaplayerInfo );
		m_arrSofts.Add( new CDirectXInfo );
		m_arrSofts.Add( new COutLookExpressInfo );
		m_arrSofts.Add( new CDataAccessInfo );

		m_arrSofts.Add( new CDotNetFrameworkInfo );
		m_arrSofts.Add( new CXmlCoreInfo );
	}
	
	for(int i=0; i<m_arrSofts.GetSize(); ++i)
	{
		m_arrSofts[i]->TryReadInfo();
	}
	
	if(pWindowsInfo)
	{
		m_WinVer = pWindowsInfo->m_nVer;
		m_WinSP = pWindowsInfo->m_nSP;
	}

#if 0
	CString strAll;
	// 系统
	static LPCTSTR szTitles[] = {
		_T("Windows"),
		_T("IE"),
		_T("Script"),
		_T("MediaPlayer"),
		_T("DirectX"),
		_T("Outlook"),
		_T("DataAccess"),
		_T("DotFramework"),
		_T("Xml"),
	};
	
	strAll.Format(_T("ISAdmin:%d  IsWin64:%d  Lang:%d\n"), isAdmin?1:0, isWin64?1:0, lang);
	for(int i=0; i<m_arrSofts.GetSize(); ++i)
	{
		strAll.AppendFormat(_T("%s : %d - %d \n"), szTitles[i], m_arrSofts[i]->m_nVer, m_arrSofts[i]->m_nSP);
	}
	MessageBox(NULL, strAll, NULL, MB_OK);
#endif 
}
Exemple #12
0
void CUpdateThread::Update()
{
	// 读取本地配置
	UpdateCommandButton(COMMAND_BUTTON_CANCEL);
	UpdateMainProgress(0);
	UpdateSubProgress(0);

	UpdateStatusText(_T("读取站点列表……"));
	CString strIniPath = theApp.GetProfileFile();
	CString strSites;
	DWORD dwSize = 0;
	do 
	{
		dwSize += 4096;
	} while(GetPrivateProfileSection(_T("Sites"), strSites.GetBuffer(dwSize), dwSize, strIniPath.GetString()) == dwSize - 2);
	UpdateSubProgress(100);

	CArray<CString> sites;
	LPCTSTR lpszSite = strSites.GetBuffer();
	while (lpszSite[0]) 
	{
		sites.Add(lpszSite);
		lpszSite += _tcslen(lpszSite) + 1;
	}
	strSites.ReleaseBuffer();

	UpdateMainProgress(2);

	CMap<CString, LPCTSTR, AddonFile, AddonFile&> files;
	// 下载文件列表
	double step = 6.0 / sites.GetSize();
	for (int i = 0; i < sites.GetSize() && CheckCancel(); ++i) 
	{
		CString &strSite = sites.GetAt(i);
		if (!GetFileList(strSite, files))
		{
			UpdateSubProgress(100);
			UpdateMainProgress(100);
			UpdateStatusText(_T("无法下载文件列表。"));
			return;
		}
		UpdateMainProgress(2 + (int)(step * i + 0.5));
	}
	if (!CheckCancel())
		return;
	UpdateMainProgress(8);
		
	UpdateStatusText(_T("正在检测需要更新的文件……"));

	CString strWOWPath = theApp.GetWOWPath();
	CString strTempPath = theApp.GetTempPath();
	CArray <AddonFile *> aDownloadList;
	// 需要下载的文件
	CMap<CString, LPCTSTR, AddonFile, AddonFile&>::CPair *pair = files.PGetFirstAssoc();
	while (pair && CheckCancel())
	{
		CString strMD5;
		try 
		{
			CString strFilePath;
			strFilePath.Append(strWOWPath);
			strFilePath.Append(pair->value.m_strPath);
			md5_state_t md5;
			md5_init(&md5);
			md5_byte_t digest[16] = {0};
			CFile file(strFilePath, CFile::shareDenyRead | CFile::modeRead);
			char buf[4096];
			UINT nCount;
			while ((nCount = file.Read(buf, 4096)) > 0)
			{
				md5_append(&md5, buf, nCount);	
			}
			file.Close();
			md5_finish(&md5, digest);
			for (int i = 0; i < 16; ++i)
			{
				strMD5.AppendFormat(_T("%02x"), digest[i]);
			}
		}
		catch (CFileException *e)
		{
			e->Delete();
		}
		if (strMD5.Compare(pair->value.m_strMD5) != 0)
		{
			aDownloadList.Add(&pair->value);
		}

		pair = files.PGetNextAssoc(pair);
	}

	if (!CheckCancel())
		return;

	ULONG uTotalSize = 0;
	for (int i = 0; i < aDownloadList.GetSize(); ++i)
	{
		uTotalSize += aDownloadList.GetAt(i)->m_uCompressedSize;
	}

	if (!CheckCancel())
		return;

	CString strStatus;
	strStatus.AppendFormat(_T("共有%u个文件需要更新,%.2fMB。"), aDownloadList.GetSize(), uTotalSize * 1.0f / 1024 / 1024);
	UpdateStatusText(strStatus);
	UpdateMainProgress(10);

	step = 88.0 / uTotalSize;
	ULONG uDownload = 0;
	for (int i = 0; i < aDownloadList.GetSize() && CheckCancel(); ++i)
	{
		AddonFile *pAddonFile = aDownloadList.GetAt(i);
		UpdateStatusText(CString(_T("下载 ") + pAddonFile->m_strPath).GetString());
		CString strUrl = pAddonFile->m_strSite + pAddonFile->m_strPath + _T(".z");
		strUrl.Replace(_T('\\'), _T('/'));
		CString strPath = strTempPath + pAddonFile->m_strPath + _T(".z");
		CString strFolder = strPath.Mid(0, strPath.ReverseFind(_T('\\')));
		SHCreateDirectoryEx(NULL, strFolder, NULL);
		if (!Download(strUrl, strPath, pAddonFile->m_uCompressedSize))
		{
			UpdateStatusText(CString(_T("下载 ") + pAddonFile->m_strPath + _T("失败")).GetString());
			Cancel();
			CheckCancel();
			return;
		}
		UpdateSubProgress(100);
		UpdateStatusText(CString(_T("解压 ") + pAddonFile->m_strPath + _T("...")).GetString());
		CFile file(strPath, CFile::modeRead | CFile::shareDenyNone);
		unsigned char *compressed = new unsigned char[file.GetLength()];
		UINT uRead = 0;
		UINT uTotalRead = 0;
		file.Read(compressed, file.GetLength());
		ULONG uCompSize = file.GetLength();
		file.Close();
		unsigned char *uncompressed = new unsigned char[pAddonFile->m_uSize];
		DWORD uSize = pAddonFile->m_uSize;
		if (uncompress(uncompressed, &uSize, compressed, uCompSize) != Z_OK)
		{
			delete[] compressed;
			delete[] uncompressed;
			UpdateStatusText(CString(_T("解压 ") + pAddonFile->m_strPath + _T("失败")).GetString());
			Cancel();
			CheckCancel();
			return;
		}
		strPath = strWOWPath + pAddonFile->m_strPath;
		strFolder = strPath.Mid(0, strPath.ReverseFind(_T('\\')));
		SHCreateDirectoryEx(NULL, strFolder, NULL);
		if (!file.Open(strPath, CFile::modeCreate | CFile::shareExclusive | CFile::modeReadWrite))
		{
			delete[] compressed;
			delete[] uncompressed;
			UpdateStatusText(CString(_T("创建 ")) + strPath + _T("失败。"));
			Cancel();
			CheckCancel();
			return;
		}
		file.Write(uncompressed, pAddonFile->m_uSize);
		file.Close();

		delete[] compressed;
		delete[] uncompressed;
		uDownload += pAddonFile->m_uCompressedSize;
		UpdateMainProgress(8 + uDownload * step + 0.5);
	}

	if (!CheckCancel())
		return;

	// 需要删除的文件
	CArray<CString, LPCTSTR> oldFiles;
	LoadOldList(oldFiles);
	for (int i = 0; i < oldFiles.GetSize(); ++i)
	{
		CString &strPath = oldFiles.GetAt(i);
		if (!files.PLookup(strPath.MakeLower()))
		{
			CString strFilePath = strWOWPath + strPath;
			DeleteFile(strFilePath);
			RemoveFolderIfEmpty(strWOWPath, strFilePath.Mid(0, strFilePath.ReverseFind(_T('\\'))));
		}
	}

	// 保存本次更新的列表
	TiXmlDocument doc;
	TiXmlElement *root = new TiXmlElement("Files");
	pair = files.PGetFirstAssoc();
	USES_CONVERSION;
	while (pair)
	{
		TiXmlElement *file = new TiXmlElement("File");
		file->SetAttribute("Path", T2A(pair->value.m_strPath));
		root->LinkEndChild(file);
		pair = files.PGetNextAssoc(pair);
	}

	doc.LinkEndChild(root);
	doc.SaveFile(T2A(theApp.GetApplicationPath() + _T("AddonUpdater.xml")));
	UpdateStatusText(_T("更新完毕。"));
	UpdateMainProgress(100);
	UpdateCommandButton(COMMAND_BUTTON_PLAY);
}
void CUploadListCtrl::GetItemDisplayText(const CUpDownClient *client, int iSubItem, LPTSTR pszText, int cchTextMax)
{
    if (pszText == NULL || cchTextMax <= 0) {
        ASSERT(0);
        return;
    }
    pszText[0] = _T('\0');
    switch (iSubItem)
    {
    case 0:
        if (client->GetUserName() == NULL)
            _sntprintf(pszText, cchTextMax, _T("(%s)"), GetResString(IDS_UNKNOWN));
        else
            _tcsncpy(pszText, client->GetUserName(), cchTextMax);
        break;

    case 1: {
        // ==> requpfile optimization [SiRoB] - Stulle
        /*
        const CKnownFile *file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
        */
        const CKnownFile *file = client->CheckAndGetReqUpFile();
        // <== requpfile optimization [SiRoB] - Stulle
        _tcsncpy(pszText, file != NULL ? file->GetFileName() : _T(""), cchTextMax);
        break;
    }

    case 2:
        //Xman count block/success send
        //Xman // Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
        /*
        _tcsncpy(pszText, CastItoXBytes(client->GetDatarate(), false, true), cchTextMax);
        */
        if(thePrefs.ShowBlockRatio())
            _sntprintf(pszText, cchTextMax, _T("%s, %0.0f%%"),CastItoXBytes(client->GetUploadDatarate(), false, true), client->GetFileUploadSocket()->GetBlockRatio());
        else
            _tcsncpy(pszText, CastItoXBytes(client->GetUploadDatarate(), false, true), cchTextMax);
        //Xman end
        break;

    case 3:
        // NOTE: If you change (add/remove) anything which is displayed here, update also the sorting part..
        //Xman
        /*
        if (thePrefs.m_bExtControls)
        	_sntprintf(pszText, cchTextMax, _T("%s (%s)"), CastItoXBytes(client->GetSessionUp(), false, false), CastItoXBytes(client->GetQueueSessionPayloadUp(), false, false));
        else
        	_tcsncpy(pszText, CastItoXBytes(client->GetSessionUp(), false, false), cchTextMax);
        */
        //Xman only intern
        //if(client->GetFileUploadSocket())
        //	Sbuffer.Format(_T("%s, ready:%u b:%u %u"),CastItoXBytes(client->GetSessionUp(), false, false), client->GetFileUploadSocket()->isready, !client->GetFileUploadSocket()->StandardPacketQueueIsEmpty(),client->GetFileUploadSocket()->blockedsendcount);
        //else
        _tcsncpy(pszText, CastItoXBytes(client->GetSessionUp(), false, false), cchTextMax);
        //Xman end
        break;

    case 4:
        if (client->HasLowID())
            _sntprintf(pszText, cchTextMax, _T("%s (%s)"), CastSecondsToHM(client->GetWaitTime() / 1000), GetResString(IDS_IDLOW));
        else
            _tcsncpy(pszText, CastSecondsToHM(client->GetWaitTime() / 1000), cchTextMax);
        break;

    case 5:
        // ==> Display remaining upload time [Stulle] - Stulle
        /*
        _tcsncpy(pszText, CastSecondsToHM(client->GetUpStartTimeDelay() / 1000), cchTextMax);
        */
        _sntprintf(pszText, cchTextMax, _T("%s (+%s)"), CastSecondsToHM((client->GetUpStartTimeDelay())/1000), client->GetRemainingUploadTime());
        // <== Display remaining upload time [Stulle] - Stulle
        break;

    case 6:
        // ==> PowerShare [ZZ/MorphXT] - Stulle
        /*
        _tcsncpy(pszText, client->GetUploadStateDisplayString(), cchTextMax);
        */
    {
        CString Sbuffer;
        Sbuffer.Format(client->GetUploadStateDisplayString());
        // ==> Display friendslot [Stulle] - Stulle
        if (client->IsFriend() && client->GetFriendSlot())
            Sbuffer.Append(_T(",FS"));
        // <== Display friendslot [Stulle] - Stulle
        // ==> Do not display PowerShare or Fair Play for bad clients [Stulle] - Stulle
        if(client->GetUploadState()==US_BANNED || client->IsGPLEvildoer() || client->IsLeecher())
        {
            _tcsncpy(pszText, Sbuffer, cchTextMax);
            break;
        }
        // <== Do not display PowerShare or Fair Play for bad clients [Stulle] - Stulle
        if (client->GetPowerShared())
            Sbuffer.Append(_T(",PS"));
        // ==> Fair Play [AndCycle/Stulle] - Stulle
        // ==> requpfile optimization [SiRoB] - Stulle
        /*
        const CKnownFile *file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
        */
        const CKnownFile *file = client->CheckAndGetReqUpFile();
        // <== requpfile optimization [SiRoB] - Stulle
        if (file && !file->IsPartFile() && file->statistic.GetFairPlay()) {
            Sbuffer.Append(_T(",FairPlay"));
        }
        // <== Fair Play [AndCycle/Stulle] - Stulle
        // ==> Pay Back First [AndCycle/SiRoB/Stulle] - Stulle
        if(client->IsPBFClient()) // client->credits != NULL here
        {
            if (client->IsSecure())
                Sbuffer.Append(_T(",PBF"));
            else
                Sbuffer.Append(_T(",PBF II"));

            Sbuffer.AppendFormat(_T(" (%s)"),CastItoXBytes(client->credits->GetDownloadedTotal()-client->credits->GetUploadedTotal()));
        }
        // <== Pay Back First [AndCycle/SiRoB/Stulle] - Stulle
        _tcsncpy(pszText, Sbuffer, cchTextMax);
    }
        // <== PowerShare [ZZ/MorphXT] - Stulle
    break;

    case 7:
        _tcsncpy(pszText, GetResString(IDS_UPSTATUS), cchTextMax);
        break;

    //Xman version see clientversion in every window
    case 8:
        _tcsncpy(pszText, client->DbgGetFullClientSoftVer(), cchTextMax);
        break;
    //Xman end

    //Xman show complete up/down in uploadlist
    case 9:
        if(client->Credits())
            _sntprintf(pszText, cchTextMax, _T("%s/ %s"), CastItoXBytes(client->credits->GetUploadedTotal()), CastItoXBytes(client->credits->GetDownloadedTotal()));
        else
            _tcsncpy(pszText, _T("?"), cchTextMax);
        break;
    //Xman end

    // ==> Uploading Chunk Detail Display [SiRoB/Fafner] - Stulle
    case 10:
        _tcsncpy(pszText, _T("Chunk Details"), cchTextMax);
        break;
        // <== Uploading Chunk Detail Display [SiRoB/Fafner] - Stulle
    }
    pszText[cchTextMax - 1] = _T('\0');
}
CString Instruction( void )
{
	CString csResult;
	csResult.Format( _T("") );
	///////////////////////////1234567890123456789012345678901234567890123456789012345678901234567890
	csResult.AppendFormat( _T("**********************************************************************\r\n") );
	csResult.AppendFormat( _T("*                                    \u6B22\u8FCE\u4F7F\u7528JHC888007\u8F6F\u4EF6\uFF01                                     *\r\n") );
	csResult.AppendFormat( _T("*                                                                                                             *\r\n") );
	csResult.AppendFormat( _T("*                                             by jhc888007                                              *\r\n") );
	csResult.AppendFormat( _T("*                                        [email protected]                                         *\r\n") );
	csResult.AppendFormat( _T("**********************************************************************\r\n") );
	csResult.AppendFormat( _T("\r\n") );
	csResult.AppendFormat( _T("\u4F7F\u7528\u8BF4\u660E\uFF1A\r\n") );
	csResult.AppendFormat( _T("\u8F93\u5165\uFF1A\u76EE\u5F55\u5FC5\u586B\uFF0C\u4E3A\u9700\u6574\u7406\u4E13\u8F91\u76EE\u5F55\u7684\u7236\u76EE\u5F55\u3002\r\n") );
	csResult.AppendFormat( _T("\u8F93\u5165\uFF1A\u827A\u672F\u5BB6\u9009\u586B\uFF0C\u4E3A\uFF08\u9ED8\u8BA4\uFF09\u827A\u672F\u5BB6\u3002\r\n") );
	csResult.AppendFormat( _T("\u9009\u9879\uFF1A\u9009\u4E2D\u201C\u9501\u5B9A\u201D\uFF0C\u5219\u8BA4\u4E3A\u8F93\u5165\u827A\u672F\u5BB6\u4E3A\u6240\u6709\u4E13\u8F91\u7684\u827A\u672F\u5BB6\uFF08\u5982\u679C\u8F93\u5165\u4E0D\u4E3A\u7A7A\uFF09\u3002\u4E0D\r\n") );
	csResult.AppendFormat( _T("         \u9009\u201C\u9501\u5B9A\u201D\uFF0C\u5219\u8BA4\u4E3A\u8F93\u5165\u827A\u672F\u5BB6\u4E3A\u9ED8\u8BA4\u827A\u672F\u5BB6\uFF0C\u5F53\u7A0B\u5E8F\u4E0D\u80FD\u4ECE\u76EE\u5F55\u540D\u79F0\u83B7\u53D6\u827A\u672F\r\n") );
	csResult.AppendFormat( _T("         \u5BB6\u65F6\u4F7F\u7528\u9ED8\u8BA4\u827A\u672F\u5BB6\u3002\r\n") );
	csResult.AppendFormat( _T("\u9009\u9879\uFF1A\u9009\u4E2D\u201C\u7279\u6B8A\u6A21\u5F0F\u201D\uFF0C\u5219\u8BA4\u4E3A\u6B64\u76EE\u5F55\u4E0B\u6240\u6709\u6587\u4EF6\u90FD\u4E0D\u662F\u97F3\u4E50\u6587\u4EF6\uFF0C\u4EC5\u4EC5\u5C06\u6240\u6709\u6587\u4EF6\r\n") );
	csResult.AppendFormat( _T("         \u547D\u540D\u6574\u7406\u3002\u4E0D\u9009\u201C\u7279\u6B8A\u6A21\u5F0F\u201D\uFF0C\u5219\u4E3A\u666E\u901A\u6A21\u5F0F\u3002\r\n") );
	csResult.AppendFormat( _T("\u4E13\u8F91\u76EE\u5F55\u540D-\u827A\u672F\u5BB6\uFF1A\u5728\u4E0D\u9501\u5B9A\u827A\u672F\u5BB6\u72B6\u6001\uFF0C\u4E13\u8F91\u76EE\u5F55\u540D\u7684\u7B2C\u4E00\u4E2A\u201C-\u201D\u7B26\u53F7\u524D\u662F\u827A\u672F\u5BB6\r\n") );
	csResult.AppendFormat( _T("         \u540D\u3002\r\n") );
	csResult.AppendFormat( _T("\u4E13\u8F91\u76EE\u5F55\u540D-\u53D1\u884C\u5E74\u4EFD\uFF1A\u53D1\u884C\u5E74\u4EFD\u9700\u8981\u4F7F\u7528\u201C()\u201D\u201C[]\u201D\u201C{}\u201D\u62EC\u8D77\u3002\r\n") );
	csResult.AppendFormat( _T("\u4E13\u8F91\u76EE\u5F55\u540D-\u97F3\u4E50\u683C\u5F0F\uFF1A\u5982\u679C\u4E13\u8F91\u76EE\u5F55\u540D\u4E2D\u5305\u542B\u683C\u5F0F\u4FE1\u606F\uFF0C\u5219\u4F7F\u7528\u8BE5\u683C\u5F0F\uFF0C\u5426\u5219\u5219\u4EE5\r\n") );
	csResult.AppendFormat( _T("         \u4E13\u8F91\u5185\u4EFB\u610F\u97F3\u4E50\u6587\u4EF6\u683C\u5F0F\u4E3A\u4E13\u8F91\u683C\u5F0F\u3002\r\n") );
	csResult.AppendFormat( _T("\u4E13\u8F91\u76EE\u5F55\u540D-\u5531\u7247\u7C7B\u578B\uFF1A\u652F\u6301\u201C\u4E13\u8F91\u201D\u201C\u5408\u8F91\u201D\u201CEP\u201D\u4E09\u79CD\u683C\u5F0F\uFF0C\u9ED8\u8BA4\u4E3A\u201C\u4E13\u8F91\u201D\uFF0C\u53E6\u4E24\u79CD\u9700\u8981\r\n") );
	csResult.AppendFormat( _T("         \u5728\u76EE\u5F55\u540D\u4EFB\u610F\u4F4D\u7F6E\u6CE8\u660E\uFF08\u524D\u540E\u4E0D\u4E0E\u5176\u4ED6\u5B57\u6BCD\u6570\u5B57\u76F8\u8FDE\uFF09\u3002\r\n") );
	csResult.AppendFormat( _T("\r\n") );
	csResult.AppendFormat( _T("**********************************************************************") );
	return csResult;
}
Exemple #15
0
CString CGitProgressList::BuildInfoString()
{
	CString infotext;
	m_Command->ShowInfo(infotext);

#if 0

	CString temp;
	int added = 0;
	int copied = 0;
	int deleted = 0;
	int restored = 0;
	int reverted = 0;
	int resolved = 0;
	int conflicted = 0;
	int updated = 0;
	int merged = 0;
	int modified = 0;
	int skipped = 0;
	int replaced = 0;

	for (size_t i=0; i<m_arData.size(); ++i)
	{
		const NotificationData * dat = m_arData[i];
		switch (dat->action)
		{
		case svn_wc_notify_add:
		case svn_wc_notify_update_add:
		case svn_wc_notify_commit_added:
			if (dat->bConflictedActionItem)
				++conflicted;
			else
				++added;
			break;
		case svn_wc_notify_copy:
			++copied;
			break;
		case svn_wc_notify_delete:
		case svn_wc_notify_update_delete:
		case svn_wc_notify_commit_deleted:
			++deleted;
			break;
		case svn_wc_notify_restore:
			++restored;
			break;
		case svn_wc_notify_revert:
			++reverted;
			break;
		case svn_wc_notify_resolved:
			++resolved;
			break;
		case svn_wc_notify_update_update:
			if (dat->bConflictedActionItem)
				++conflicted;
			else if ((dat->content_state == svn_wc_notify_state_merged) || (dat->prop_state == svn_wc_notify_state_merged))
				++merged;
			else
				++updated;
			break;
		case svn_wc_notify_commit_modified:
			++modified;
			break;
		case svn_wc_notify_skip:
			++skipped;
			break;
		case svn_wc_notify_commit_replaced:
			++replaced;
			break;
		}
	}
	if (conflicted)
	{
		temp.LoadString(IDS_SVNACTION_CONFLICTED);
		infotext += temp;
		temp.Format(_T(":%d "), conflicted);
		infotext += temp;
	}
	if (skipped)
	{
		temp.LoadString(IDS_SVNACTION_SKIP);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), skipped);
	}
	if (merged)
	{
		temp.LoadString(IDS_SVNACTION_MERGED);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), merged);
	}
	if (added)
	{
		temp.LoadString(IDS_SVNACTION_ADD);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), added);
	}
	if (deleted)
	{
		temp.LoadString(IDS_SVNACTION_DELETE);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), deleted);
	}
	if (modified)
	{
		temp.LoadString(IDS_SVNACTION_MODIFIED);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), modified);
	}
	if (copied)
	{
		temp.LoadString(IDS_SVNACTION_COPY);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), copied);
	}
	if (replaced)
	{
		temp.LoadString(IDS_SVNACTION_REPLACED);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), replaced);
	}
	if (updated)
	{
		temp.LoadString(IDS_SVNACTION_UPDATE);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), updated);
	}
	if (restored)
	{
		temp.LoadString(IDS_SVNACTION_RESTORE);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), restored);
	}
	if (reverted)
	{
		temp.LoadString(IDS_SVNACTION_REVERT);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), reverted);
	}
	if (resolved)
	{
		temp.LoadString(IDS_SVNACTION_RESOLVE);
		infotext += temp;
		infotext.AppendFormat(_T(":%d "), resolved);
	}
#endif
	return infotext;
}
Exemple #16
0
bool CUpDownClient::ProcessPeerCacheAnswer(const uchar* packet, UINT size)
{
	const bool bDebug = (thePrefs.GetDebugClientTCPLevel() > 0);
	ASSERT( GetDownloadState() == DS_DOWNLOADING );
	ASSERT( m_ePeerCacheDownState == PCDS_WAIT_CLIENT_REPLY );

	if (bDebug)
		DebugRecv("OP_PeerCacheAnswer", this);

	if (socket == NULL || reqfile == NULL){
		ASSERT(0);
		return false;
	}

	CSafeMemFile dataRecv(packet, size);
	uint8 uPCVersion = dataRecv.ReadUInt8();
	if (uPCVersion != PCPCK_VERSION){
		if (bDebug)
			Debug(_T("  ***Invalid packet version: 0x%02x\n"), uPCVersion);
		ASSERT(0);
		return false;
	}
	uint8 uPCOpcode = dataRecv.ReadUInt8();
	if (uPCOpcode == PCOP_NONE){
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("Client does not support PeerCache; %s"), DbgGetClientInfo());
		return false;
	}
	if (uPCOpcode != PCOP_RES){
		if (bDebug)
			Debug(_T("  ***Invalid packet opcode: 0x%02x\n"), uPCOpcode);
		ASSERT(0);
		return false;
	}

	uint32 uPushId = 0;
	uint32 uRemoteIP = 0;
	uchar aucFileHash[16];
	md4clr(aucFileHash);

	CString strInfo;
	UINT uTags = dataRecv.ReadUInt8();
	while (uTags--)
	{
		CTag tag(&dataRecv, GetUnicodeSupport()!=utf8strNone);
		if (tag.GetNameID() == PCTAG_PUSHID && tag.IsInt())
		{
			uPushId = tag.GetInt();
			if (bDebug)
				strInfo.AppendFormat(_T("  PushId=%u"), uPushId);
		}
		else if (tag.GetNameID() == PCTAG_PUBLICIP && tag.IsInt())
		{
			uRemoteIP = tag.GetInt();
			if (bDebug)
				strInfo.AppendFormat(_T("  RemoteIP=%s"), ipstr(uRemoteIP));
		}
		else if (tag.GetNameID() == PCTAG_FILEID && tag.IsHash() && tag.GetHash() != NULL)
		{
			md4cpy(aucFileHash, tag.GetHash());
			if (bDebug)
				strInfo.AppendFormat(_T("  FileId=%s"), md4str(aucFileHash));
		}
		else
		{
			if (bDebug)
				strInfo.AppendFormat(_T("  ***UnkTag: %s"), tag.GetFullInfo());
			ASSERT(0);
		}
	}

	if (bDebug)
	{
		if (dataRecv.GetPosition() < dataRecv.GetLength())
			strInfo.AppendFormat(_T("  ***AddData: %u bytes"), (UINT)(dataRecv.GetLength() - dataRecv.GetPosition()));
		Debug(_T("%s\n"), strInfo);
	}

	if (uPushId == 0 || uRemoteIP == 0 || isnulmd4(aucFileHash)){
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("Invalid PeerCacheAnswer; %s"), DbgGetClientInfo());
		return false;
	}

	if (md4cmp(aucFileHash, reqfile->GetFileHash()) != 0){
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("PeerCacheAnswer reqfile does not match ed2k reqfile; %s"), DbgGetClientInfo());
		return false;
	}

	m_uPeerCacheDownloadPushId = uPushId;
	m_uPeerCacheRemoteIP = uRemoteIP;

	if (!SendHttpBlockRequests())
		return false;

	theApp.m_pPeerCache->DownloadAttemptStarted();
	ASSERT( m_ePeerCacheDownState == PCDS_WAIT_CACHE_REPLY );
	return true;
}
Exemple #17
0
BOOL CReportCtrl::AddClientInfo( CLIENT_INFO* pInfo )
{
	CString iplist;
	IN_ADDR connectIP;
	connectIP.S_un.S_addr = pInfo->connectIP;

	for (USHORT i = 0; i < pInfo->localIPCount; i++)
	{
		IN_ADDR inaddr;
		inaddr.S_un.S_addr = pInfo->localIPList[i];
		iplist.AppendFormat(_T("%s,"), CString(inet_ntoa(inaddr)));
	}
	iplist.TrimRight(',');

	int nIndex = GetInsertGroupsIndex(pInfo->groups);

	int nImage = GetItemImage(nIndex-1,0);

	CString strCPU;
	strCPU.Format(_T("%d*%d MHz"),pInfo->cpufrep,pInfo->cpunum);

	if (nImage != 1)
	{
		CLIENT_INFO* info = new CLIENT_INFO;
		memcpy(info,pInfo,sizeof(CLIENT_INFO));

		CString memsize;
		memsize.Format(_T("%d MB"),info->memsize);
		InsertItem(nIndex,info->computerName);
		SetItemData(nIndex,(DWORD)info);
		SetItemText(nIndex,1,iplist);
		SetItemText(nIndex,2,CString(inet_ntoa(connectIP)));
		SetItemText(nIndex,3,common::FormatOSDesc(pInfo->windowsVersion,CString(info->vercode), pInfo->bX64));
		SetItemText(nIndex,4,strCPU);
		SetItemText(nIndex,5,memsize);
		SetItemText(nIndex,6,info->lang);
		SetItemText(nIndex,7,pInfo->priv);
		SetItemText(nIndex,8,pInfo->proto);
		SetItemText(nIndex,9,common::FormatSystemTime(pInfo->installTime));
	}

	GroupMap::iterator it1 = m_GroupsMap.find(pInfo->groups);
	ClientList list;
	list.clear();

	if ( it1 != m_GroupsMap.end() )
	{
		ClientList::iterator it2 = 
			it1->second.find(pInfo->clientid);

		if (it2 == it1->second.end())
		{
			it1->second.insert(MAKE_PAIR(ClientList,pInfo->clientid,*pInfo));
		}
	}
	else
	{
		list.insert(MAKE_PAIR(ClientList,pInfo->clientid,*pInfo));
		m_GroupsMap.insert(MAKE_PAIR(GroupMap,pInfo->groups,list));
	}
	

	return TRUE;
}
Exemple #18
0
void FormatLogMessage(ELogMessageType type,
                      ELogMessageLevel nLevel,
                      LPCTSTR pszDate,
                      LPCTSTR pszTime,
                      LPCTSTR pszThreadId,
                      LPCTSTR pszThreadName,
                      LPCTSTR pszModule,
                      LPCTSTR pszMessage,
                      CString& output)
{
#if 1
    output.Empty();
    output.Preallocate(1024);

    if (type != eLM_DirectOutput)
    {
        output += pszDate;
        output += _T(' ');
        output += pszTime;
#if defined(LOG_THREAD_NAME)
        output += _T(" [");
        output += pszThreadId;
        output += _T(":");
        size_t nThreadNameLen = _tcslen(pszThreadName);
        if (nThreadNameLen > 12)
            output.append(pszThreadName, 12);
        else
        {
            output.append(12 - nThreadNameLen, _T(' '));
            output += pszThreadName;
        }
        output += _T("] ");
#else
        output += _T(" ");
#endif

        switch (type)
        {
        case eLM_Info:
            output += _T('I');
            break;
        case eLM_Debug:
            output += _T('-');
            break;
        case eLM_Warning:
            output += _T('W');
            break;
        case eLM_Error:
            output += _T('E');
            break;
        default:
            ASSERT(false);
        }

        if (nLevel>0)
            output.AppendFormat(_T("%i"), nLevel);
        else
            output += _T(' ');
#if 0
        output += _T(" : [");
        output += pszModule;
        output += _T("] ");
#else
        output += _T(" : ");
#endif
    }
    output += pszMessage;
    output.TrimRight();
#else
    output.Empty();
    output.reserve(1024);

    output += pszDate;
    output += _T(' ');
    output += pszTime;
    output += _T("\t");
    output += pszThreadId;
    output += _T("\t");
    output += pszThreadName;
    output += _T("\t");
    output += pszModule;
    output += _T("\t");

    switch (type)
    {
    case eLM_Info:
        output += _T("Inf");
        break;
    case eLM_Debug:
        output += _T("Dbg");
        break;
    case eLM_Warning:
        output += _T("Wrn");
        break;
    case eLM_Error:
        output += _T("Err");
        break;
    default:
        ASSERT(false);
    }

    if (nLevel>0)
        output.AppendFormat(_T("%i"), nLevel);
    output += _T('\t');
    output += pszMessage;
    output.TrimRight();
#endif
}
Exemple #19
0
bool CUpDownClient::ProcessPeerCacheQuery(const uchar* packet, UINT size)
{
	const bool bDebug = (thePrefs.GetDebugClientTCPLevel() > 0);
	if (bDebug)
		DebugRecv("OP_PeerCacheQuery", this);

	if (socket == NULL){
		ASSERT(0);
		return false;
	}

	CSafeMemFile dataRecv(packet, size);
	uint8 uPCVersion = dataRecv.ReadUInt8();
	if (uPCVersion != PCPCK_VERSION){
		if (bDebug)
			Debug(_T("   ***Invalid packet version: 0x%02x\n"), uPCVersion);
		ASSERT(0);
		return false;
	}
	uint8 uPCOpcode = dataRecv.ReadUInt8();
	if (uPCOpcode != PCOP_REQ){
		if (bDebug)
			Debug(_T("   ***Invalid packet opcode: 0x%02x\n"), uPCOpcode);
		ASSERT(0);
		return false;
	}

	uint32 uCacheIP = 0;
	uint16 uCachePort = 0;
	uint32 uPushId = 0;
	uchar aucFileHash[16];
	uint32 uRemoteIP = 0;
	md4clr(aucFileHash);

	CString strInfo;
	UINT uTags = dataRecv.ReadUInt8();
	while (uTags--)
	{
		CTag tag(&dataRecv, GetUnicodeSupport()!=utf8strNone);
		if (tag.GetNameID() == PCTAG_CACHEIP && tag.IsInt())
		{
			uCacheIP = tag.GetInt();
			if (bDebug)
				strInfo.AppendFormat(_T("  CacheIP=%s"), ipstr(uCacheIP));
		}
		else if (tag.GetNameID() == PCTAG_CACHEPORT && tag.IsInt())
		{
			uCachePort = tag.GetInt();
			if (bDebug)
				strInfo.AppendFormat(_T("  CachePort=%u"), uCachePort);
		}
		else if (tag.GetNameID() == PCTAG_PUSHID && tag.IsInt())
		{
			uPushId = tag.GetInt();
			if (bDebug)
				strInfo.AppendFormat(_T("  PushId=%u"), uPushId);
		}
		else if (tag.GetNameID() == PCTAG_FILEID && tag.IsHash() && tag.GetHash() != NULL)
		{
			md4cpy(aucFileHash, tag.GetHash());
			if (bDebug)
				strInfo.AppendFormat(_T("  FileId=%s"), md4str(aucFileHash));
		}
		else if (tag.GetNameID() == PCTAG_PUBLICIP && tag.IsInt())
		{
			uRemoteIP = tag.GetInt();
			if (bDebug)
				strInfo.AppendFormat(_T("  PublicIP=%s"), ipstr(uRemoteIP));
		}
		else
		{
			if (bDebug)
				strInfo.AppendFormat(_T("  ***UnkTag: %s"), tag.GetFullInfo());
			ASSERT(0);
		}
	}

	if (bDebug)
	{
		if (dataRecv.GetPosition() < dataRecv.GetLength())
			strInfo.AppendFormat(_T("  ***AddData: %u bytes"), (UINT)(dataRecv.GetLength() - dataRecv.GetPosition()));
		Debug(_T("%s\n"), strInfo);
	}

	if (uCacheIP == 0 || uCachePort == 0 || uPushId == 0 || isnulmd4(aucFileHash)){
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("Invalid PeerCacheQuery; %s"), DbgGetClientInfo());
		return false;
	}

	CKnownFile* pUploadFile = theApp.sharedfiles->GetFileByID(aucFileHash);
	if (pUploadFile == NULL){
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("PeerCacheQuery reqfile does not match ed2k reqfile; %s"), DbgGetClientInfo());
		return false;
	}

	if (m_pPCUpSocket != NULL)
	{
        SetPeerCacheUpState(PCUS_NONE);
		m_pPCUpSocket->Safe_Delete();
		ASSERT( m_pPCUpSocket == NULL );
	}
	m_pPCUpSocket = new CPeerCacheUpSocket(this);
	m_pPCUpSocket->SetTimeOut(GetPeerCacheSocketUploadTimeout());
	m_pPCUpSocket->Create();

	SOCKADDR_IN sockAddr = {0};
	sockAddr.sin_family = AF_INET;
	sockAddr.sin_port = htons(uCachePort);
	sockAddr.sin_addr.S_un.S_addr = uCacheIP;
	//Try to always tell the socket to WaitForOnConnect before you call Connect.
	m_pPCUpSocket->WaitForOnConnect();
	m_pPCUpSocket->Connect((SOCKADDR*)&sockAddr, sizeof sockAddr);

	CStringA strPCRequest;
	strPCRequest.AppendFormat("GIVE %u\r\n", uPushId);

	if (thePrefs.GetDebugClientTCPLevel() > 0){
		DebugSend("PeerCache-GIVE", this, pUploadFile->GetFileHash());
		Debug(_T("  %hs\n"), strPCRequest);
	}
	
	CRawPacket* pHttpPacket = new CRawPacket(strPCRequest);
	theStats.AddUpDataOverheadFileRequest(pHttpPacket->size);
	m_pPCUpSocket->SendPacket(pHttpPacket);
	m_pPCUpSocket->SetHttpState(HttpStateRecvExpected);
	m_bPeerCacheUpHit = false;
	SetPeerCacheUpState(PCUS_WAIT_CACHE_REPLY);
	//theApp.uploadBandwidthThrottler->AddToStandardList(0, m_pPCUpSocket);

	CSafeMemFile dataSend(128);
	dataSend.WriteUInt8(PCPCK_VERSION);
	dataSend.WriteUInt8(PCOP_RES);
	dataSend.WriteUInt8(3);
	CTag tagPushId(PCTAG_PUSHID, uPushId);
	tagPushId.WriteNewEd2kTag(&dataSend);
	CTag tagPublicIP(PCTAG_PUBLICIP, theApp.GetPublicIP());
	tagPublicIP.WriteNewEd2kTag(&dataSend);
	CTag tagFileId(PCTAG_FILEID, (BYTE*)aucFileHash);
	tagFileId.WriteNewEd2kTag(&dataSend);
	
	if (thePrefs.GetDebugClientTCPLevel() > 0){
		DebugSend("OP__PeerCacheAnswer", this, aucFileHash);
		Debug(_T("  PushId=%u  PublicIP=%s  FileId=%s\n"), tagPushId.GetInt(), ipstr(tagPublicIP.GetInt()), md4str(tagFileId.GetHash()));
	}
	
	Packet* pEd2kPacket = new Packet(&dataSend, OP_EMULEPROT, OP_PEERCACHE_ANSWER);
	theStats.AddUpDataOverheadFileRequest(pEd2kPacket->size);
	socket->SendPacket(pEd2kPacket);
	return true;
}
DWORD WINAPI CDoComInOut::ReadCallerThread(LPVOID pParam)
{
	while(TRUE)
	{
		CDoComInOut* pThis=(CDoComInOut*)pParam;
		char buf[1024]={0};
		DWORD dwReaded=0;//读到的大小
		BOOL bres=FALSE;
		DWORD dwErrorFlags;
		COMSTAT ComStat;
//		OVERLAPPED m_osRead;
//		memset(&m_osRead,0,sizeof(OVERLAPPED));
		CComInit* pComInit = CComInit::GetInstance();
		if(pComInit->m_hComWndScreen
			!=INVALID_HANDLE_VALUE)
		{	
			//////考虑枷锁
			ClearCommError(pComInit->m_hComWndScreen,&dwErrorFlags,&ComStat);
			Sleep(100);
			bres=ReadFile(pComInit->m_hComWndScreen,buf,1024,&dwReaded,&pComInit->m_read_os);
			if(!bres)
			{
				if(GetLastError()==ERROR_IO_PENDING)
				{
					while(!GetOverlappedResult(pComInit->m_hComWndScreen, &pComInit->m_read_os,&dwReaded,TRUE))
					{
						dwErrorFlags = GetLastError();
						if(dwErrorFlags == ERROR_IO_INCOMPLETE) continue;
						else{
							ClearCommError(pComInit->m_hComWndScreen,&dwErrorFlags, &ComStat ) ;
							break;
						}
					}
				}
			}
			if(dwReaded>0)//读到了
			{
#ifdef _DEBUG
				unsigned char uBuf[1024]={0};
				memcpy(uBuf,buf,dwReaded);
				CString temp;
				for(UINT i=0;i<dwReaded;i++)
				{
					temp+=_T("0x");
					temp.AppendFormat(_T("%08x"),uBuf[i]);
					temp+=_T(" ");
				}
				MyWriteConsole(temp);
				MyWriteConsole(_T("------------------------------------------"));
				CString strBuf;
				CCommonConvert convert;
				convert.CharToCstring(strBuf,buf);
				MyWriteConsole(strBuf);
				MyWriteConsole(_T("------------------------------------------"));
				CString strDwread;
				MyWriteConsole(strDwread);
#endif
				//////不是呼叫器和评价的数据,注:呼叫器评价器数据以0xff,0x68开始,0x16结束
				if(buf[0]==(char)0xA0 && buf[1]==(char)0x90 && buf[dwReaded-1]==(char)0xAA && 
					buf[dwReaded-2]==(char)0xA5)
				{
					int wndID = buf[2];//屏地址
#ifdef _DEBUG
					CString str;
					str.Format(_T("屏地址:%d发送成功"),wndID);
					MyWriteConsole(str);
#endif
					//条屏,综合屏数据,发送成功
				}
				else if((buf[0]!=(char)0xff&&buf[2]!=(char)0x68) && buf[dwReaded-1]!=(char)0x16)
				{
					//通屏数据
					if(!pThis->m_isDoneThroughInit)
					{
// #ifdef _DEBUG
// 						MyWriteConsole(_T("同频数据"));
// #endif
// 						SLZCWndScreen* pWindowScreen = SLZCWndScreen::GetInstance();
// 						pWindowScreen->AddThroughInitStr(buf,dwReaded);

					}
				}
				else
				{
					if(buf[5]>0xffffff80)
					{/////////平价器消息
						//返回给评价器信息
						char evabuf[8]={0};
						pThis->m_pSlzEvaluator->SystemSendToEva(evabuf,buf);
						WriteComMsg* pMsg = new WriteComMsg;;
 						memset(pMsg->buf,0,DATABUFLEN);
						memcpy(pMsg->buf,evabuf,8);
						pMsg->length = 8;
						pThis->AddWriteComMsg(pMsg);
						WaitForSingleObject(pThis->m_hWriteComThread,80);
						//判断评价超时并改值(当前一次评价没结束时,(同一个评价器)
						//又来一个评价,需要判断改值
						pThis->m_pSlzEvaluator->IsOutTimeAndReser(buf);
						//处理评价数据
						pThis->m_pSlzEvaluator->DoEvaltorMsg(buf);
					}
					else
					{//////////呼叫器消息
						//呼叫器消息
						WriteComMsg* pMsg = new WriteComMsg;
						memset(pMsg->buf,0,DATABUFLEN);
						memcpy(pMsg->buf,buf,dwReaded);
						pMsg->length = dwReaded;
						pThis->AddWriteComMsg(pMsg);
						WaitForSingleObject(pThis->m_hWriteComThread,80);
						pThis->m_pSlzCaller->DoReadMsg(dwReaded,buf);
					}	
				}
			}
			////////////////解锁
		}
		else
		{
			Sleep(20);
		}
	}
	return 0;
}
Exemple #21
0
// ----------------------------------------------------------------------------
//
void ActorSelectField::helpText( CString& help_text) {
    for ( ActorSelectField::EntryMap::iterator it=m_entries.begin(); it != m_entries.end(); ++it )
        help_text.AppendFormat( " %6s - %s\n", (*it).second.m_id, (*it).second.m_label );
}
GUID GetSystemProviderID(void)
{
	CComPtr<IVssBackupComponents> backupComponents; 
	
	OutputWriter::WriteLine(TEXT("Calling CreateVssBackupComponents in GetSystemProviderId")); 
	CHECK_HRESULT(::CreateVssBackupComponents(&backupComponents)); 

	OutputWriter::WriteLine(TEXT("Calling InitializeForBackup in GetSystemProviderId")); 
	CHECK_HRESULT(backupComponents->InitializeForBackup()); 

	// The following code for selecting the system proviider is necessary 
	// per http://forum.storagecraft.com/Community/forums/p/177/542.aspx#542
	// which is a totally awesome post
	OutputWriter::WriteLine(TEXT("Looking for the system VSS provider"));

	OutputWriter::WriteLine(TEXT("Calling backupComponents->Query(enum providers)"));
	CComPtr<IVssEnumObject> pEnum; 
	CHECK_HRESULT(backupComponents->Query(GUID_NULL, VSS_OBJECT_NONE, VSS_OBJECT_PROVIDER, &pEnum));

	GUID systemProviderId = GUID_NULL;
	VSS_OBJECT_PROP prop;
	ULONG nFetched;
	do 
	{
		OutputWriter::WriteLine(TEXT("Calling IVssEnumObject::Next"));
		HRESULT hr = pEnum->Next(1, &prop, &nFetched);

		CString message;
		message.AppendFormat(TEXT("Examining provider %s to see if it's the system provider..."), prop.Obj.Prov.m_pwszProviderName);
		OutputWriter::WriteLine(message);

		if (hr == S_OK)
		{
			if (prop.Obj.Prov.m_eProviderType == VSS_PROV_SYSTEM)
			{
				systemProviderId = prop.Obj.Prov.m_ProviderId; 
				OutputWriter::WriteLine(TEXT("...and it is."));
				break;
			}
		}
		else if (hr == S_FALSE)
		{
			OutputWriter::WriteLine(TEXT("...but it's not."));
			break;
		}
		else
		{
			throw new CComException(hr, __FILE__, __LINE__);
		}
	} while (true);

	if (systemProviderId.Data1 == GUID_NULL.Data1 && 
		systemProviderId.Data2 == GUID_NULL.Data2 &&
		systemProviderId.Data3 == GUID_NULL.Data3 &&
		systemProviderId.Data4 == GUID_NULL.Data4)
	{
		throw new CShadowSpawnException(TEXT("Unable to locate the system snapshot provider."));
	}

	return systemProviderId;
}
Exemple #23
0
HRESULT STDMETHODCALLTYPE CProvider::GetCommitMessage2( 
	/* [in] */ HWND hParentWnd,
	/* [in] */ BSTR parameters,
	/* [in] */ BSTR commonURL,
	/* [in] */ BSTR commonRoot,
	/* [in] */ SAFEARRAY * pathList,
	/* [in] */ BSTR originalMessage,
	/* [retval][out] */ BSTR *newMessage)
{
	USES_CONVERSION;

	if (commonURL)
	{
		// do something with the common root url
		// if necessary
	}

	parameters_t params = ParseParameters(parameters);
	CString commandLine = params[CString("CommandLine")];

	if (commandLine.IsEmpty())
	{
		MessageBox(hParentWnd, _T("CommandLine parameter is empty"), _T("ExampleAtlPlugin"), MB_OK | MB_ICONERROR);
		return S_OK;
	}

	TCHAR szTempPath[MAX_PATH];
	GetTempPath(ARRAYSIZE(szTempPath), szTempPath);

	// Create a temporary file to hold the path list, and write the list to the file.
	TCHAR szPathListTempFile[MAX_PATH];
	GetTempFileName(szTempPath, _T("svn"), 0, szPathListTempFile);

	DWORD bytesWritten;
	HANDLE hPathListFile = CreateFile(szPathListTempFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);

	LONG a, b;
	if (FAILED(SafeArrayGetLBound(pathList, 1, &a)) || (FAILED(SafeArrayGetUBound(pathList, 1, &b))))
		return E_FAIL;

	for (LONG i = a; i <= b; ++i)
	{
		BSTR path = NULL;
		SafeArrayGetElement(pathList, &i, &path);

		CStringA line = OLE2A(path);
		line += "\r\n";

		WriteFile(hPathListFile, line, line.GetLength(), &bytesWritten, NULL);
	}

	CloseHandle(hPathListFile);

	TCHAR szOriginalMessageTempFile[MAX_PATH];
	GetTempFileName(szTempPath, _T("svn"), 0, szOriginalMessageTempFile);

	HANDLE hOriginalMessageFile = CreateFile(szOriginalMessageTempFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);

	CStringA temp = OLE2A(originalMessage);
	WriteFile(hOriginalMessageFile, temp, temp.GetLength(), &bytesWritten, NULL);

	CloseHandle(hOriginalMessageFile);

	commandLine.AppendFormat(_T(" \"%s\" \"%ls\" \"%s\""), szPathListTempFile, commonRoot, szOriginalMessageTempFile);

	CString message = originalMessage;
	CWaitDialog dlg(commandLine);
	if (dlg.DoModal() == IDOK)
	{
		HANDLE hOrig = CreateFile(szOriginalMessageTempFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
		DWORD cb = GetFileSize(hOrig, NULL);
		BYTE *buffer = (BYTE *)malloc(cb + 1);
		memset(buffer, 0, cb + 1);
		DWORD bytesRead;
		ReadFile(hOrig, buffer, cb, &bytesRead, NULL);
		CloseHandle(hOrig);

		message = A2T((const char *)buffer);
	}

	DeleteFile(szPathListTempFile);
	DeleteFile(szOriginalMessageTempFile);

	*newMessage = message.AllocSysString();
	return S_OK;
}
DWORD PageUpgrade::UpgradeAsync() {
  // upload upgrade file.
  DeviceProxy *proxy = DeviceProxy::GetInstance();
  ParameterBlock *modelBlock = WorkingParameters::GetInstance()->GetCurrentModelParameters();
  ASSERT(modelBlock != NULL && !modelBlock->IsNull());
  ParameterBlock firmwareBlock = modelBlock->SelectBlock(_T("Firmware"));
  CString firmwareVersion = firmwareBlock.GetStringParameter(_T("version"), NULL);
  TCHAR appDataPath[MAX_PATH];
  GetAppDataPath(appDataPath);
  PathAddBackslash(appDataPath);
  _tcscat(appDataPath, _T("config\\"));
  CString firmwareFilePath = appDataPath;
  firmwareFilePath.AppendFormat(_T("firmware_%d.dat"), modelBlock->GetIntParameter(_T("id"), -1));

  ::PostMessage(m_hWnd, WM_UPGRADE_STEP, UPGRADE_UPLOAD, 0);
  if (!proxy->Upgrade(firmwareFilePath, firmwareVersion, &progressTracker_)) {
    int error = GetLastError();
    
    DebugLogger::GetInstance()->Upgrade(firmwareVersion, error);

    ::PostMessage(m_hWnd, WM_UPGRADE_STEP_COMPLETED, UPGRADE_UPLOAD, FALSE);
    ::PostMessage(m_hWnd, WM_UPGRADE_COMPLETED, FALSE, error);

    return -1;
  } else {
    DebugLogger::GetInstance()->Upgrade(firmwareVersion, 0);
  }

  ::PostMessage(m_hWnd, WM_UPGRADE_STEP_COMPLETED, UPGRADE_UPLOAD, TRUE);  
  // update debug state.
  ::PostMessage(m_hWnd, WM_UPGRADE_STEP, UPGRADE_UPDATE_STATE, 0);
  if (!proxy->UpdateDebugState(DEBUG_UPGRADE_DONE, 0)) {    
    int error = GetLastError();
    ::PostMessage(m_hWnd, WM_UPGRADE_STEP_COMPLETED, UPGRADE_UPDATE_STATE, FALSE);
    ::PostMessage(m_hWnd, WM_UPGRADE_COMPLETED, FALSE, error);
    return -1;
  }
  ::PostMessage(m_hWnd, WM_UPGRADE_STEP_COMPLETED, UPGRADE_UPDATE_STATE, TRUE);
  // restart device.
  ::PostMessage(m_hWnd, WM_UPGRADE_STEP, UPGRADE_RESTART, 0);
  if (!proxy->Restart()) {
    int error = GetLastError();
    ::PostMessage(m_hWnd, WM_UPGRADE_STEP_COMPLETED, UPGRADE_RESTART, FALSE);
    ::PostMessage(m_hWnd, WM_UPGRADE_COMPLETED, FALSE, error);
    return -1;
  }
  // wait for restart.
  while (1) {
    if (!proxy->Echo()) {
      // device is shutdown.
      break;
    }
    Sleep(500);
  }
  
  Sleep(2000);

  ::PostMessage(m_hWnd, WM_UPGRADE_STEP_COMPLETED, UPGRADE_RESTART, TRUE);
  ::PostMessage(m_hWnd, WM_UPGRADE_COMPLETED, TRUE, 0);

  proxy->Disconnect();

  //CString deviceIP = parameters->GetDeviceIP();
  //int devicePort = parameters->GetDevicePort();
  //while (!upgradeThread_.IsInterrupted()) {
  //  // device is started.
  //  if (proxy->Connect(deviceIP, devicePort)) {
  //    break;
  //  }
  //  Sleep(500);
  //}

  //::PostMessage(m_hWnd, WM_UPGRADE_STEP_COMPLETED, UPGRADE_RESTART, TRUE);
  //::PostMessage(m_hWnd, WM_UPGRADE_COMPLETED, TRUE, 0);

  return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
    //::DebugBreak(); 

    OutputWriter::SetVerbosityLevel(VERBOSITY_LEVEL_NORMAL); 
    OutputWriter::WriteLine(TEXT("ShadowSpawn (c) 2011 Craig Andera. [email protected]"), 
        VERBOSITY_THRESHOLD_UNLESS_SILENT); 
    OutputWriter::WriteLine(TEXT(""), VERBOSITY_THRESHOLD_UNLESS_SILENT); 

    bool bAbnormalAbort = true; 
    DWORD exitCode = 0;

    int fileCount = 0; 
    LONGLONG byteCount = 0; 
    int directoryCount = 0; 
    int skipCount = 0; 
    SYSTEMTIME startTime;
    try
    {
        COptions options = COptions::Parse(argc, argv); 

        if (options.get_Debug())
        {
            ::DebugBreak(); 
        }

        OutputWriter::SetVerbosityLevel((VERBOSITY_LEVEL) options.get_VerbosityLevel()); 

		for (int i = 0; i < argc; ++i)
		{
			CString message; 
			message.AppendFormat(TEXT("Argument %d: %s"), i, argv[i]);
			OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_IF_VERBOSE);
		}

        if (!Utilities::DirectoryExists(options.get_Source()))
        {
            CString message;
            message.AppendFormat(TEXT("Source path is not an existing directory: %s"), options.get_Source());
            throw new CShadowSpawnException(message); 
        }

        OutputWriter::WriteLine(TEXT("Calling CoInitialize")); 
        CHECK_HRESULT(::CoInitialize(NULL)); 
        CHECK_HRESULT(
            ::CoInitializeSecurity(
            NULL, 
            -1, 
            NULL, 
            NULL, 
            RPC_C_AUTHN_LEVEL_PKT_PRIVACY, 
            RPC_C_IMP_LEVEL_IDENTIFY, 
            NULL, 
            EOAC_NONE, 
            NULL)); 

        ::GetSystemTime(&startTime); 
        CString startTimeString; 
        Utilities::FormatDateTime(&startTime, TEXT(" "), false, startTimeString); 

        CString message; 
        message.AppendFormat(TEXT("Shadowing %s at %s"), 
            options.get_Source(), 
            options.get_Device()); 
        OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL); 

		GUID systemProviderId = GetSystemProviderID();

        OutputWriter::WriteLine(TEXT("Calling CreateVssBackupComponents")); 
        CHECK_HRESULT(::CreateVssBackupComponents(&pBackupComponents)); 
		
		OutputWriter::WriteLine(TEXT("Calling InitializeForBackup")); 
        CHECK_HRESULT(pBackupComponents->InitializeForBackup()); 

        CComPtr<IVssAsync> pWriterMetadataStatus; 

        OutputWriter::WriteLine(TEXT("Calling GatherWriterMetadata")); 
        CHECK_HRESULT(pBackupComponents->GatherWriterMetadata(&pWriterMetadataStatus)); 

        OutputWriter::WriteLine(TEXT("Waiting for call to GatherWriterMetadata to finish...")); 
        CHECK_HRESULT(pWriterMetadataStatus->Wait()); 

        HRESULT hrGatherStatus; 
        OutputWriter::WriteLine(TEXT("Calling QueryStatus for GatherWriterMetadata")); 
        CHECK_HRESULT(pWriterMetadataStatus->QueryStatus(&hrGatherStatus, NULL)); 

        if (hrGatherStatus == VSS_S_ASYNC_CANCELLED)
        {
            throw new CShadowSpawnException(L"GatherWriterMetadata was cancelled."); 
        }

		OutputWriter::WriteLine(TEXT("Call to GatherWriterMetadata finished.")); 


        OutputWriter::WriteLine(TEXT("Calling GetWriterMetadataCount")); 

        vector<CWriter> writers;

        UINT cWriters; 
        CHECK_HRESULT(pBackupComponents->GetWriterMetadataCount(&cWriters)); 

        for (UINT iWriter = 0; iWriter < cWriters; ++iWriter)
        {
            CWriter writer; 
            CComPtr<IVssExamineWriterMetadata> pExamineWriterMetadata; 
            GUID id; 
            OutputWriter::WriteLine(TEXT("Calling GetWriterMetadata")); 
            CHECK_HRESULT(pBackupComponents->GetWriterMetadata(iWriter, &id, &pExamineWriterMetadata)); 
            GUID idInstance; 
            GUID idWriter; 
            BSTR bstrWriterName;
            VSS_USAGE_TYPE usage; 
            VSS_SOURCE_TYPE source; 
            CHECK_HRESULT(pExamineWriterMetadata->GetIdentity(&idInstance, &idWriter, &bstrWriterName, &usage, &source)); 

            writer.set_InstanceId(idInstance); 
            writer.set_Name(bstrWriterName); 
            writer.set_WriterId(idWriter); 

            CComBSTR writerName(bstrWriterName); 
            CString message; 
            message.AppendFormat(TEXT("Writer %d named %s"), iWriter, (LPCTSTR) writerName); 
            OutputWriter::WriteLine(message); 

            UINT cIncludeFiles;
            UINT cExcludeFiles; 
            UINT cComponents; 
            CHECK_HRESULT(pExamineWriterMetadata->GetFileCounts(&cIncludeFiles, &cExcludeFiles, &cComponents)); 

            message.Empty(); 
            message.AppendFormat(TEXT("Writer has %d components"), cComponents); 
            OutputWriter::WriteLine(message); 

            for (UINT iComponent = 0; iComponent < cComponents; ++iComponent)
            {
                CWriterComponent component; 

                CComPtr<IVssWMComponent> pComponent; 
                CHECK_HRESULT(pExamineWriterMetadata->GetComponent(iComponent, &pComponent)); 

                PVSSCOMPONENTINFO pComponentInfo; 
                CHECK_HRESULT(pComponent->GetComponentInfo(&pComponentInfo)); 

                CString message; 
                message.AppendFormat(TEXT("Component %d is named %s, has a path of %s, and is %sselectable for backup. %d files, %d databases, %d log files."), 
                    iComponent,
                    pComponentInfo->bstrComponentName, 
                    pComponentInfo->bstrLogicalPath, 
                    pComponentInfo->bSelectable ? TEXT("") : TEXT("not "), 
                    pComponentInfo->cFileCount, 
                    pComponentInfo->cDatabases,
                    pComponentInfo->cLogFiles); 
                OutputWriter::WriteLine(message); 

                component.set_LogicalPath(pComponentInfo->bstrLogicalPath); 
                component.set_SelectableForBackup(pComponentInfo->bSelectable); 
                component.set_Writer(iWriter); 
                component.set_Name(pComponentInfo->bstrComponentName);
                component.set_Type(pComponentInfo->type);

                for (UINT iFile = 0; iFile < pComponentInfo->cFileCount; ++iFile)
                {
                    CComPtr<IVssWMFiledesc> pFileDesc; 
                    CHECK_HRESULT(pComponent->GetFile(iFile, &pFileDesc)); 

                    CComBSTR bstrPath; 
                    CHECK_HRESULT(pFileDesc->GetPath(&bstrPath)); 

                    CComBSTR bstrFileSpec; 
                    CHECK_HRESULT(pFileDesc->GetFilespec(&bstrFileSpec)); 

                    CString message; 
                    message.AppendFormat(TEXT("File %d has path %s\\%s"), iFile, bstrPath, bstrFileSpec); 
                    OutputWriter::WriteLine(message); 
                }

                for (UINT iDatabase = 0; iDatabase < pComponentInfo->cDatabases; ++iDatabase)
                {
                    CComPtr<IVssWMFiledesc> pFileDesc; 
                    CHECK_HRESULT(pComponent->GetDatabaseFile(iDatabase, &pFileDesc)); 

                    CComBSTR bstrPath; 
                    CHECK_HRESULT(pFileDesc->GetPath(&bstrPath)); 

                    CComBSTR bstrFileSpec; 
                    CHECK_HRESULT(pFileDesc->GetFilespec(&bstrFileSpec)); 

                    CString message; 
                    message.AppendFormat(TEXT("Database file %d has path %s\\%s"), iDatabase, bstrPath, bstrFileSpec); 
                    OutputWriter::WriteLine(message); 
                }

                for (UINT iDatabaseLogFile = 0; iDatabaseLogFile < pComponentInfo->cLogFiles; ++iDatabaseLogFile)
                {
                    CComPtr<IVssWMFiledesc> pFileDesc; 
                    CHECK_HRESULT(pComponent->GetDatabaseLogFile(iDatabaseLogFile, &pFileDesc)); 

                    CComBSTR bstrPath; 
                    CHECK_HRESULT(pFileDesc->GetPath(&bstrPath)); 

                    CComBSTR bstrFileSpec; 
                    CHECK_HRESULT(pFileDesc->GetFilespec(&bstrFileSpec)); 

                    CString message; 
                    message.AppendFormat(TEXT("Database log file %d has path %s\\%s"), iDatabaseLogFile, bstrPath, bstrFileSpec); 
                    OutputWriter::WriteLine(message); 
                }

                CHECK_HRESULT(pComponent->FreeComponentInfo(pComponentInfo)); 

                writer.get_Components().push_back(component); 

            }

            writer.ComputeComponentTree(); 

            for (unsigned int iComponent = 0; iComponent < writer.get_Components().size(); ++iComponent)
            {
                CWriterComponent& component = writer.get_Components()[iComponent]; 
                CString message; 
                message.AppendFormat(TEXT("Component %d has name %s, path %s, is %sselectable for backup, and has parent %s"), 
                    iComponent, 
                    component.get_Name(), 
                    component.get_LogicalPath(), 
                    component.get_SelectableForBackup() ? TEXT("") : TEXT("not "), 
                    component.get_Parent() == NULL ? TEXT("(no parent)") : component.get_Parent()->get_Name()); 
                OutputWriter::WriteLine(message); 
            }

            writers.push_back(writer); 
        }

        OutputWriter::WriteLine(TEXT("Calling StartSnapshotSet")); 
        CHECK_HRESULT(pBackupComponents->StartSnapshotSet(&snapshotSetId));

        OutputWriter::WriteLine(TEXT("Calling GetVolumePathName")); 
        WCHAR wszVolumePathName[MAX_PATH]; 
        BOOL bWorked = ::GetVolumePathName(options.get_Source(), wszVolumePathName, MAX_PATH); 

        if (!bWorked)
        {
            DWORD error = ::GetLastError(); 
            CString errorMessage; 
            Utilities::FormatErrorMessage(error, errorMessage); 
            CString message; 
            message.AppendFormat(TEXT("There was an error retrieving the volume name from the path. Path: %s Error: %s"), 
                options.get_Source(), errorMessage); 
            throw new CShadowSpawnException(message.GetString()); 
        }

		
        OutputWriter::WriteLine(TEXT("Calling AddToSnapshotSet")); 
        GUID snapshotId; 
        CHECK_HRESULT(pBackupComponents->AddToSnapshotSet(wszVolumePathName, systemProviderId, &snapshotId)); 

        for (unsigned int iWriter = 0; iWriter < writers.size(); ++iWriter)
        {
            CWriter writer = writers[iWriter];

            CString message; 
            message.AppendFormat(TEXT("Adding components to snapshot set for writer %s"), writer.get_Name()); 
            OutputWriter::WriteLine(message); 
            for (unsigned int iComponent = 0; iComponent < writer.get_Components().size(); ++iComponent)
            {
                CWriterComponent component = writer.get_Components()[iComponent];

                if (ShouldAddComponent(component))
                {
                    CString message; 
                    message.AppendFormat(TEXT("Adding component %s (%s) from writer %s"), 
                        component.get_Name(), 
                        component.get_LogicalPath(), 
                        writer.get_Name()); 
                    OutputWriter::WriteLine(message); 
                    CHECK_HRESULT(pBackupComponents->AddComponent(
                        writer.get_InstanceId(), 
                        writer.get_WriterId(),
                        component.get_Type(), 
                        component.get_LogicalPath(), 
                        component.get_Name()
                        ));
                }
                else
                {
                    CString message; 
                    message.AppendFormat(TEXT("Not adding component %s from writer %s."), 
                        component.get_Name(), writer.get_Name()); 
                    OutputWriter::WriteLine(message); 
                }
            }
        }

        OutputWriter::WriteLine(TEXT("Calling SetBackupState")); 
        CHECK_HRESULT(pBackupComponents->SetBackupState(TRUE, FALSE, options.get_BackupType(), FALSE)); 

        OutputWriter::WriteLine(TEXT("Calling PrepareForBackup")); 
        CComPtr<IVssAsync> pPrepareForBackupResults; 
        CHECK_HRESULT(pBackupComponents->PrepareForBackup(&pPrepareForBackupResults)); 

        OutputWriter::WriteLine(TEXT("Waiting for call to PrepareForBackup to finish...")); 
        CHECK_HRESULT(pPrepareForBackupResults->Wait()); 

        HRESULT hrPrepareForBackupResults; 
        CHECK_HRESULT(pPrepareForBackupResults->QueryStatus(&hrPrepareForBackupResults, NULL)); 

        if (hrPrepareForBackupResults != VSS_S_ASYNC_FINISHED)
        {
            throw new CShadowSpawnException(TEXT("Prepare for backup failed.")); 
        }

        OutputWriter::WriteLine(TEXT("Call to PrepareForBackup finished.")); 
		
        SYSTEMTIME snapshotTime; 
        ::GetSystemTime(&snapshotTime); 

        bWorked = ::SetConsoleCtrlHandler(CtrlHandler, TRUE); 

        if (!bWorked)
        {
            OutputWriter::WriteLine(TEXT("Unable to set control handler. Ctrl-C and Ctrl-Break may have undesirable results."), 
                VERBOSITY_THRESHOLD_NORMAL);
        }

        if (!options.get_Simulate())
        {
            OutputWriter::WriteLine(TEXT("Calling DoSnapshotSet")); 
            CComPtr<IVssAsync> pDoSnapshotSetResults;
            CHECK_HRESULT(pBackupComponents->DoSnapshotSet(&pDoSnapshotSetResults)); 

            OutputWriter::WriteLine(TEXT("Waiting for call to DoSnapshotSet to finish...")); 
		   
            CHECK_HRESULT(pDoSnapshotSetResults->Wait());

            bSnapshotCreated = true; 

             HRESULT hrDoSnapshotSetResults; 
            CHECK_HRESULT(pDoSnapshotSetResults->QueryStatus(&hrDoSnapshotSetResults, NULL)); 

            if (hrDoSnapshotSetResults != VSS_S_ASYNC_FINISHED)
            {
                throw new CShadowSpawnException(L"DoSnapshotSet failed."); 
            }

	        OutputWriter::WriteLine(TEXT("Call to DoSnapshotSet finished.")); 

            OutputWriter::WriteLine(TEXT("Calling GetSnapshotProperties")); 
            VSS_SNAPSHOT_PROP snapshotProperties; 
            CHECK_HRESULT(pBackupComponents->GetSnapshotProperties(snapshotId, &snapshotProperties));

            OutputWriter::WriteLine(TEXT("Calling CalculateSourcePath")); 
            // TODO: We'll eventually have to deal with mount points
            CString wszSource;
            CalculateSourcePath(
                snapshotProperties.m_pwszSnapshotDeviceObject, 
                options.get_Source(),
                wszVolumePathName, 
                wszSource
                );

            OutputWriter::WriteLine(TEXT("Calling DefineDosDevice to mount device.")); 
            if (0 == wszSource.Find(TEXT("\\\\?\\GLOBALROOT")))
            {
                wszSource = wszSource.Mid(_tcslen(TEXT("\\\\?\\GLOBALROOT")));
            }
            bWorked = DefineDosDevice(DDD_RAW_TARGET_PATH, options.get_Device(), wszSource); 
            if (!bWorked)
            {
                DWORD error = ::GetLastError(); 
                CString errorMessage; 
                Utilities::FormatErrorMessage(error, errorMessage); 
                CString message; 
                message.AppendFormat(TEXT("There was an error calling DefineDosDevice when mounting a device. Error: %s"), errorMessage); 
                throw new CShadowSpawnException(message.GetString()); 
            }
            mountedDevice = options.get_Device();

            STARTUPINFO startUpInfo;
            memset(&startUpInfo, 0, sizeof(startUpInfo));
            startUpInfo.cb = sizeof(startUpInfo);

            PROCESS_INFORMATION processInformation;
            size_t commandLength = options.get_Command().size();
            wchar_t* copyCommand = (wchar_t*)_alloca((commandLength+1)*sizeof(wchar_t));
            options.get_Command().copy(copyCommand, commandLength);
            copyCommand[commandLength] = L'\0';

            message.Format(TEXT("Launching command: %s"), options.get_Command().c_str());
            OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL); 
            bWorked = CreateProcess(NULL, copyCommand, NULL, NULL, FALSE, 0, NULL, 
                                    NULL, &startUpInfo, &processInformation);
            if (!bWorked)
            {
                DWORD error = ::GetLastError(); 
                CString errorMessage; 
                Utilities::FormatErrorMessage(error, errorMessage); 
                CString message; 
                message.AppendFormat(TEXT("There was an error calling CreateProcess. Process: %s Error: %s"), 
                    options.get_Command().c_str(), errorMessage); 
                throw new CShadowSpawnException(message.GetString()); 
            }

            WaitForSingleObject(processInformation.hProcess, INFINITE);

            bWorked = GetExitCodeProcess(processInformation.hProcess, &exitCode);
            if (!bWorked)
            {
                DWORD error = ::GetLastError(); 
                CString errorMessage; 
                Utilities::FormatErrorMessage(error, errorMessage); 
                CString message; 
                message.AppendFormat(TEXT("There was an error calling GetExitCodeProcess. Error: %s"), errorMessage); 
                throw new CShadowSpawnException(message.GetString()); 
            }

            CloseHandle(processInformation.hThread);
            CloseHandle(processInformation.hProcess);

            message.Format(TEXT("Launched command finished with exit code: %d."), exitCode);
            OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL); 

            OutputWriter::WriteLine(TEXT("Calling DefineDosDevice to remove device.")); 
            bWorked = DefineDosDevice(DDD_REMOVE_DEFINITION, options.get_Device(), NULL); 
            if (!bWorked)
            {
                DWORD error = ::GetLastError(); 
                CString errorMessage; 
                Utilities::FormatErrorMessage(error, errorMessage); 
                CString message; 
                message.AppendFormat(TEXT("There was an error calling DefineDosDevice. Error: %s"), errorMessage); 
                throw new CShadowSpawnException(message.GetString()); 
            }
            mountedDevice.Empty();

            OutputWriter::WriteLine(TEXT("Calling BackupComplete")); 
            CComPtr<IVssAsync> pBackupCompleteResults; 
            CHECK_HRESULT(pBackupComponents->BackupComplete(&pBackupCompleteResults)); 

            OutputWriter::WriteLine(TEXT("Waiting for call to BackupComplete to finish...")); 
			CHECK_HRESULT(pBackupCompleteResults->Wait());

            HRESULT hrBackupCompleteResults; 
            CHECK_HRESULT(pBackupCompleteResults->QueryStatus(&hrBackupCompleteResults, NULL)); 

            if (hrBackupCompleteResults != VSS_S_ASYNC_FINISHED)
            {
                throw new CShadowSpawnException(TEXT("Completion of backup failed.")); 
            }

            OutputWriter::WriteLine(TEXT("Call to BackupComplete finished.")); 

            bAbnormalAbort = false; 
        }
    }
    catch (CComException* e)
    {
        Cleanup(bAbnormalAbort, bSnapshotCreated, mountedDevice, pBackupComponents, snapshotSetId);
        CString message; 
        CString file; 
        e->get_File(file); 
        message.Format(TEXT("There was a COM failure 0x%x - %s (%d)"), 
            e->get_Hresult(), file, e->get_Line()); 
        OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_UNLESS_SILENT); 
        return 1; 
    }
    catch (CShadowSpawnException* e)
    {
        Cleanup(bAbnormalAbort, bSnapshotCreated, mountedDevice, pBackupComponents, snapshotSetId);
        OutputWriter::WriteLine(e->get_Message(), VERBOSITY_THRESHOLD_UNLESS_SILENT); 
        return 1; 
    }
    catch (CParseOptionsException* e)
    {
        Cleanup(bAbnormalAbort, bSnapshotCreated, mountedDevice, pBackupComponents, snapshotSetId);
        CString message; 
        message.AppendFormat(TEXT("Error: %s\n"), e->get_Message()); 
        OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_UNLESS_SILENT);
        OutputWriter::WriteLine(COptions::get_Usage(), VERBOSITY_THRESHOLD_UNLESS_SILENT); 
        return 2; 
    }

    Cleanup(false, bSnapshotCreated, mountedDevice, pBackupComponents, snapshotSetId);
    OutputWriter::WriteLine(TEXT("Shadowing successfully completed."), VERBOSITY_THRESHOLD_NORMAL); 
    if (exitCode != 0)
    {
        return (0x8000 | exitCode);
    }

    return 0;
}
Exemple #26
0
void ProcessDirectory(LPCTSTR srcbase, CDirectoryAction& action, LPCTSTR directory, bool recursive, wregex* ignorePattern)
{
	WIN32_FIND_DATA findData;
	HANDLE hFindHandle;

	CString srcdir;
	Utilities::CombinePath(srcbase, directory, srcdir);

	if (!ShouldProcess(ignorePattern, srcdir))
	{
		return;
	}

	action.VisitDirectoryInitial(directory);

	CString pattern;
	Utilities::CombinePath(srcdir, TEXT("*"), pattern);

	Utilities::FixLongFilenames(pattern);

	hFindHandle = ::FindFirstFile(pattern, &findData);
	if (hFindHandle != INVALID_HANDLE_VALUE)
	{
		BOOL done = false;
		while (!done)
		{
			if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
			{
				if (recursive)
				{
					if (Utilities::AreEqual(findData.cFileName, L".") || Utilities::AreEqual(findData.cFileName, L".."))
					{
						// Do nothing
					}
					else
					{
						CString subdirectory;
						Utilities::CombinePath(directory, findData.cFileName, subdirectory);
						if (!ShouldProcess(ignorePattern, srcbase, subdirectory))
						{
							continue;
						}
						ProcessDirectory(srcbase, action, subdirectory, recursive, ignorePattern);
					}
				}
			}
			else
			{
				CString file;
				Utilities::CombinePath(directory, findData.cFileName, file);
				if (!ShouldProcess(ignorePattern, srcbase, file)) continue;
				action.VisitFile(file);
			}

			BOOL worked = ::FindNextFile(hFindHandle, &findData);

			if (!worked)
			{
				int error = GetLastError();

				if (error == ERROR_NO_MORE_FILES)
				{
					done = true;
				}
				else
				{
					CString errorMessage;
					Utilities::FormatErrorMessage(error, errorMessage);
					CString message;
					message.AppendFormat(TEXT("There was an error calling FindNextFile. Path: %s Error: %s"),
						pattern, errorMessage);
					throw new CVSSCopyException(message.GetString());
				}
			}
		}
	}
	else
	{
		int error = GetLastError();

		if (error != ERROR_FILE_NOT_FOUND)
		{
			CString errorMessage;
			Utilities::FormatErrorMessage(error, errorMessage);
			CString message;
			message.AppendFormat(TEXT("There was an error calling FindFirstFile. Path: %s Error: %s"),
				pattern, errorMessage);
			throw new CVSSCopyException(message.GetString());
		}
	}
	::FindClose(hFindHandle);


	// Important to put this after FindClose, since otherwise there's still an 
	// open handle to the directory, and that can interfere with (e.g.) directory
	// deletion
	action.VisitDirectoryFinal(directory);

}
Exemple #27
0
void startBackup(COptions options)
{
	GUID snapshotSetId = GUID_NULL;
	bool bSnapshotCreated = false;
	bool bAbnormalAbort = true;
	CComPtr<IVssBackupComponents> pBackupComponents;

	int fileCount = 0;
	LONGLONG byteCount = 0;
	int directoryCount = 0;
	int skipCount = 0;
	SYSTEMTIME startTime;
	
	try
	{
		OutputWriter::SetVerbosityLevel((VERBOSITY_LEVEL)options.get_VerbosityLevel());

		//for (int i = 0; i < argc; ++i)
		//{
		//	CString message;
		//	message.AppendFormat(TEXT("Argument %d: %s"), i, argv[i]);
		//	OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_IF_VERBOSE);
		//}

		OutputWriter::WriteLine(TEXT("Calling CoInitialize"));
		CHECK_HRESULT(::CoInitialize(NULL));
		CHECK_HRESULT(
			::CoInitializeSecurity(
			NULL,
			-1,
			NULL,
			NULL,
			RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
			RPC_C_IMP_LEVEL_IDENTIFY,
			NULL,
			EOAC_NONE,
			NULL));

		::GetSystemTime(&startTime);
		CString startTimeString;
		Utilities::FormatDateTime(&startTime, TEXT(" "), false, startTimeString);

		CString message;
		message.AppendFormat(TEXT("Starting a %s copy from %s to %s"),
			options.get_BackupType() == VSS_BT_FULL ? TEXT("full") : TEXT("incremental"),
			options.get_Source(),
			options.get_Destination());
		OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL);

			if (options.get_ClearDestination())
			{
				if (!Utilities::DirectoryExists(options.get_Destination()))
				{
					CString message;
					message.AppendFormat(TEXT("Skipping recursive delete of destination directory %s because it appears not to exist."),
						options.get_Destination());
					OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL);
				}
				else
				{
					CString message;
					message.AppendFormat(TEXT("Recursively deleting destination directory %s."),
						options.get_Destination());
					OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL);

					bool doDelete = options.get_AcceptAll();

					if (!doDelete)
					{
						if (Confirm(message))
						{
							doDelete = true;
						}
						else
						{
							OutputWriter::WriteLine(TEXT("Aborting backup."), VERBOSITY_THRESHOLD_NORMAL);
							return;
						}
					}

					if (doDelete)
					{
						DeleteRecursive(options.get_Destination(), options.get_IgnorePattern());
					}
				}
			}

			CBackupState backupState;

			LPSYSTEMTIME lastBackupTime;

			if (options.get_BackupType() == VSS_BT_INCREMENTAL)
			{
				backupState.Load(options.get_StateFile());

				LPSYSTEMTIME lastFullBackupTime = backupState.get_LastFullBackupTime();
				LPSYSTEMTIME lastIncrementalBackupTime = backupState.get_LastIncrementalBackupTime();
				if (lastIncrementalBackupTime != NULL)
				{
					lastBackupTime = lastIncrementalBackupTime;
				}
				else
				{
					lastBackupTime = lastFullBackupTime;
				}
			}


			OutputWriter::WriteLine(TEXT("Calling CreateVssBackupComponents"));
			CHECK_HRESULT(::CreateVssBackupComponents(&pBackupComponents));

			OutputWriter::WriteLine(TEXT("Calling InitializeForBackup"));
			CHECK_HRESULT(pBackupComponents->InitializeForBackup());

			CComPtr<IVssAsync> pWriterMetadataStatus;

			OutputWriter::WriteLine(TEXT("Calling GatherWriterMetadata"));
			CHECK_HRESULT(pBackupComponents->GatherWriterMetadata(&pWriterMetadataStatus));

			OutputWriter::WriteLine(TEXT("Waiting for call to GatherWriterMetadata to finish..."));
			CHECK_HRESULT(pWriterMetadataStatus->Wait());

			HRESULT hrGatherStatus;
			OutputWriter::WriteLine(TEXT("Calling QueryStatus for GatherWriterMetadata"));
			CHECK_HRESULT(pWriterMetadataStatus->QueryStatus(&hrGatherStatus, NULL));

			if (hrGatherStatus == VSS_S_ASYNC_CANCELLED)
			{
				throw new CVSSCopyException(L"GatherWriterMetadata was cancelled.");
			}

			OutputWriter::WriteLine(TEXT("Call to GatherWriterMetadata finished."));


			OutputWriter::WriteLine(TEXT("Calling GetWriterMetadataCount"));

			vector<CWriter> writers;

			UINT cWriters;
			CHECK_HRESULT(pBackupComponents->GetWriterMetadataCount(&cWriters));

			for (UINT iWriter = 0; iWriter < cWriters; ++iWriter)
			{
				CWriter writer;
				CComPtr<IVssExamineWriterMetadata> pExamineWriterMetadata;
				GUID id;
				OutputWriter::WriteLine(TEXT("Calling GetWriterMetadata"));
				CHECK_HRESULT(pBackupComponents->GetWriterMetadata(iWriter, &id, &pExamineWriterMetadata));
				GUID idInstance;
				GUID idWriter;
				BSTR bstrWriterName;
				VSS_USAGE_TYPE usage;
				VSS_SOURCE_TYPE source;
				CHECK_HRESULT(pExamineWriterMetadata->GetIdentity(&idInstance, &idWriter, &bstrWriterName, &usage, &source));

				writer.set_InstanceId(idInstance);
				writer.set_Name(bstrWriterName);
				writer.set_WriterId(idWriter);

				CComBSTR writerName(bstrWriterName);
				CString message;
				message.AppendFormat(TEXT("Writer %d named %s"), iWriter, (LPCTSTR)writerName);
				OutputWriter::WriteLine(message);

				UINT cIncludeFiles;
				UINT cExcludeFiles;
				UINT cComponents;
				CHECK_HRESULT(pExamineWriterMetadata->GetFileCounts(&cIncludeFiles, &cExcludeFiles, &cComponents));

				message.Empty();
				message.AppendFormat(TEXT("Writer has %d components"), cComponents);
				OutputWriter::WriteLine(message);

				for (UINT iComponent = 0; iComponent < cComponents; ++iComponent)
				{
					CWriterComponent component;

					CComPtr<IVssWMComponent> pComponent;
					CHECK_HRESULT(pExamineWriterMetadata->GetComponent(iComponent, &pComponent));

					PVSSCOMPONENTINFO pComponentInfo;
					CHECK_HRESULT(pComponent->GetComponentInfo(&pComponentInfo));

					CString message;
					message.AppendFormat(TEXT("Component %d is named %s, has a path of %s, and is %sselectable for backup. %d files, %d databases, %d log files."),
						iComponent,
						pComponentInfo->bstrComponentName,
						pComponentInfo->bstrLogicalPath,
						pComponentInfo->bSelectable ? TEXT("") : TEXT("not "),
						pComponentInfo->cFileCount,
						pComponentInfo->cDatabases,
						pComponentInfo->cLogFiles);
					OutputWriter::WriteLine(message);

					component.set_LogicalPath(pComponentInfo->bstrLogicalPath);
					component.set_SelectableForBackup(pComponentInfo->bSelectable);
					component.set_Writer(iWriter);
					component.set_Name(pComponentInfo->bstrComponentName);
					component.set_Type(pComponentInfo->type);

					for (UINT iFile = 0; iFile < pComponentInfo->cFileCount; ++iFile)
					{
						CComPtr<IVssWMFiledesc> pFileDesc;
						CHECK_HRESULT(pComponent->GetFile(iFile, &pFileDesc));

						CComBSTR bstrPath;
						CHECK_HRESULT(pFileDesc->GetPath(&bstrPath));

						CComBSTR bstrFileSpec;
						CHECK_HRESULT(pFileDesc->GetFilespec(&bstrFileSpec));

						CString message;
						message.AppendFormat(TEXT("File %d has path %s\\%s"), iFile, bstrPath, bstrFileSpec);
						OutputWriter::WriteLine(message);
					}

					for (UINT iDatabase = 0; iDatabase < pComponentInfo->cDatabases; ++iDatabase)
					{
						CComPtr<IVssWMFiledesc> pFileDesc;
						CHECK_HRESULT(pComponent->GetDatabaseFile(iDatabase, &pFileDesc));

						CComBSTR bstrPath;
						CHECK_HRESULT(pFileDesc->GetPath(&bstrPath));

						CComBSTR bstrFileSpec;
						CHECK_HRESULT(pFileDesc->GetFilespec(&bstrFileSpec));

						CString message;
						message.AppendFormat(TEXT("Database file %d has path %s\\%s"), iDatabase, bstrPath, bstrFileSpec);
						OutputWriter::WriteLine(message);
					}

					for (UINT iDatabaseLogFile = 0; iDatabaseLogFile < pComponentInfo->cLogFiles; ++iDatabaseLogFile)
					{
						CComPtr<IVssWMFiledesc> pFileDesc;
						CHECK_HRESULT(pComponent->GetDatabaseLogFile(iDatabaseLogFile, &pFileDesc));

						CComBSTR bstrPath;
						CHECK_HRESULT(pFileDesc->GetPath(&bstrPath));

						CComBSTR bstrFileSpec;
						CHECK_HRESULT(pFileDesc->GetFilespec(&bstrFileSpec));

						CString message;
						message.AppendFormat(TEXT("Database log file %d has path %s\\%s"), iDatabaseLogFile, bstrPath, bstrFileSpec);
						OutputWriter::WriteLine(message);
					}

					CHECK_HRESULT(pComponent->FreeComponentInfo(pComponentInfo));

					writer.get_Components().push_back(component);

				}

				writer.ComputeComponentTree();

				for (unsigned int iComponent = 0; iComponent < writer.get_Components().size(); ++iComponent)
				{
					CWriterComponent& component = writer.get_Components()[iComponent];
					CString message;
					message.AppendFormat(TEXT("Component %d has name %s, path %s, is %sselectable for backup, and has parent %s"),
						iComponent,
						component.get_Name(),
						component.get_LogicalPath(),
						component.get_SelectableForBackup() ? TEXT("") : TEXT("not "),
						component.get_Parent() == NULL ? TEXT("(no parent)") : component.get_Parent()->get_Name());
					OutputWriter::WriteLine(message);
				}

				writers.push_back(writer);
			}

			OutputWriter::WriteLine(TEXT("Calling StartSnapshotSet"));
			CHECK_HRESULT(pBackupComponents->StartSnapshotSet(&snapshotSetId));

			OutputWriter::WriteLine(TEXT("Calling GetVolumePathName"));
			WCHAR wszVolumePathName[MAX_PATH];
			BOOL bWorked = ::GetVolumePathName(options.get_Source(), wszVolumePathName, MAX_PATH);

			if (!bWorked)
			{
				DWORD error = ::GetLastError();
				CString errorMessage;
				Utilities::FormatErrorMessage(error, errorMessage);
				CString message;
				message.AppendFormat(TEXT("There was an error retrieving the volume name from the path. Path: %s Error: %s"),
					options.get_Source(), errorMessage);
				throw new CVSSCopyException(message.GetString());
			}

			OutputWriter::WriteLine(TEXT("Calling AddToSnapshotSet"));
			GUID snapshotId;
			CHECK_HRESULT(pBackupComponents->AddToSnapshotSet(wszVolumePathName, GUID_NULL, &snapshotId));

			for (unsigned int iWriter = 0; iWriter < writers.size(); ++iWriter)
			{
				CWriter writer = writers[iWriter];

				CString message;
				message.AppendFormat(TEXT("Adding components to snapshot set for writer %s"), writer.get_Name());
				OutputWriter::WriteLine(message);
				for (unsigned int iComponent = 0; iComponent < writer.get_Components().size(); ++iComponent)
				{
					CWriterComponent component = writer.get_Components()[iComponent];

					if (ShouldAddComponent(component))
					{
						CString message;
						message.AppendFormat(TEXT("Adding component %s (%s) from writer %s"),
							component.get_Name(),
							component.get_LogicalPath(),
							writer.get_Name());
						OutputWriter::WriteLine(message);
						CHECK_HRESULT(pBackupComponents->AddComponent(
							writer.get_InstanceId(),
							writer.get_WriterId(),
							component.get_Type(),
							component.get_LogicalPath(),
							component.get_Name()
							));
					}
					else
					{
						CString message;
						message.AppendFormat(TEXT("Not adding component %s from writer %s."),
							component.get_Name(), writer.get_Name());
						OutputWriter::WriteLine(message);
					}
				}
			}

			OutputWriter::WriteLine(TEXT("Calling SetBackupState"));
			// Issue #29: trying to figure out if using VSS_BT_INCREMENTAL causes a problem
			CHECK_HRESULT(pBackupComponents->SetBackupState(TRUE, FALSE, VSS_BT_FULL, FALSE));

			OutputWriter::WriteLine(TEXT("Calling PrepareForBackup"));
			CComPtr<IVssAsync> pPrepareForBackupResults;
			CHECK_HRESULT(pBackupComponents->PrepareForBackup(&pPrepareForBackupResults));

			OutputWriter::WriteLine(TEXT("Waiting for call to PrepareForBackup to finish..."));
			CHECK_HRESULT(pPrepareForBackupResults->Wait());

			HRESULT hrPrepareForBackupResults;
			CHECK_HRESULT(pPrepareForBackupResults->QueryStatus(&hrPrepareForBackupResults, NULL));

			if (hrPrepareForBackupResults != VSS_S_ASYNC_FINISHED)
			{
				throw new CVSSCopyException(TEXT("Prepare for backup failed."));
			}

			OutputWriter::WriteLine(TEXT("Call to PrepareForBackup finished."));

			SYSTEMTIME snapshotTime;
			::GetSystemTime(&snapshotTime);

			bWorked = ::SetConsoleCtrlHandler(CtrlHandler, TRUE);

			if (!bWorked)
			{
				OutputWriter::WriteLine(TEXT("Unable to set control handler. Ctrl-C and Ctrl-Break may have undesirable results."),
					VERBOSITY_THRESHOLD_NORMAL);
			}

			if (!options.get_Simulate())
			{
				OutputWriter::WriteLine(TEXT("Calling DoSnapshotSet"));
				CComPtr<IVssAsync> pDoSnapshotSetResults;
				CHECK_HRESULT(pBackupComponents->DoSnapshotSet(&pDoSnapshotSetResults));

				OutputWriter::WriteLine(TEXT("Waiting for call to DoSnapshotSet to finish..."));

				CHECK_HRESULT(pDoSnapshotSetResults->Wait());

				bSnapshotCreated = true;

				if (s_cancel)
				{
					throw new CVSSCopyException(TEXT("Processing was cancelled by control-c, control-break, or a shutdown event. Terminating."));
				}

				bWorked = ::SetConsoleCtrlHandler(CtrlHandler, FALSE);

				if (!bWorked)
				{
					OutputWriter::WriteLine(TEXT("Unable to reset control handler. Ctrl-C and Ctrl-Break may have undesirable results."), VERBOSITY_THRESHOLD_NORMAL);
				}

				HRESULT hrDoSnapshotSetResults;
				CHECK_HRESULT(pDoSnapshotSetResults->QueryStatus(&hrDoSnapshotSetResults, NULL));

				if (hrDoSnapshotSetResults != VSS_S_ASYNC_FINISHED)
				{
					throw new CVSSCopyException(L"DoSnapshotSet failed.");
				}

				OutputWriter::WriteLine(TEXT("Call to DoSnapshotSet finished."));

				OutputWriter::WriteLine(TEXT("Calling GetSnapshotProperties"));
				VSS_SNAPSHOT_PROP snapshotProperties;
				CHECK_HRESULT(pBackupComponents->GetSnapshotProperties(snapshotId, &snapshotProperties));

				OutputWriter::WriteLine(TEXT("Calling CalculateSourcePath"));
				// TODO: We'll eventually have to deal with mount points
				CString wszSource;
				CalculateSourcePath(
					snapshotProperties.m_pwszSnapshotDeviceObject,
					options.get_Source(),
					wszVolumePathName,
					wszSource
					);

				message.Empty();
				message.AppendFormat(TEXT("Recursively creating destination directory %s."),
					options.get_Destination());
				OutputWriter::WriteLine(message);

				Utilities::CreateDirectory(options.get_Destination());

				OutputWriter::WriteLine(TEXT("Calling CopyRecursive"));

				vector<CCopyFilter*> filters;

				if (options.get_BackupType() == VSS_BT_FULL)
				{
					filters.push_back(new CIncludeAllCopyFilter());
				}
				else if (options.get_BackupType() == VSS_BT_INCREMENTAL)
				{
					filters.push_back(new CModifiedSinceCopyFilter(lastBackupTime, options.get_SkipDenied()));
				}

				filters.push_back(new CFilespecCopyFilter(options.get_Filespecs()));

				CCopyAction copyAction(wszSource, options.get_Destination(), options.get_SkipDenied(), filters);
				ProcessDirectory(wszSource, copyAction, TEXT(""), options.get_Recursive(), options.get_IgnorePattern());

				for (unsigned int iFilter = 0; iFilter < filters.size(); ++iFilter)
				{
					delete filters[iFilter];
				}

				fileCount = copyAction.get_FileCount();
				directoryCount = copyAction.get_DirectoryCount();
				skipCount = copyAction.get_SkipCount();
				byteCount = copyAction.get_ByteCount();

				OutputWriter::WriteLine(TEXT("Calling BackupComplete"));
				CComPtr<IVssAsync> pBackupCompleteResults;
				CHECK_HRESULT(pBackupComponents->BackupComplete(&pBackupCompleteResults));

				OutputWriter::WriteLine(TEXT("Waiting for call to BackupComplete to finish..."));
				CHECK_HRESULT(pBackupCompleteResults->Wait());

				HRESULT hrBackupCompleteResults;
				CHECK_HRESULT(pBackupCompleteResults->QueryStatus(&hrBackupCompleteResults, NULL));

				if (hrBackupCompleteResults != VSS_S_ASYNC_FINISHED)
				{
					throw new CVSSCopyException(TEXT("Completion of backup failed."));
				}

				OutputWriter::WriteLine(TEXT("Call to BackupComplete finished."));

				bAbnormalAbort = false;

				if (options.get_StateFile() != NULL)
				{
					OutputWriter::WriteLine(TEXT("Calling SaveAsXML"));
					CComBSTR bstrBackupDocument;
					CHECK_HRESULT(pBackupComponents->SaveAsXML(&bstrBackupDocument));

					if (options.get_BackupType() == VSS_BT_FULL)
					{
						backupState.set_LastFullBackupTime(&snapshotTime);
					}
					else if (options.get_BackupType() == VSS_BT_INCREMENTAL)
					{
						backupState.set_LastIncrementalBackupTime(&snapshotTime);
					}
					else
					{
						throw new CVSSCopyException(TEXT("Unsupported backup type."));
					}

					backupState.Save(options.get_StateFile(), bstrBackupDocument);
				}
			}
		}
		catch (CComException* e)
		{
			Cleanup(bAbnormalAbort, bSnapshotCreated, pBackupComponents, snapshotSetId);
			CString message;
			CString file;
			e->get_File(file);
			message.Format(TEXT("There was a COM failure 0x%x - %s (%d)"),
				e->get_Hresult(), file, e->get_Line());
			OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_UNLESS_SILENT);
			return;
		}
		catch (CVSSCopyException* e)
		{
			Cleanup(bAbnormalAbort, bSnapshotCreated, pBackupComponents, snapshotSetId);
			OutputWriter::WriteLine(e->get_Message(), VERBOSITY_THRESHOLD_UNLESS_SILENT);
			return;
		}
		catch (CParseOptionsException* e)
		{
			Cleanup(bAbnormalAbort, bSnapshotCreated, pBackupComponents, snapshotSetId);
			CString message;
			message.AppendFormat(TEXT("Error: %s\n"), e->get_Message());
			OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_UNLESS_SILENT);
			OutputWriter::WriteLine(COptions::get_Usage(), VERBOSITY_THRESHOLD_UNLESS_SILENT);
			return;
		}

		Cleanup(false, bSnapshotCreated, pBackupComponents, snapshotSetId);
		OutputWriter::WriteLine(TEXT("Backup successfully completed."), VERBOSITY_THRESHOLD_UNLESS_SILENT);

		CString message;
		CString startTimeStringLocal;
		Utilities::FormatDateTime(&startTime, TEXT(" "), true, startTimeStringLocal);
		CString finishTimeString;
		SYSTEMTIME finishTime;
		::GetSystemTime(&finishTime);
		Utilities::FormatDateTime(&finishTime, TEXT(" "), true, finishTimeString);
		message.AppendFormat(TEXT("Backup started at %s, completed at %s."),
			startTimeStringLocal, finishTimeString);
		OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL);
		message.Empty();

		float unitCount = (float)byteCount;
		LPCTSTR units = TEXT("bytes");

		if (unitCount > 1024)
		{
			unitCount = unitCount / 1024.0F;
			units = TEXT("KB");
		}

		if (unitCount > 1024)
		{
			unitCount = unitCount / 1024.0F;
			units = TEXT("MB");
		}

		if (unitCount > 1024)
		{
			unitCount = unitCount / 1024.0F;
			units = TEXT("GB");
		}

		message.AppendFormat(TEXT("%d files (%.2f %s, %d directories) copied, %d files skipped"),
			fileCount, unitCount, units, directoryCount, skipCount);
		OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL);

		OutputWriter::SetVerbosityLevel((VERBOSITY_LEVEL)options.get_VerbosityLevel());

		//for (int i = 0; i < argc; ++i)
		//{
		//	CString message;
		//	message.AppendFormat(TEXT("Argument %d: %s"), i, argv[i]);
		//	OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_IF_VERBOSE);
		//}
}
	HRESULT CAddInRegistrar::Register(CLSID clsid, LCID lcid, LPCTSTR name, LPCTSTR summary, ULONG cEnvironments, CATID environments[])
	{
		HRESULT hr = S_OK;

#pragma region "HKEY_CLASSES_ROOT\CLSID\{ADDIN_GUID}"
		
		LPOLESTR lpClsidString;
		StringFromCLSID(clsid, &lpClsidString);

		CString strKeyCLSID;
		strKeyCLSID.AppendFormat(L"CLSID\\%s", lpClsidString);

		CoTaskMemFree(lpClsidString);

		CString strValueName;
		strValueName.AppendFormat(L"%x", lcid);

		CRegKey key;

		// Create\Open the key.
		LONG result = key.Create(HKEY_CLASSES_ROOT, strKeyCLSID);

		if (result == ERROR_SUCCESS)
		{
			// Set the localized addin name.
			key.SetStringValue(strValueName, name);
			key.Close();
		}

#pragma endregion

#pragma region "HKEY_CLASSES_ROOT\CLSID\{ADDIN_GUID}\Summary"

		CString strKeySummary;
		strKeySummary = strKeyCLSID;
		strKeySummary.Append(L"\\Summary");

		result = key.Create(HKEY_CLASSES_ROOT, strKeySummary);

		if (result == ERROR_SUCCESS)
		{
			key.SetStringValue(strValueName, summary);
			key.Close();
		}

#pragma endregion

#pragma region "HKEY_CLASSES_ROOT\CLSID\{ADDIN_GUID}\Environment Categories"

		CString strKeyEnvironmentCategories;
		strKeyEnvironmentCategories = strKeyCLSID;
		strKeyEnvironmentCategories.Append(L"\\Environment Categories");

		result = key.Create(HKEY_CLASSES_ROOT, strKeyEnvironmentCategories);

		if (result == ERROR_SUCCESS)
		{
			for (ULONG i = 0; i < cEnvironments; i++ )
			{
				LPOLESTR lpCatidString = NULL;
				StringFromCLSID( environments[i], &lpCatidString );

				CString strEnvCATID(lpCatidString);
				CRegKey keyEnvironment;
				keyEnvironment.Create(key, strEnvCATID);

				CoTaskMemFree(lpCatidString);
			}

			key.Close();
		}

#pragma endregion

#pragma region "HKEY_CLASSES_ROOT\CLSID\{ADDIN_GUID}\Implemented Categories"
		
		ICatRegisterPtr pCatRegister;
		IfFailGoCheck(pCatRegister.CreateInstance(CLSID_StdComponentCategoriesMgr), pCatRegister);

		CATID implementedCategories[] = { CATID_SolidEdgeAddIn };
		IfFailGo(pCatRegister->RegisterClassImplCategories(clsid, _countof(implementedCategories), implementedCategories));

#pragma endregion

Error:
		pCatRegister = NULL;
		return hr;
	}
CString aft_gen_report_string()
{
	CString cstrTemp;
	int iAxisCurr;

	cstrTemp.Format("%%%%%%%% BE WireBonder AFT (Assembly Functional Test) Report \r\n");
	cstrTemp.AppendFormat("%%%%%%%% Section-1: Travel Range and Index Distance \r\n");

	for(iAxisCurr = WB_AXIS_TABLE_X; iAxisCurr <= WB_AXIS_BOND_Z; iAxisCurr ++)
	{
		cstrTemp.AppendFormat("%% ------ Axis: %s \r\n", astAssemblyFuncTestAxisSpec[iAxisCurr].strAxisName_en);
		if(astAssemblyFuncTestAxisOut[iAxisCurr].dDistLimitToLimit_mm == 0 ||
			astAssemblyFuncTestAxisOut[iAxisCurr].dDistLowLimitToIndex_mm == 0 ||
			astAssemblyFuncTestAxisOut[iAxisCurr].dDistUppLimitToIndex_mm == 0 ||
			astAssemblyFuncTestAxisOut[iAxisCurr].dDistIndexUppLow_mm == 0)
		{
			cstrTemp.AppendFormat("NOT YET to do AFT\r\n\r\n");
		}
		else
		{
			cstrTemp.AppendFormat("DistLimitToLimit_mm = %8.2f; %% [%8.2f, %8.2f] --- %s %s\r\n", 
				astAssemblyFuncTestAxisOut[iAxisCurr].dDistLimitToLimit_mm,
				astAssemblyFuncTestAxisSpec[iAxisCurr].dDistLimitToLimit_mm_L, astAssemblyFuncTestAxisSpec[iAxisCurr].dDistLimitToLimit_mm_U,
				strAFT_Result_en[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagFailLimitToLimit + 1],
				strAFT_Result_cn[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagFailLimitToLimit + 1]);

			cstrTemp.AppendFormat("DistLowLimitToIndex_mm = -%4.2f; %% [%8.2f, %8.2f] --- %s %s\r\n", 
				astAssemblyFuncTestAxisOut[iAxisCurr].dDistLowLimitToIndex_mm,
				astAssemblyFuncTestAxisSpec[iAxisCurr].dDistLowLimitToIndex_mm_L, astAssemblyFuncTestAxisSpec[iAxisCurr].dDistLowLimitToIndex_mm_U,
				strAFT_Result_en[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagFailLowLimitToIndex + 1],
				strAFT_Result_cn[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagFailLowLimitToIndex + 1]);

			cstrTemp.AppendFormat("DistUppLimitToIndex_mm = %8.2f; %% [%8.2f, %8.2f] --- %s %s \r\n", 
				astAssemblyFuncTestAxisOut[iAxisCurr].dDistUppLimitToIndex_mm,
				astAssemblyFuncTestAxisSpec[iAxisCurr].dDistUppLimitToIndex_mm_L, astAssemblyFuncTestAxisSpec[iAxisCurr].dDistUppLimitToIndex_mm_U,
				strAFT_Result_en[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagFailUppLimitToIndex + 1],
				strAFT_Result_cn[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagFailUppLimitToIndex + 1]);

			cstrTemp.AppendFormat("DistIndexUppLow_mm = %8.4f; %% [%8.4f, %8.4f] --- %s %s\r\n\r\n", 
				astAssemblyFuncTestAxisOut[iAxisCurr].dDistIndexUppLow_mm,
				astAssemblyFuncTestAxisSpec[iAxisCurr].dDistIndexUppLow_mm_L, astAssemblyFuncTestAxisSpec[iAxisCurr].dDistIndexUppLow_mm_U,
				strAFT_Result_en[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagFailIndexUppLow + 1],
				strAFT_Result_cn[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagFailIndexUppLow + 1]);

		}
	}
	cstrTemp.AppendFormat("%%%%%%%% Section-2: Maximum Expected Acc (m/s/s) \r\n");
	for(iAxisCurr = WB_AXIS_TABLE_X; iAxisCurr <= WB_AXIS_BOND_Z; iAxisCurr ++)
	{
		cstrTemp.AppendFormat("%% ------ Axis: %s \r\n", astAssemblyFuncTestAxisSpec[iAxisCurr].strAxisName_en);
		if(astAssemblyFuncTestAxisOut[iAxisCurr].dExpectMaxAccNegDir_m_s == 0 ||
			astAssemblyFuncTestAxisOut[iAxisCurr].dExpectMaxAccPosDir_m_s == 0)
		{
			cstrTemp.AppendFormat("NOT YET to do AFT\r\n\r\n");
		}
		else
		{
			cstrTemp.AppendFormat("ExpectMaxAccPosDir_m_s = %8.1f; %% [%8.1f, %8.1f] --- %s %s\r\n", 
				astAssemblyFuncTestAxisOut[iAxisCurr].dExpectMaxAccPosDir_m_s,
				astAssemblyFuncTestAxisSpec[iAxisCurr].dExpectMaxAccPosDir_m_s_L, astAssemblyFuncTestAxisSpec[iAxisCurr].dExpectMaxAccPosDir_m_s_U,
				strAFT_Result_en[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagExpMaxAccPosDir + 1],
				strAFT_Result_cn[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagExpMaxAccPosDir + 1]);
			cstrTemp.AppendFormat("ExpectMaxAccNegDir_m_s = %8.1f; %% [%8.1f, %8.1f] --- %s %s\r\n", 
				astAssemblyFuncTestAxisOut[iAxisCurr].dExpectMaxAccNegDir_m_s,
				astAssemblyFuncTestAxisSpec[iAxisCurr].dExpectMaxAccNegDir_m_s_L, astAssemblyFuncTestAxisSpec[iAxisCurr].dExpectMaxAccNegDir_m_s_U,
				strAFT_Result_en[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagExpMaxAccNegDir + 1],
				strAFT_Result_cn[astAssemblyFuncTestAxisResult[iAxisCurr].iFlagExpMaxAccNegDir + 1]);

			cstrTemp.AppendFormat("ExpectMaxAccPosDir_mean_std = [%8.1f, %8.1f]; \r\n", 
				astAssemblyFuncTestAxisOut[iAxisCurr].dExpMaxAccMeanPosDir, astAssemblyFuncTestAxisOut[iAxisCurr].dExpMaxAccStdPosDir);
			cstrTemp.AppendFormat("ExpectMaxAccNegDir_mean_std = [%8.1f, %8.1f]; \r\n\r\n", 
				astAssemblyFuncTestAxisOut[iAxisCurr].dExpMaxAccMeanNegDir, astAssemblyFuncTestAxisOut[iAxisCurr].dExpMaxAccStdNegDir);
		}
	}
	return cstrTemp;
}
Exemple #30
-1
void CFilesHashDlg::AppendResult(const ResultData& result, CString& strToAppend)
{
	strToAppend.Append(FILENAME_STRING);
	strToAppend.Append(_T(" "));
	strToAppend.Append(result.strPath);
	strToAppend.Append(_T("\r\n"));
	if(result.bDone)
	{
		// A succeed result
		strToAppend.Append(FILESIZE_STRING);
		strToAppend.Append(_T(" "));
		strToAppend.AppendFormat(_T("%I64u "), result.ulSize);
		strToAppend.Append(BYTE_STRING);
		strToAppend.Append(ConvertSizeToCStr(result.ulSize));
		strToAppend.Append(_T("\r\n"));
		strToAppend.Append(MODIFYTIME_STRING);
		strToAppend.Append(_T(" "));
		strToAppend.Append(result.strMDate);
		if(result.strVersion.Compare(_T("")) != 0)
		{
			strToAppend.Append(_T("\r\n"));
			strToAppend.Append(VERSION_STRING);
			strToAppend.Append(_T(" "));
			strToAppend.Append(result.strVersion);
		}
		strToAppend.Append(_T("\r\n"));

		CString strMD5(result.strMD5);
		CString strSHA1(result.strSHA1);
		CString strSHA256(result.strSHA256);
		CString strCRC32(result.strCRC32);

		if(m_thrdData.uppercase = m_chkUppercase.GetCheck())
		{
			strToAppend.Append(_T("MD5: "));
			strToAppend.Append(strMD5.MakeUpper());
			strToAppend.Append(_T("\r\nSHA1: "));
			strToAppend.Append(strSHA1.MakeUpper());
			strToAppend.Append(_T("\r\nSHA256: "));
			strToAppend.Append(strSHA256.MakeUpper());
			strToAppend.Append(_T("\r\nCRC32: "));
			strToAppend.Append(strCRC32.MakeUpper());
		}
		else
		{
			strToAppend.Append(_T("MD5: "));
			strToAppend.Append(strMD5.MakeLower());
			strToAppend.Append(_T("\r\nSHA1: "));
			strToAppend.Append(strSHA1.MakeLower());
			strToAppend.Append(_T("\r\nSHA256: "));
			strToAppend.Append(strSHA256.MakeLower());
			strToAppend.Append(_T("\r\nCRC32: "));
			strToAppend.Append(strCRC32.MakeLower());
		}
	}
	else
	{
		// An error result
		strToAppend.Append(result.strError);
	}

	strToAppend.Append(_T("\r\n\r\n"));
}