Пример #1
0
void PasswordSafeFrame::OnPreferencesClick( wxCommandEvent& /* evt */ )
{
  PWSprefs* prefs = PWSprefs::GetInstance();
  const StringX sxOldDBPrefsString(prefs->Store());
  COptions *window = new COptions(this);
  if (window->ShowModal() == wxID_OK) {
    StringX sxNewDBPrefsString(prefs->Store(true));
    // Update system tray icon if visible so changes show up immediately
    if (m_sysTray && prefs->GetPref(PWSprefs::UseSystemTray))
        m_sysTray->ShowIcon();

    if (!m_core.GetCurFile().empty() && !m_core.IsReadOnly() &&
        m_core.GetReadFileVersion() == PWSfile::VCURRENT) {
      if (sxOldDBPrefsString != sxNewDBPrefsString) {
        Command *pcmd = DBPrefsCommand::Create(&m_core, sxNewDBPrefsString);
        if (pcmd) {
            //I don't know why notifications should ever be suspended, but that's how
            //things were before I messed with them, so I want to limit the damage by
            //enabling notifications only as long as required and no more
            m_core.ResumeOnDBNotification();
            Execute(pcmd);  //deleted automatically
            m_core.SuspendOnDBNotification();
        }
      }
    }
  }
  window->Destroy();
}
CEnemyDemon::CEnemyDemon()
{
    COptions *op = COptions::GetInstance();
    CSGD_EventSystem *pES = CSGD_EventSystem::GetInstance();

    SetHP(25 * op->GetDifficulty());
    SetVelX(100.0f * op->GetDifficulty());
    SetVelY(100.0f * op->GetDifficulty());
    SetXFlip(-1);
    SetHeight(64);
    SetWidth(64);
    SetPosX(500);
    SetPosY(500);
    SetType(ACTOR_ENEMY);
    SetPower(5 * op->GetDifficulty());
    SetScoreValue(100 * op->GetDifficulty());
    SetHit(false);

    rEnemyRect.top = 65;
    rEnemyRect.bottom = 123;
    rEnemyRect.left = 0;
    rEnemyRect.right = 60;

    m_nSoundID = CSGD_WaveManager::GetInstance()->LoadWave("Resource/sounds/JoA_Bark.wav");
    CSGD_WaveManager::GetInstance()->SetVolume(m_nSoundID,COptions::GetInstance()->GetSFXVolume()-40);


}
Пример #3
0
BOOL CAdminSocket::Init()
{
	char *buffer = new char[100];
	char *p = buffer;
	strcpy(buffer, "FZS");
	p += 3;

	*p++ = 0;
	*p++ = 4;
	memcpy(p, &SERVER_VERSION, 4);
	p += 4;

	*p++ = 0;
	*p++ = 4;

	memcpy(p, &PROTOCOL_VERSION, 4);
	p += 4;

	COptions options;
	CStdString pass = options.GetOption(OPTION_ADMINPASS);
	CStdString peerAddress;
	UINT port = 0;
	if (GetPeerName(peerAddress, port) && IsLocalhost(peerAddress) && pass == _T("")) {
		BOOL res = Send(buffer, p-buffer) == p - buffer;
		delete [] buffer;
		if (!res) {
			Close();
			return FALSE;
		}
		return FinishLogon();
	}
	else {
		*p++ = 0;

		DWORD len = 20;
		memcpy(p, &len, 4);
		p += 4;

		*p++ = 0;
		*p++ = 8;

		int i;
		for (i = 0; i < 8; ++i) {
			m_Nonce1[i] = std::uniform_int_distribution<unsigned int>(0, 255)(std::random_device());
			*p++ = m_Nonce1[i];
		}

		*p++ = 0;
		*p++ = 8;

		for (i = 0; i < 8; ++i) {
			m_Nonce2[i] = std::uniform_int_distribution<unsigned int>(0, 255)(std::random_device());
			*p++ = m_Nonce2[i];
		}
	}

	int res = Send(buffer, p-buffer) == p-buffer;
	delete [] buffer;
	return res;
}
void CEnemyBusiness::HandleEvent(CEvent *pEvent)
{
	CSGD_ObjectFactory<string, CBase> *pOF		= CSGD_ObjectFactory<string, CBase>::GetInstance();
	CSGD_ObjectManager *pOM						= CSGD_ObjectManager::GetInstance();
 	CSGD_TextureManager *pTM = CSGD_TextureManager::GetInstance();
	COptions *op = COptions::GetInstance();

	if (pEvent->GetEventID() == "businessman fire")
	{
		m_fFireReady = 5.0f;
		bIsFiring = true;

		pBullet = pOF->CreateObject("CBulletPaper");
		pBullet->SetImageID(GetImageID());

		if (GetXFlip() == -1)
			pBullet->SetVelX(500);
		else
			pBullet->SetVelX(-500);

		pBullet->SetVelY(0);
		pBullet->SetPosX(GetPosX() - (GetXFlip() * 48));
		pBullet->SetPosY(GetPosY());
		pBullet->SetType(ACTOR_BULLET);

		pBullet->SetHeight(20);
		pBullet->SetWidth(20);
		pBullet->SetPower(5 * op->GetDifficulty());

		pOM->AddObject(pBullet);
	}

}
Пример #5
0
bool COptionsPageEdit::LoadPage()
{
	bool failure = false;

	COptions* pOptions = COptions::Get();

	wxString editor = pOptions->GetOption(OPTION_EDIT_DEFAULTEDITOR);
	if (editor.empty() || editor[0] == '0')
		SetRCheck(XRCID("ID_DEFAULT_NONE"), true, failure);
	else if (editor[0] == '1')
		SetRCheck(XRCID("ID_DEFAULT_TEXT"), true, failure);
	else
	{
		if (editor[0] == '2')
			editor = editor.Mid(1);

		SetRCheck(XRCID("ID_DEFAULT_CUSTOM"), true, failure);
		SetText(XRCID("ID_EDITOR"), editor, failure);
	}

	if (pOptions->GetOptionVal(OPTION_EDIT_ALWAYSDEFAULT))
		SetRCheck(XRCID("ID_USEDEFAULT"), true, failure);
	else
		SetRCheck(XRCID("ID_USEASSOCIATIONS"), true, failure);

	SetCheckFromOption(XRCID("ID_EDIT_TRACK_LOCAL"), OPTION_EDIT_TRACK_LOCAL, failure);

	if (!failure)
		SetCtrlState();

	return !failure;
}
Пример #6
0
void CUpdateWizard::DisplayUpdateAvailability(bool showDialog)
{
	COptions* pOptions = COptions::Get();

	if (CBuildInfo::GetVersion() == _T("custom build"))
		return;

	const wxString& newVersion = pOptions->GetOption(OPTION_UPDATECHECK_NEWVERSION);
	if (newVersion == _T(""))
		return;

	wxLongLong v = CBuildInfo::ConvertToVersionNumber(newVersion);
	if (v <= CBuildInfo::ConvertToVersionNumber(CBuildInfo::GetVersion()))
	{
		pOptions->SetOption(OPTION_UPDATECHECK_NEWVERSION, _T(""));
		return;
	}

	if (!m_menuUpdated)
	{
		m_menuUpdated = true;

#ifdef __WXMSW__
		// All open menus need to be closed or app will become unresponsive.
		::EndMenu();
#endif

		CMainFrame* pFrame = (CMainFrame*)m_parent;

		wxMenu* pMenu = new wxMenu();
		const wxString& name = wxString::Format(_("&Version %s"), pOptions->GetOption(OPTION_UPDATECHECK_NEWVERSION).c_str());
		pMenu->Append(XRCID("ID_CHECKFORUPDATES"), name);
		wxMenuBar* pMenuBar = pFrame->GetMenuBar();
		if (pMenuBar)
			pMenuBar->Append(pMenu, _("&New version available!"));
	}

	if (showDialog && !m_updateShown)
	{
		if (wxDialogEx::ShownDialogs())
		{
			m_busy_timer.Start(1000, true);
			return;
		}

		m_updateShown = true;

#ifdef __WXMSW__
		// All open menus need to be closed or app will become unresponsive.
		::EndMenu();
#endif

		CUpdateWizard dlg(m_parent);
		if (dlg.Load())
			dlg.Run();
	}
}
bool COptionsPageEditAssociations::SavePage()
{
	COptions* pOptions = COptions::Get();

	SetOptionFromText(XRCID("ID_ASSOCIATIONS"), OPTION_EDIT_CUSTOMASSOCIATIONS);
	
	pOptions->SetOption(OPTION_EDIT_INHERITASSOCIATIONS, GetCheck(XRCID("ID_INHERIT")) ? 1 : 0);
		
	return true;
}
bool COptionsPageEditAssociations::LoadPage()
{
	bool failure = false;

	COptions* pOptions = COptions::Get();

	SetTextFromOption(XRCID("ID_ASSOCIATIONS"), OPTION_EDIT_CUSTOMASSOCIATIONS, failure);
	SetCheck(XRCID("ID_INHERIT"), pOptions->GetOptionVal(OPTION_EDIT_INHERITASSOCIATIONS) != 0, failure);

	return !failure;
}
Пример #9
0
bool COptionsPageEdit::SavePage()
{
	COptions* pOptions = COptions::Get();

	if (GetRCheck(XRCID("ID_DEFAULT_CUSTOM")))
		pOptions->SetOption(OPTION_EDIT_DEFAULTEDITOR, _T("2") + GetText(XRCID("ID_EDITOR")));
	else 
		pOptions->SetOption(OPTION_EDIT_DEFAULTEDITOR, GetRCheck(XRCID("ID_DEFAULT_TEXT")) ? _T("1") : _T("0"));

	if (GetRCheck(XRCID("ID_USEDEFAULT")))
		pOptions->SetOption(OPTION_EDIT_ALWAYSDEFAULT, 1);
	else
		pOptions->SetOption(OPTION_EDIT_ALWAYSDEFAULT, 0);

	SetOptionFromCheck(XRCID("ID_EDIT_TRACK_LOCAL"), OPTION_EDIT_TRACK_LOCAL);
		
	return true;
}
CEnemyPsycrow::CEnemyPsycrow()
{
	CSGD_EventSystem *pES = CSGD_EventSystem::GetInstance();
	CSGD_TextureManager *pTM = CSGD_TextureManager::GetInstance();
	COptions *op = COptions::GetInstance();

	pES->RegisterClient("psycrow fire", this);
	pES->RegisterClient("state transition 1", this);
	pES->RegisterClient("state transition 2", this);
	pES->RegisterClient("state transition 3", this);
	pES->RegisterClient("state transition 4", this);

	m_nState = PSYCROW_STATE1;
	m_nSoundID = CSGD_WaveManager::GetInstance()->LoadWave("Resource/sounds/JoA_Squawk.wav");
	CSGD_WaveManager::GetInstance()->SetVolume(m_nSoundID, op->GetSFXVolume() - 40);
	m_fFireReady = 5.0f;
	m_fHitTimer = 0.4f;
	m_nOffset = 0;
	bIsFired = false;
	m_fFiringTimer = 0.5f;
	m_fSineFloat = 3.14f;
	m_nColor = 255;
	m_nScale = 1.5f;

	SetHP(250 * op->GetDifficulty());
	SetVelX(75 * op->GetDifficulty());
	SetVelY(0.0f);
	SetXFlip(-1);
	SetHeight(84);
	SetWidth(70);
	SetPosX(320);
	SetPosY(240);
	SetPower(0);
	SetType(ACTOR_ENEMY);
	SetScoreValue(1000 * op->GetDifficulty());
	SetHit(false);
	pBullet = NULL;

	bIsFiring = false;

}
CEnemyBusiness::CEnemyBusiness()
{
	CSGD_EventSystem *pES = CSGD_EventSystem::GetInstance();
	CSGD_TextureManager *pTM = CSGD_TextureManager::GetInstance();
	COptions *op = COptions::GetInstance();
	CSGD_WaveManager *pWM = CSGD_WaveManager::GetInstance();

	pES->RegisterClient("businessman fire", this);

	SetHP(50 *op->GetDifficulty());
	SetVelX(-50.0f * op->GetDifficulty());
	SetVelY(0.0f);
	SetXFlip(-1);
	SetHeight(63);
	SetWidth(86);
	SetPosX(1000);
	SetPosY(220);
	SetPower(0);
	SetType(ACTOR_ENEMY);
	SetScoreValue(200 * op->GetDifficulty());
	SetHit(false);
	pBullet = NULL;

	bIsFiring = false;

	m_fFireReady = 5.0f;
	m_fHitTimer = 1.0f;
	m_nOffset = 0;
	m_fFiringTimer = 1.0f;

	rEnemyRect.top = 18;
	rEnemyRect.bottom = 61;
	rEnemyRect.left = 2;
	rEnemyRect.right = 54;

	m_nSoundID = pWM->LoadWave("Resource/sounds/JoA_Scream.wav");
	pWM->SetVolume(m_nSoundID,op->GetSFXVolume() - 25);
	

}
Пример #12
0
//---------------------------------------------------------------------------//
// Init
//
//---------------------------------------------------------------------------//
bool CFilterDll::Init(COptions &aOptions)
{
  m_Ok = false;

  const string &sFile = aOptions.Option("library");
  if (sFile == "")
  {
    GLOG(("ERR: Library file not specified\n"));
    return false;
  }
  m_hLibrary = LoadLibrary(sFile.c_str());
  if (!m_hLibrary)
  {
    GLOG(("ERR: Can't load library %s\n", sFile.c_str()));
    return false;
  }

  if (!LoadFunctions())
  {
    GLOG(("ERR: FilterDLL version from file %s is not compatible with current version (%d)\n", sFile.c_str(), FILTER_VERSION));
    FreeLibrary(m_hLibrary);
    return false;
  }

  // Filter init
  int iErr = m_pFncInit(FILTER_VERSION, this, g_DisplayDevice.GetD3DDevice(), aOptions.Options(), &m_uID);
  if (iErr)
  {
    if (iErr == -1)
      GLOG(("ERR: FilterDLL version from file %s is not compatible with this one (%d)\n", sFile.c_str(), FILTER_VERSION));
    else
      GLOG(("ERR: FilterDLL can't load library %s. Return code = %d\n", sFile.c_str(), iErr));
    FreeLibrary(m_hLibrary);
    return false;
  }

  m_Ok = true;
  return m_Ok;
}
Пример #13
0
int SSC_OnProtocolAck(WPARAM, LPARAM lParam)
{
	if (g_bMirandaIsShutdown)
		return 0;

	ACKDATA* pAckData = reinterpret_cast<ACKDATA*>(lParam);
	if (pAckData->type != ACKTYPE_STATUS || pAckData->result != ACKRESULT_SUCCESS || !pAckData->szModule)
		return 0;

	if (!g_Options.IsProtocolExcluded(pAckData->szModule)) {
		int nStatus = CallProtoService(pAckData->szModule, PS_GETSTATUS, 0, 0);
		for (size_t i = 0; i < _countof(g_aStatusCode); ++i) {
			const CMirandaStatus2SkypeStatus& ms = g_aStatusCode[i];
			if (ms.m_nMirandaStatus == nStatus) {
				int nPrevStatus;
				if ((false == g_Options.IsProtocolStatusExcluded(pAckData->szModule, nStatus))
					&& ((false == g_Options.GetSyncStatusStateFlag())
						|| (false == g_Options.GetPreviousStatus(pAckData->szModule, nPrevStatus))
						|| (nPrevStatus != nStatus))) {
							{
								mir_cslock guard(g_csStatusInfo);
								g_CurrStatusInfo.StatusIndex(i);
								g_CurrStatusInfo.Module(pAckData->szModule);
							}
							if (0 == ::PostMessage(HWND_BROADCAST, g_MsgIDSkypeControlAPIDiscover, (WPARAM)g_wndMainWindow, 0)) {
								mir_cslock guard(g_csStatusInfo);
								g_CurrStatusInfo.StatusIndex(INVALID_INDEX);
								g_CurrStatusInfo.Module(NULL);
							}
							else g_Options.SetPreviousStatus(pAckData->szModule, nStatus);
				}
				break;
			}
		}
	}

	return 0;
}
Пример #14
0
bool CUpdateWizard::Run()
{
	COptions* pOptions = COptions::Get();

	if (CBuildInfo::GetVersion() == _T("custom build"))
		return false;

	const wxString& newVersion = pOptions->GetOption(OPTION_UPDATECHECK_NEWVERSION);
	if (newVersion == _T(""))
		return RunWizard(m_pages.front());

	if (CBuildInfo::ConvertToVersionNumber(newVersion) <= CBuildInfo::ConvertToVersionNumber(CBuildInfo::GetVersion()))
	{
		pOptions->SetOption(OPTION_UPDATECHECK_NEWVERSION, _T(""));
		return RunWizard(m_pages.front());
	}

	// Force another check
	PrepareUpdateCheckPage();
	m_start_check = true;
	m_currentPage = 0;

	return RunWizard(m_pages[0]);
}
Пример #15
0
void CUpdateWizard::InitAutoUpdateCheck()
{
	COptions* pOptions = COptions::Get();
	wxASSERT(pOptions->GetOptionVal(OPTION_UPDATECHECK));

	if (CBuildInfo::GetVersion() == _T("custom build"))
		return;

	// Check every hour if allowed to check for updates

	m_autoCheckTimer.Start(1000 * 3600);
	if (!CanAutoCheckForUpdateNow())
	{
		DisplayUpdateAvailability(false);
		return;
	}
	else
	{
		m_autoUpdateCheckRunning = true;
		const wxDateTime& now = wxDateTime::Now();
		pOptions->SetOption(OPTION_UPDATECHECK_LASTDATE, now.Format(_T("%Y-%m-%d %H:%M:%S")));
		StartUpdateCheck();
	}
}
Пример #16
0
LRESULT CALLBACK CServer::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	CServer *pServer=(CServer *)GetWindowLongPtr(hWnd, GWLP_USERDATA);

	if (message == WM_CLOSE) {
		pServer->OnClose();
		return 0;
	}
	else if (hWnd && message == WM_DESTROY) {
		ASSERT (hWnd == pServer->m_hWnd);
		HANDLE *handle = new HANDLE[pServer->m_ThreadArray.size()];
		unsigned int i = 0;
		for (auto iter = pServer->m_ThreadArray.begin(); iter != pServer->m_ThreadArray.end(); ++iter, ++i) {
			handle[i] = (*iter)->m_hThread;
			(*iter)->PostThreadMessage(WM_QUIT, 0, 0);
		}
		for (i = 0; i < pServer->m_ThreadArray.size(); ++i) {
			int res = WaitForSingleObject(handle[i], INFINITE);
			if (res == WAIT_FAILED)
				res = GetLastError();
		}
		delete [] handle;
		handle = new HANDLE[pServer->m_ClosedThreads.size()];
		i = 0;
		for (auto iter = pServer->m_ClosedThreads.begin(); iter != pServer->m_ClosedThreads.end(); ++iter, ++i) {
			handle[i] = (*iter)->m_hThread;
			(*iter)->PostThreadMessage(WM_QUIT, 0, 0);
		}
		for (i = 0; i < pServer->m_ClosedThreads.size(); ++i) {
			int res = WaitForSingleObject(handle[i], INFINITE);
			if (res == WAIT_FAILED)
				res = GetLastError();
		}
		delete [] handle;
		pServer->m_AdminListenSocketList.clear();
		delete pServer->m_pAdminInterface;
		pServer->m_pAdminInterface = NULL;
		delete pServer->m_pOptions;
		pServer->m_pOptions = NULL;
		if (pServer->m_nTimerID) {
			KillTimer(pServer->m_hWnd, pServer->m_nTimerID);
			pServer->m_nTimerID = 0;
		}
		PostQuitMessage(0);
		return 0;
	}
	else if (message == WM_TIMER)
		pServer->OnTimer(wParam);
	else if (message == WM_FILEZILLA_RELOADCONFIG) {
		COptions options;
		options.ReloadConfig();
		CPermissions perm = CPermissions(std::function<void()>());
		perm.ReloadConfig();
	}
	else if (message >= WM_FILEZILLA_SERVERMSG) {
		UINT index = message - WM_FILEZILLA_SERVERMSG;
		if (index >= pServer->m_ThreadNotificationIDs.size())
			return 0;

		CServerThread *pThread = pServer->m_ThreadNotificationIDs[index];
		if (pThread) {
			std::list<CServerThread::t_Notification> notifications;
			pThread->GetNotifications(notifications);
			for (std::list<CServerThread::t_Notification>::const_iterator iter = notifications.begin(); iter != notifications.end(); iter++)
				if (pServer->OnServerMessage(pThread, iter->wParam, iter->lParam) != 0)
					break;
		}
		return 0;
	}

	return ::DefWindowProc(hWnd, message, wParam, lParam);
}
Пример #17
0
//--------------------------------------------------------------------------------
int main(int argc, const char * argv[])
{
	// We handle options early because the later code may
	// depend on them (-verbose, -testing, -help, --file)
	SFString cmdFile=EMPTY;
	for (int i=0;i<argc;i++)
	{
		SFString arg = argv[i];
		if (arg.startsWith("--file:"))
		{
			cmdFile = arg.Substitute("--file:",EMPTY);
			cmdFile.Replace("~/",getHomeFolder());
			if (!SFos::fileExists(cmdFile))
				return usage("--file: '" + cmdFile + "' not found. Quitting.");

		} else if (arg == "-h" || arg == "-help" || arg == "--help")
		{
			return usage();

		} else if (arg.startsWith("-v") || arg.startsWith("-verbose"))
		{
			verbose = TRUE;
			arg.Replace("-verbose",EMPTY);
			arg.Replace("-v",      EMPTY);
			arg.Replace(":",       EMPTY);
			if (!arg.IsEmpty())
				verbose = toLong(arg);

		} else if (arg=="-t" || arg=="-test" || arg=="-titles")
		{
			// During testing, we send all output (including error messages)
			// to the screen so it can be re-directed to a file
			outErr = outScreen;
			isTesting = TRUE;
		}
	}

	// If we have a command file, we will use it, if not we will create
	// one and pretend we had one. This makes the processing code easier.
	SFString commandList;
	if (cmdFile.IsEmpty())
	{
		for (int i=1;i<argc;i++) // we know the program's name
			commandList += (SFString(argv[i]) + " ");
		commandList += '\n';

	} else
	{
		commandList = asciiFileToString(cmdFile).Substitute("\t", " ").Substitute("  ", " ");
	}

	// We keep only a single slurper. If the user is using the --file option and they
	// are reading the same account repeatedly, we only need to read the cache once.
	CSlurperApp slurper;

	// For each command we first parse the options (expanding them if neceassary), then setup
	// the sluper, then read from either cache or the blockchain, then display the results.
	while (!commandList.IsEmpty())
	{
		SFString command = StripAny(nextTokenClear(commandList, '\n'),"\t\r\n ");
		if (!command.IsEmpty() && !command.startsWith(";")) // ignore comments
		{
			outErr << "Processing: " << command << "\n";

			SFInt32 nArgs=0;
			SFString args[40]; // safe enough
			while (!command.IsEmpty())
			{
				SFString arg = nextTokenClear(command, ' ');
				while (!arg.IsEmpty())
					args[nArgs++] = expandOption(arg); // handles case of -rf for example
			}

			SFString message;

			// Parse the command line
			COptions options; options.cmdFile=!cmdFile.IsEmpty();
			if (!options.parseArguments(nArgs, args))
				return FALSE;

			// Setup the slurper
			if (!slurper.Initialize(options, message))
				return usage(message);

			// Slurp the address...
			if (!slurper.Slurp(options, message))
				return usage(message);

			// Apply the filters if any...
			if (!slurper.Filter(options, message))
				return usage(message);

			// Report on the address...
			if (!slurper.Display(options, message))
				return usage(message);
		}
	}
	return FALSE;
}
Пример #18
0
BOOL CAdminSocket::ParseRecvBuffer()
{
	if (m_nRecvBufferPos<5)
		return FALSE;

	if ((m_pRecvBuffer[0]&0x03) != 0)
	{
		SendCommand(_T("Protocol error: Unknown command type, closing connection."), 1);
		Close();
		m_pAdminInterface->Remove(this);
		return FALSE;
	}
	else
	{
		DWORD len;
		memcpy(&len, m_pRecvBuffer+1, 4);
		if (len > 0xFFFFFF)
		{
			SendCommand(_T("Protocol error: Invalid data length, closing connection."), 1);
			Close();
			m_pAdminInterface->Remove(this);
			return FALSE;
		}
		if (m_nRecvBufferPos < len+5)
			return FALSE;
		else
		{
			int nID = (m_pRecvBuffer[0]&0x7C)>>2;
			if (m_bStillNeedAuth)
			{
				if (nID)
				{
					SendCommand(_T("Protocol error: Not authenticated, closing connection."), 1);
					Close();
					m_pAdminInterface->Remove(this);
					return FALSE;
				}
				if (len != 16)
				{
					SendCommand(_T("Protocol error: Auth data len invalid, closing connection."), 1);
					Close();
					m_pAdminInterface->Remove(this);
					return FALSE;
				}
				MD5 md5;
				md5.update(m_Nonce1, 8);
				COptions options;
				CStdString pass = options.GetOption(OPTION_ADMINPASS);
				if (pass.GetLength() < 6)
				{
					SendCommand(_T("Protocol error: Server misconfigured, admin password not set correctly"), 1);
					Close();
					m_pAdminInterface->Remove(this);
					return FALSE;
				}
				md5.update((unsigned char *)pass.c_str(), pass.GetLength());
				md5.update(m_Nonce2, 8);
				md5.finalize();
				unsigned char *digest = md5.raw_digest();
				if (memcmp(m_pRecvBuffer + 5, digest, 16))
				{
					SendCommand(_T("Protocol error: Auth failed, closing connection."), 1);
					Close();
					m_pAdminInterface->Remove(this);
					return FALSE;
				}
				delete [] digest;

				FinishLogon();
			}
			else
				m_pAdminInterface->ProcessCommand(this, nID, m_pRecvBuffer+5, len);
			memmove(m_pRecvBuffer, m_pRecvBuffer+len+5, m_nRecvBufferPos-len-5);
			m_nRecvBufferPos-=len+5;
		}
	}
	return TRUE;
}
void CEnemyPsycrow::Update(float fElapsedTime)
{
	COptions *op = COptions::GetInstance();
	CSGD_ObjectManager *pOM = CSGD_ObjectManager::GetInstance();
	CSGD_MessageSystem *pMS = CSGD_MessageSystem::GetInstance();
	CSGD_EventSystem *pES= CSGD_EventSystem::GetInstance();
	CGame *theGame = CGame::GetInstance();

	if (m_nState % 2 == 0)
	{
		SetVelY(sin(m_fSineFloat) * 50 * op->GetDifficulty() * (m_nState + 0.5));
		rEnemyRect.top = 507;
		rEnemyRect.bottom = 561;
		rEnemyRect.left = 584;
		rEnemyRect.right = 650;

		if (!bIsFiring)
			m_fFireReady -= fElapsedTime;
		
		if (m_fFireReady <= 0)
			bIsFiring = true;

		if (bIsFiring)
		{
			m_fFiringTimer -= fElapsedTime;
			if (m_fFiringTimer <= 0.5f && m_fFiringTimer > 0.4f)
			{
				rEnemyRect.top = 507;
				rEnemyRect.bottom = 561;
				rEnemyRect.left = 494;
				rEnemyRect.right = 566;
				if (!bIsFired)
				{
					pES->SendEvent("psycrow fire", NULL);
					bIsFired = true;

				}
			}
			else if (m_fFiringTimer <= 0.4f && m_fFiringTimer > 0.3f)
			{
				rEnemyRect.top = 507;
				rEnemyRect.bottom = 567;
				rEnemyRect.left = 790;
				rEnemyRect.right = 856;
			}
			else if (m_fFiringTimer <= 0.3f && m_fFiringTimer > 0.2f)
			{
				rEnemyRect.top = 511;
				rEnemyRect.bottom = 564;
				rEnemyRect.left = 873;
				rEnemyRect.right = 935;
			}
			else if (m_fFiringTimer <= 0.2f && m_fFiringTimer > 0.1f)
			{
				rEnemyRect.top = 581;
				rEnemyRect.bottom = 641;
				rEnemyRect.left = 502;
				rEnemyRect.right = 573;
			}
			else if (m_fFiringTimer <= 0.1f)
			{
				rEnemyRect.top = 579;
				rEnemyRect.bottom = 639;
				rEnemyRect.left = 601;
				rEnemyRect.right = 673;
				bIsFiring = false;
				bIsFired = false;
				m_fFireReady = 5.0f;
				m_fFiringTimer = 0.5f;
			}

		}
	}
	else if (m_nState % 2 == 1)
	{
		rEnemyRect.top = 666;
		rEnemyRect.bottom = 726;
		DWORD timer = GetTickCount();
		if (timer % 300 <= 100)
		{
			rEnemyRect.left = 494;
			rEnemyRect.right = 533;
		}
		else if (timer % 300 > 100 && timer % 300 <= 200)
		{
			rEnemyRect.left = 542;
			rEnemyRect.right = 581;
		}
		else if (timer % 300 > 200)
		{
			rEnemyRect.left = 591;
			rEnemyRect.right = 630;
		}
	}

	if (GetHP() < op->GetDifficulty() * 200 && m_nState == PSYCROW_STATE1)
	{
		rEnemyRect.top = 674;
		rEnemyRect.bottom = 726;
		m_fHitTimer -= fElapsedTime;
		if (m_fHitTimer <= 0.4f && m_fHitTimer > 0.3f)
		{
			CSGD_WaveManager::GetInstance()->Play(m_nSoundID,0);
			rEnemyRect.left = 649;
			rEnemyRect.right = 708;
		}
		else if (m_fHitTimer <= 0.3f && m_fHitTimer > 0.2f)
		{
			rEnemyRect.left = 719;
			rEnemyRect.right = 772;
		}
		else if (m_fHitTimer <= 0.2f && m_fHitTimer > 0.1f)
		{
			rEnemyRect.left = 787;
			rEnemyRect.right = 844;
		}
		else if (m_fHitTimer <= 0.1f && m_fHitTimer > 0.0f)
		{
			rEnemyRect.left = 861;
			rEnemyRect.right = 912;
		}

		if (m_fHitTimer < 0)
			pES->SendEvent("state transition 1");
	}
	if (GetHP() < op->GetDifficulty() * 150 && m_nState == PSYCROW_STATE2)
	{
		rEnemyRect.top = 674;
		rEnemyRect.bottom = 726;
		m_fHitTimer -= fElapsedTime;
		if (m_fHitTimer <= 0.4f && m_fHitTimer > 0.3f)
		{
			CSGD_WaveManager::GetInstance()->Play(m_nSoundID,0);
			rEnemyRect.left = 649;
			rEnemyRect.right = 708;
		}
		else if (m_fHitTimer <= 0.3f && m_fHitTimer > 0.2f)
		{
			rEnemyRect.left = 719;
			rEnemyRect.right = 772;
		}
		else if (m_fHitTimer <= 0.2f && m_fHitTimer > 0.1f)
		{
			rEnemyRect.left = 787;
			rEnemyRect.right = 844;
		}
		else if (m_fHitTimer <= 0.1f && m_fHitTimer > 0.0f)
		{
			rEnemyRect.left = 861;
			rEnemyRect.right = 912;
		}

		if (m_fHitTimer < 0)
			pES->SendEvent("state transition 2");
	}
	if (GetHP() < op->GetDifficulty() * 100 && m_nState == PSYCROW_STATE3)
	{
		rEnemyRect.top = 674;
		rEnemyRect.bottom = 726;
		m_fHitTimer -= fElapsedTime;
		if (m_fHitTimer <= 0.4f && m_fHitTimer > 0.3f)
		{
			CSGD_WaveManager::GetInstance()->Play(m_nSoundID,0);
			rEnemyRect.left = 649;
			rEnemyRect.right = 708;
		}
		else if (m_fHitTimer <= 0.3f && m_fHitTimer > 0.2f)
		{
			rEnemyRect.left = 719;
			rEnemyRect.right = 772;
		}
		else if (m_fHitTimer <= 0.2f && m_fHitTimer > 0.1f)
		{
			rEnemyRect.left = 787;
			rEnemyRect.right = 844;
		}
		else if (m_fHitTimer <= 0.1f && m_fHitTimer > 0.0f)
		{
			rEnemyRect.left = 861;
			rEnemyRect.right = 912;
		}

		if (m_fHitTimer < 0)
			pES->SendEvent("state transition 3");
	}
	if (GetHP() < op->GetDifficulty() * 50 && m_nState == PSYCROW_STATE4)
	{
		rEnemyRect.top = 674;
		rEnemyRect.bottom = 726;
		m_fHitTimer -= fElapsedTime;
		if (m_fHitTimer <= 0.4f && m_fHitTimer > 0.3f)
		{
			CSGD_WaveManager::GetInstance()->Play(m_nSoundID,0);
			rEnemyRect.left = 649;
			rEnemyRect.right = 708;
		}
		else if (m_fHitTimer <= 0.3f && m_fHitTimer > 0.2f)
		{
			rEnemyRect.left = 719;
			rEnemyRect.right = 772;
		}
		else if (m_fHitTimer <= 0.2f && m_fHitTimer > 0.1f)
		{
			rEnemyRect.left = 787;
			rEnemyRect.right = 844;
		}
		else if (m_fHitTimer <= 0.1f && m_fHitTimer > 0.0f)
		{
			rEnemyRect.left = 861;
			rEnemyRect.right = 912;
		}

		if (m_fHitTimer < 0)
			pES->SendEvent("state transition 4");
	}
	if (GetHP() <= 0 && m_nState == PSYCROW_STATE5)
	{
		pMS->SendMsg(new CDestroyMessage(this));
	}

	if (CPlayerCharacter::GetInstance()->GetPosX() < GetPosX())
		SetXFlip(-1);
	else if (CPlayerCharacter::GetInstance()->GetPosX() >= GetPosX())
		SetXFlip(1);

	SetPosX(GetPosX() + GetVelX() * fElapsedTime);
	SetPosY(GetPosY() + GetVelY() * fElapsedTime);

	if (m_fSineFloat <= -3.14f)
		m_fSineFloat = 3.14f;

	m_fSineFloat -= fElapsedTime;

	rCollisionRect.left = GetPosX();
	rCollisionRect.right = GetPosX() + GetWidth();
	rCollisionRect.top = GetPosY();
	rCollisionRect.bottom = GetPosY() + GetHeight();
	SetCollisionRect(rCollisionRect);

	if (GetPosX() < -32)
	{
		SetVelX(-1 * GetVelX());
		SetPosX(-31);
	}
	else if (GetPosX() > 600)
	{
		SetVelX(-1 * GetVelX());
		SetPosX(599);
	}
	if (GetPosY() < 0)
	{
		SetVelY(-1 * GetVelY());
		SetPosY(1);
	}
	else if (GetPosY() > 400)
	{
		SetVelY(-abs(GetVelY()));
		SetPosY(399);
	}

	DWORD timer = GetTickCount();

}
void CEnemyPsycrow::HandleEvent(CEvent *pEvent)
{
	CSGD_ObjectFactory<string, CBase> *pOF		= CSGD_ObjectFactory<string, CBase>::GetInstance();
	CSGD_ObjectManager *pOM						= CSGD_ObjectManager::GetInstance();
 	CSGD_TextureManager *pTM = CSGD_TextureManager::GetInstance();
	COptions *op = COptions::GetInstance();

	if (pEvent->GetEventID() == "psycrow fire")
	{
		pBullet = pOF->CreateObject("CBulletHook");

		pBullet->SetImageID(GetImageID());

		if (GetState() == PSYCROW_STATE1)
		{
			if (CPlayerCharacter::GetInstance()->GetPosX() > GetPosX())
				pBullet->SetVelX(op->GetDifficulty() * 150);
			else
				pBullet->SetVelX(op->GetDifficulty() * -150);
			if (CPlayerCharacter::GetInstance()->GetPosY() > GetPosY())
				pBullet->SetVelY(op->GetDifficulty() * 150);
			else
				pBullet->SetVelY(op->GetDifficulty() * -150);
			pBullet->SetScoreValue(1);
		}
		else if (GetState() == PSYCROW_STATE3)
		{
			if (CPlayerCharacter::GetInstance()->GetPosX() > GetPosX())
				pBullet->SetVelX(0);
			else
				pBullet->SetVelX(0);
			if (CPlayerCharacter::GetInstance()->GetPosY() > GetPosY())
				pBullet->SetVelY(0);
			else
				pBullet->SetVelY(0);
			pBullet->SetScoreValue(2);
		}
		else if (GetState() == PSYCROW_STATE5)
		{
			if (CPlayerCharacter::GetInstance()->GetPosX() > GetPosX())
				pBullet->SetVelX(op->GetDifficulty() * 50);
			else
				pBullet->SetVelX(op->GetDifficulty() * -50);
			if (CPlayerCharacter::GetInstance()->GetPosY() > GetPosY())
				pBullet->SetVelY(op->GetDifficulty() * 50);
			else
				pBullet->SetVelY(op->GetDifficulty() * -50);
			pBullet->SetScoreValue(3);
		}


		pBullet->SetPosX(GetPosX() + (GetXFlip() * 64));
		pBullet->SetPosY(GetPosY() + 48);
		pBullet->SetType(ACTOR_BULLET);

		pBullet->SetHeight(12);
		pBullet->SetWidth(28);
		pBullet->SetPower(5 * op->GetDifficulty());

		pOM->AddObject(pBullet);
	}

	else if (pEvent->GetEventID() == "state transition 1")
	{
		m_nState = PSYCROW_STATE2;
		m_nColor = 200;
		m_fHitTimer = 0.4f;
		SetVelX(100 * op->GetDifficulty());
		SetVelY(150 * op->GetDifficulty());
		SetPower(5 * COptions::GetInstance()->GetDifficulty());
		CGamePlay::GetInstance()->SetBridgeVelocity(COptions::GetInstance()->GetDifficulty() * 50);
		if (CPlayerCharacter::GetInstance()->GetPosX() < GetPosX())
			SetXFlip(-1);
		else if (CPlayerCharacter::GetInstance()->GetPosX() >= GetPosX())
			SetXFlip(1);
	}
	else if (pEvent->GetEventID() == "state transition 2")
	{
		m_nState = PSYCROW_STATE3;
		m_nColor = 150;
		m_fHitTimer = 0.4f;
		SetPower(0);
		SetVelX(75 * op->GetDifficulty() * m_nState);
		CGamePlay::GetInstance()->SetBridgeVelocity(COptions::GetInstance()->GetDifficulty() * 75);
		if (CPlayerCharacter::GetInstance()->GetPosX() < GetPosX())
			SetXFlip(-1);
		else if (CPlayerCharacter::GetInstance()->GetPosX() >= GetPosX())
			SetXFlip(1);
	}
	else if (pEvent->GetEventID() == "state transition 3")
	{
		m_nState = PSYCROW_STATE4;
		m_nColor = 100;
		m_fHitTimer = 0.4f;
		SetVelX(250 * op->GetDifficulty());
		SetVelY(150 * op->GetDifficulty());
		SetPower(5 * COptions::GetInstance()->GetDifficulty());
		CGamePlay::GetInstance()->SetBridgeVelocity(COptions::GetInstance()->GetDifficulty() * 100);
		if (CPlayerCharacter::GetInstance()->GetPosX() < GetPosX())
			SetXFlip(-1);
		else if (CPlayerCharacter::GetInstance()->GetPosX() >= GetPosX())
			SetXFlip(1);
	}
	else if (pEvent->GetEventID() == "state transition 4")
	{
		m_nState = PSYCROW_STATE5;
		m_nColor = 50;
		m_fHitTimer = 0.4f;
		SetPower(0);
		SetVelX(75 * op->GetDifficulty() * m_nState);
		CGamePlay::GetInstance()->SetBridgeVelocity(COptions::GetInstance()->GetDifficulty() * 125);
		if (CPlayerCharacter::GetInstance()->GetPosX() < GetPosX())
			SetXFlip(-1);
		else if (CPlayerCharacter::GetInstance()->GetPosX() >= GetPosX())
			SetXFlip(1);
	}

}
void CGamePlay::Enter()
{
	COptions *op = COptions::GetInstance();
	CSGD_ObjectFactory<string, CBase> *pOF		= CSGD_ObjectFactory<string, CBase>::GetInstance();
	CSGD_ObjectManager *pOM						= CSGD_ObjectManager::GetInstance();
	CSGD_TextureManager *pTM					= CSGD_TextureManager::GetInstance();
	CPlayerCharacter *pPC						= CPlayerCharacter::GetInstance();
	CSGD_EventSystem *pEM						= CSGD_EventSystem::GetInstance();
	CSGD_DirectSound *pDS						= CSGD_DirectSound::GetInstance();
	CSGD_WaveManager* pWM						= CSGD_WaveManager::GetInstance();


	m_nBridgeOffset = 0;
	m_nSpaceOffset = 0;
	m_nEnemyCounter = 0;
	m_nTotalSpawns = 0;

	stateTimer = 6.0f;
	m_fSpawnPowerupTimer = 15.0f;

	//	Register classes with ObjectFactory
	pEM->RegisterClient("scroll right", this);
	pEM->RegisterClient("scroll left", this);
	pEM->RegisterClient("spawn enemies",this);
	pEM->RegisterClient("spawn powerups",this);

	pOF->RegisterClassType<CPlayerCharacter>("CPlayerCharacter");
	pOF->RegisterClassType<CBullet>("CBullet");
	pOF->RegisterClassType<CEnemyDemon>("CEnemyDemon");
	pOF->RegisterClassType<CEnemyBusiness>("CEnemyBusiness");
	pOF->RegisterClassType<CBulletPaper>("CBulletPaper");
	pOF->RegisterClassType<CEnemyMeat>("CEnemyMeat");
	pOF->RegisterClassType<CBulletFire>("CBulletFire");
	pOF->RegisterClassType<CEnemyBooger>("CEnemyBooger");
	pOF->RegisterClassType<CPowerup1up>("CPowerup1up");
	pOF->RegisterClassType<CPowerupHealth>("CPowerupHealth");
	pOF->RegisterClassType<CPowerupRapidFire>("CPowerupRapidFire");
	pOF->RegisterClassType<CPowerupThreeWay>("CPowerupThreeWay");
	pOF->RegisterClassType<CEnemyPsycrow>("CEnemyPsycrow");
	pOF->RegisterClassType<CBulletHook>("CBulletHook");

	m_nImageID[0] = pTM->LoadTexture("Resource\\JoA_EarthwormJim.bmp", D3DCOLOR_XRGB(80,192,64));
	m_nImageID[1] = pTM->LoadTexture("Resource\\JoA_jim_level2enemies.png",D3DCOLOR_XRGB(0,64,128));
	m_nImageID[2] = pTM->LoadTexture("Resource\\JoA_ewj2-flaminyawn.png",D3DCOLOR_XRGB(0,64,128));
	m_nImageID[3] = pTM->LoadTexture("Resource\\JoA_earthwormjim-items.png",D3DCOLOR_XRGB(0,128,255));
	m_nImageID[4] = pTM->LoadTexture("Resource\\JoA_ewj_forpete.png",D3DCOLOR_XRGB(0,64,128));
	m_nBGID		  = pTM->LoadTexture("Resource\\JoA_jim_psycro.png", D3DCOLOR_XRGB(0,64,128));

	pOM->AddObject(CPlayerCharacter::GetInstance());

	m_fFinishedTimer = 5.0f;

	m_Font.SetFontImageID( CSGD_TextureManager::GetInstance()->LoadTexture("resource/JoA_023 - small.bmp", D3DCOLOR_XRGB(0, 0, 0)) );
	m_Font.SetCharWidth( 16 );
	m_Font.SetCharHeight( 16 );
	m_Font.SetNumCols( 10 );
	m_Font.SetStartChar( ' ' );

	m_Font2.SetFontImageID( CSGD_TextureManager::GetInstance()->LoadTexture("resource/JoA_023 - large.bmp", D3DCOLOR_XRGB(0, 0, 0)) );
	m_Font2.SetCharWidth( 32 );
	m_Font2.SetCharHeight( 32 );
	m_Font2.SetNumCols( 10 );
	m_Font2.SetStartChar( ' ' );

	pPC->SetBulletScale(1.0f);
	pPC->SetRateOfFire(7);
	pPC->SetHP(100);
	pPC->SetPosX( 100.0f );
	pPC->SetImageID(m_nImageID[0]);
	pPC->SetThreeWay(false);
	pPC->SetGodMode(false);
	pPC->SetVelX(0.00000004f);
	pPC->SetVelY(0.00000004f);
	pPC->SetInvulnerable(false);
	pPC->SetRapidFireTimer(0.0f);
	pPC->SetThreeWayTimer(0.0f);
	if (GetLevel() == 1)
	{
		pPC->SetPosY( 202.0f );
		SetRemainingEnemies(10);
		m_nBGMusicID = pWM->LoadWave("Resource/sounds/JoA_Song3.wav");
		pWM->SetVolume(m_nBGMusicID,op->GetMusicVolume() - 25);
	}
	else if (GetLevel() == 2)
	{
		pPC->SetPosY(375.0f);
		SetRemainingEnemies(10);
		m_nBGMusicID = pWM->LoadWave("Resource/sounds/JoA_Song4.wav");
		pWM->SetVolume(m_nBGMusicID,op->GetMusicVolume() - 25);
	}
	else if (GetLevel() == 3)
	{
		pPC->SetPosY(250.0f);
		SetRemainingEnemies(1);
		m_nBridgeOffsetY = 300;
		m_nBridgeVelocityY = 25 * op->GetDifficulty();
		pEM->SendEvent("spawn enemies", NULL);
		m_nBGMusicID = pWM->LoadWave("Resource/sounds/JoA_Song2.wav");
		pWM->SetVolume(m_nBGMusicID,op->GetMusicVolume() - 25);
	}

	pWM->Play(m_nBGMusicID,1);
}
Пример #22
0
LRESULT CServer::OnServerMessage(WPARAM wParam, LPARAM lParam)
{
	if (wParam==FSM_STATUSMESSAGE)
	{
		t_statusmsg *msg=reinterpret_cast<t_statusmsg *>(lParam);
		CStdString str;

		FILETIME fFileTime;
		SystemTimeToFileTime(&msg->time, &fFileTime);
		_int64 time = ((_int64)fFileTime.dwHighDateTime<<32) + fFileTime.dwLowDateTime;
		
		str.Format("(%06d)- %s (%s)> %s", msg->userid, (LPCTSTR)msg->user, (LPCTSTR)msg->ip, (LPCTSTR)msg->status);
		ShowStatus(time, str, msg->type);
		delete [] msg->user;
		delete [] msg->status;
		delete msg;
	}
	else if (wParam==FSM_CONNECTIONDATA)
	{
		t_connop *pConnOp = reinterpret_cast<t_connop*>(lParam);
		if (pConnOp->op != USERCONTROL_CONNOP_REMOVE)
			m_UsersList[pConnOp->data->userid] = *pConnOp->data;
		else
		{
			std::map<int, t_connectiondata>::iterator iter=m_UsersList.find(pConnOp->data->userid);
			if (iter!=m_UsersList.end())
				m_UsersList.erase(iter);
		}
		USES_CONVERSION;
		int userlen = pConnOp->data->user ? strlen(pConnOp->data->user) : 0;
		int len = 2 + 4 + strlen(pConnOp->data->ip)+2 + 4 + userlen+2;
		unsigned char *buffer = new unsigned char[len];
		buffer[0] = USERCONTROL_CONNOP;
		buffer[1] = pConnOp->op;
		memcpy(buffer+2, &pConnOp->data->userid, 4);
		buffer[2 + 4] = strlen(pConnOp->data->ip)/256;
		buffer[2 + 4 + 1] = strlen(pConnOp->data->ip)%256;
		memcpy(buffer + 2 + 4 + 2, T2CA(pConnOp->data->ip), strlen(T2CA(pConnOp->data->ip)));
		memcpy(buffer + 2 + 4 +2 + strlen(pConnOp->data->ip)+2, &pConnOp->data->port, 4);
		buffer[2 + 4 + strlen(pConnOp->data->ip)+2 + 4]= userlen/256;
		buffer[2 + 4 + strlen(pConnOp->data->ip)+2 + 4 + 1]= userlen%256;
		if (pConnOp->data->user)
			memcpy(buffer + 2 + 4 + strlen(pConnOp->data->ip)+2 + 4 + 2, T2CA(pConnOp->data->user), userlen);
		m_pAdminInterface->SendCommand(2, 3, buffer, len);
		delete [] buffer;
		delete pConnOp->data;
		delete pConnOp;
	}
	else if (wParam==FSM_THREADCANQUIT)
	{
		CServerThread *pThread=(CServerThread *)lParam;
		for (std::list<CServerThread *>::iterator iter=m_ThreadArray.begin(); iter!=m_ThreadArray.end(); iter++)
		{
			if (*iter==pThread)
			{
				HANDLE handle=pThread->m_hThread;
				pThread->PostThreadMessage(WM_QUIT, 0, 0);
				int res=WaitForSingleObject(handle, INFINITE);
				if (res==WAIT_FAILED)
					res=GetLastError();
				m_ThreadArray.erase(iter);
				if (!m_ThreadArray.size())
				{
					if (!m_bQuit)
						ShowStatus(_T("Server offline."), 1);
					else
						DestroyWindow(m_hWnd);
				}
				break;
			}
			
		}
	}
	else if (wParam==FSM_SEND)
	{
		char buffer[5];
		buffer[0] = 1;
		memcpy(buffer+1, &lParam, 4);
		m_pAdminInterface->SendCommand(2, 7, buffer, 5);
		m_nSendCount += lParam;
	}
	else if (wParam==FSM_RECV)
	{
		char buffer[5];
		buffer[0] = 0;
		memcpy(buffer+1, &lParam, 4);
		m_pAdminInterface->SendCommand(2, 7, buffer, 5);
		m_nRecvCount += lParam;
	}
	else if (wParam == FSM_RELOADCONFIG)
	{
		COptions options;
		options.ReloadConfig();
		CPermissions perm;
		perm.ReloadConfig();
	}
	return 0;
}
Пример #23
0
void SetServer(TiXmlElement *node, const CServer& server)
{
	if (!node)
		return;

	static bool initialized = false;
	static bool kiosk_mode = false;
	if (!initialized)
	{
		COptions* pOptions = COptions::Get();
		if (pOptions)
		{
			initialized = true;
			if (pOptions->GetDefaultVal(DEFAULT_KIOSKMODE) != 0)
				kiosk_mode = true;
		}
	}

	node->Clear();

	AddTextElement(node, "Host", server.GetHost());
	AddTextElement(node, "Port", server.GetPort());
	AddTextElement(node, "Protocol", server.GetProtocol());
	AddTextElement(node, "Type", server.GetType());

	enum LogonType logonType = server.GetLogonType();

	if (server.GetLogonType() != ANONYMOUS)
	{
		AddTextElement(node, "User", server.GetUser());

		if (server.GetLogonType() == NORMAL || server.GetLogonType() == ACCOUNT)
		{
			if (kiosk_mode)
				logonType = ASK;
			else
			{
				AddTextElement(node, "Pass", server.GetPass());

				if (server.GetLogonType() == ACCOUNT)
					AddTextElement(node, "Account", server.GetAccount());
			}
		}
	}
	AddTextElement(node, "Logontype", logonType);

	AddTextElement(node, "TimezoneOffset", server.GetTimezoneOffset());
	switch (server.GetPasvMode())
	{
	case MODE_PASSIVE:
		AddTextElementRaw(node, "PasvMode", "MODE_PASSIVE");
		break;
	case MODE_ACTIVE:
		AddTextElementRaw(node, "PasvMode", "MODE_ACTIVE");
		break;
	default:
		AddTextElementRaw(node, "PasvMode", "MODE_DEFAULT");
		break;
	}
	AddTextElement(node, "MaximumMultipleConnections", server.MaximumMultipleConnections());

	switch (server.GetEncodingType())
	{
	case ENCODING_AUTO:
		AddTextElementRaw(node, "EncodingType", "Auto");
		break;
	case ENCODING_UTF8:
		AddTextElementRaw(node, "EncodingType", "UTF-8");
		break;
	case ENCODING_CUSTOM:
		AddTextElementRaw(node, "EncodingType", "Custom");
		AddTextElement(node, "CustomEncoding", server.GetCustomEncoding());
		break;
	}

	const enum ServerProtocol protocol = server.GetProtocol();
	if (protocol == FTP || protocol == FTPS || protocol == FTPES)
	{
		const std::vector<wxString>& postLoginCommands = server.GetPostLoginCommands();
		if (!postLoginCommands.empty())
		{
			TiXmlElement* pElement = node->LinkEndChild(new TiXmlElement("PostLoginCommands"))->ToElement();
			for (std::vector<wxString>::const_iterator iter = postLoginCommands.begin(); iter != postLoginCommands.end(); iter++)
				AddTextElement(pElement, "Command", *iter);
		}
	}

	AddTextElementRaw(node, "BypassProxy", server.GetBypassProxy() ? "1" : "0");
	const wxString& name = server.GetName();
	if (name != _T(""))
		AddTextElement(node, "Name", name);
}
Пример #24
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);
		//}
}
Пример #25
0
UINT_PTR CALLBACK CFileDialog::AddDialogProc(HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(wParam);

    COptions *pOptions = g_app.GetOptions();

    switch (uiMsg)
    {
    case WM_INITDIALOG:
        ::SendMessage(GetDlgItem(hdlg, IDC_INCLUDE), CB_LIMITTEXT, MAX_PATH - 1, 0);
        ::SendMessage(GetDlgItem(hdlg, IDC_EXCLUDE), EM_LIMITTEXT, MAX_PATH - 1, 0);
        CheckDlgButton(hdlg, IDC_AUTO_START, pOptions->GetAutoStart(TRUE));
        EnableWindow(GetDlgItem(hdlg, IDC_CHECK_NEW_ONLY), pOptions->GetAutoStart(TRUE));
        CheckDlgButton(hdlg, IDC_CHECK_NEW_ONLY, pOptions->GetCheckNewOnly(TRUE));
        SendMessage(GetDlgItem(hdlg, IDC_INCLUDE), CB_ADDSTRING, 0, (LPARAM)MOD_INCLUDE_COMMON);
        SendMessage(GetDlgItem(hdlg, IDC_INCLUDE), CB_ADDSTRING, 0, (LPARAM)MOD_INCLUDE_EXE);
        SendMessage(GetDlgItem(hdlg, IDC_INCLUDE), CB_ADDSTRING, 0, (LPARAM)MOD_INCLUDE_ALL);
        SetDlgItemText(hdlg, IDC_INCLUDE, pOptions->GetInclude(TRUE));
        SetDlgItemText(hdlg, IDC_EXCLUDE, pOptions->GetExclude(TRUE));
        CheckDlgButton(hdlg, IDC_RECURSE, pOptions->GetRecurse(TRUE));
        CheckDlgButton(hdlg, IDC_SAVE_SETTINGS, FALSE);
        return (UINT_PTR)TRUE;

    case WM_NOTIFY:
        switch (((LPNMHDR)lParam)->code)
        {
        case CDN_FOLDERCHANGE:
            // POST
            PostMessage(GetParent(hdlg), CDM_SETCONTROLTEXT, edt1, (LPARAM)pOptions->GetOFNFolder());
            break;

        case CDN_FILEOK:
            if (IsDlgButtonChecked(hdlg, IDC_SAVE_SETTINGS) == BST_CHECKED)
                pOptions->SetFlag(COptions::OnceAdd | COptions::OnceCheck, COptions::OnceCheck);
            else
                pOptions->SetFlag(COptions::OnceAdd | COptions::OnceCheck, COptions::OnceAdd | COptions::OnceCheck);
            pOptions->SetAutoStart(IsDlgButtonChecked(hdlg, IDC_AUTO_START) == BST_CHECKED);
            pOptions->SetCheckNewOnly(IsDlgButtonChecked(hdlg, IDC_CHECK_NEW_ONLY) == BST_CHECKED);
            GetDlgItemText(hdlg, IDC_INCLUDE, (LPTSTR)pOptions->GetInclude(), MAX_PATH);
            GetDlgItemText(hdlg, IDC_EXCLUDE, (LPTSTR)pOptions->GetExclude(), MAX_PATH);
            pOptions->SetRecurse(IsDlgButtonChecked(hdlg, IDC_RECURSE) == BST_CHECKED);
            if (IsDlgButtonChecked(hdlg, IDC_SAVE_SETTINGS) == BST_CHECKED)
                pOptions->SavePage(MOPSP_ADD);
            break;
        }
        break;

    case WM_COMMAND:
        switch (wParam)
        {
        case MAKEWPARAM(IDC_AUTO_START, BN_CLICKED):
            EnableWindow(GetDlgItem(hdlg, IDC_CHECK_NEW_ONLY), IsDlgButtonChecked(hdlg, IDC_AUTO_START) == BST_CHECKED);
            break;
        }
        break;
    }

    return (UINT_PTR)FALSE;
}
Пример #26
0
UINT_PTR CALLBACK CFileDialog::SaveToDialogProc(HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(wParam);

    COptions *pOptions = g_app.GetOptions();

    switch (uiMsg)
    {
    case WM_INITDIALOG:
        CheckRadioButton(hdlg, IDC_ID_SPACE_ASTERISK, IDC_ID_VERTICAL_BAR, IDC_ID_SPACE_ASTERISK + pOptions->GetItemDelimiter(TRUE));
        CheckRadioButton(hdlg, IDC_LF_CR_LF, IDC_LF_CR, IDC_LF_CR_LF + pOptions->GetLineFeed(TRUE));
        CheckRadioButton(hdlg, IDC_PD_BACKSLASH, IDC_PD_SLASH, IDC_PD_BACKSLASH + pOptions->GetPathDelimiter(TRUE));
        CheckDlgButton(hdlg, IDC_SAVE_TO_FULL_PATH, pOptions->GetSaveToFullPath(TRUE));
        CheckDlgButton(hdlg, IDC_SAVE_SETTINGS, FALSE);
        return (UINT_PTR)TRUE;

    case WM_NOTIFY:
        switch (((LPNMHDR)lParam)->code)
        {
        case CDN_FILEOK:
            if (IsDlgButtonChecked(hdlg, IDC_SAVE_SETTINGS) == BST_CHECKED)
                pOptions->SetFlag(COptions::OnceSave, 0);
            else
                pOptions->SetFlag(COptions::OnceSave, COptions::OnceSave);
            if (IsDlgButtonChecked(hdlg, IDC_ID_SPACES) == BST_CHECKED)
                pOptions->SetItemDelimiter(MOE_ID_SPACES);
            else if (IsDlgButtonChecked(hdlg, IDC_ID_VERTICAL_BAR) == BST_CHECKED)
                pOptions->SetItemDelimiter(MOE_ID_VERTICAL_BAR);
            else
                pOptions->SetItemDelimiter(MOE_ID_SPACE_ASTERISK);
            if (IsDlgButtonChecked(hdlg, IDC_LF_LF) == BST_CHECKED)
                pOptions->SetLineFeed(MOE_LF_LF);
            else if (IsDlgButtonChecked(hdlg, IDC_LF_CR) == BST_CHECKED)
                pOptions->SetLineFeed(MOE_LF_CR);
            else
                pOptions->SetLineFeed(MOE_LF_CR_LF);
            if (IsDlgButtonChecked(hdlg, IDC_PD_SLASH) == BST_CHECKED)
                pOptions->SetPathDelimiter(MOE_PD_SLASH);
            else
                pOptions->SetPathDelimiter(MOE_PD_BACKSLASH);
            pOptions->SetSaveToFullPath(IsDlgButtonChecked(hdlg, IDC_SAVE_TO_FULL_PATH) == BST_CHECKED);
            if (IsDlgButtonChecked(hdlg, IDC_SAVE_SETTINGS) == BST_CHECKED)
                pOptions->SavePage(MOPSP_SAVE);
            break;
        }
        break;
    }

    return (UINT_PTR)FALSE;
}
Пример #27
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;
}
Пример #28
0
void CUpdateWizard::ParseData()
{
	const wxLongLong ownVersionNumber = CBuildInfo::ConvertToVersionNumber(CBuildInfo::GetVersion());

	wxString newVersion;
	wxLongLong newVersionNumber = -1;
	wxString newUrl;
	wxString newChecksum;

	while (m_data != _T(""))
	{
		wxString line;
		int pos = m_data.Find('\n');
		if (pos != -1)
		{
			line = m_data.Left(pos);
			m_data = m_data.Mid(pos + 1);
		}
		else
		{
			line = m_data;
			m_data = _T("");
		}

		line.Trim(true);
		line.Trim(false);

		if (line == _T(""))
		{
			// After empty line, changelog follows
			m_news = m_data;
			m_news.Trim(true);
			m_news.Trim(false);
			break;
		}

		// Extract type of update
		pos = line.Find(' ');
		if (pos < 1)
			continue;

		wxString type = line.Left(pos);
		line = line.Mid(pos + 1);

		// Extract version/date
		pos = line.Find(' ');
		if (pos < 1)
			continue;

		wxString versionOrDate = line.Left(pos);
		line = line.Mid(pos + 1);

		// Extract URL
		wxString url = line;
		if (url == _T("none"))
			url = _T("");

		pos = url.Find(' ');
		if (pos < 1)
			newChecksum.clear();
		else
		{
			newChecksum = url.Mid(pos + 1);
			url = url.Left(pos);
		}

		if (type == _T("nightly"))
		{
			if (!m_loaded)
				continue;

			if (!XRCCTRL(*this, "ID_CHECKNIGHTLY", wxCheckBox)->GetValue())
				continue;

			wxDateTime nightlyDate;
			if (!nightlyDate.ParseDate(versionOrDate))
				continue;

			wxDateTime buildDate = CBuildInfo::GetBuildDate();
			if (!buildDate.IsValid() || !nightlyDate.IsValid() || nightlyDate <= buildDate)
				continue;

			if (url == _T(""))
				continue;

			newVersion = versionOrDate + _T(" Nightly");
			newUrl = url;
			break;
		}
		else
		{
			wxLongLong v = CBuildInfo::ConvertToVersionNumber(versionOrDate);
			if (v <= ownVersionNumber)
				continue;
		}

		newVersion = versionOrDate;
		newVersionNumber = CBuildInfo::ConvertToVersionNumber(versionOrDate);
		newUrl = url;
	}

	if (!m_loaded)
	{
		if (newVersion == _T(""))
			return;

		COptions* pOptions = COptions::Get();
		pOptions->SetOption(OPTION_UPDATECHECK_NEWVERSION, newVersion);

		DisplayUpdateAvailability(true);

		return;
	}
	else
	{
		// Since the auto check and the manual check, a newer version might have been published
		COptions* pOptions = COptions::Get();
		if (!pOptions->GetOption(OPTION_UPDATECHECK_NEWVERSION).empty())
			pOptions->SetOption(OPTION_UPDATECHECK_NEWVERSION, newVersion);
	}

	if (newVersion == _T(""))
	{
		m_skipPageChanging = true;
		ShowPage(m_pages[4]);
		m_currentPage = 4;
		m_skipPageChanging = false;
	}
	else
	{
		PrepareUpdateAvailablePage(newVersion, newUrl, newChecksum);

		m_skipPageChanging = true;
		ShowPage(m_pages[1]);
		m_currentPage = 1;
		m_skipPageChanging = false;
	}

	wxButton* pNext = wxDynamicCast(FindWindow(wxID_FORWARD), wxButton);
	pNext->Enable();
	wxButton* pPrev = wxDynamicCast(FindWindow(wxID_BACKWARD), wxButton);
	pPrev->Disable();
}
Пример #29
0
LRESULT APIENTRY SkypeAPI_WindowProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp)
{
	LRESULT lReturnCode = 0;
	bool bIssueDefProc = false;

	switch (msg) {
	case WM_DESTROY:
		g_wndMainWindow = NULL;
		break;

	case WM_COPYDATA:
		break;

	default:
		if (msg == g_MsgIDSkypeControlAPIAttach) {
			switch (lp) {
			case SKYPECONTROLAPI_ATTACH_SUCCESS:
				{
					CStatusInfo si;
					{
						mir_cslock guard(g_csStatusInfo);
						si = g_CurrStatusInfo;
					}
					if (INVALID_INDEX != si.StatusIndex() && si.StatusIndex() < _countof(g_aStatusCode)) {
						const CMirandaStatus2SkypeStatus& ms = g_aStatusCode[si.StatusIndex()];
						HWND wndSkypeAPIWindow = reinterpret_cast<HWND>(wp);

						enum { BUFFER_SIZE = 256 };
						char szSkypeCmd[BUFFER_SIZE];
						const char szSkypeCmdSetStatus[] = "SET USERSTATUS ";
						::strncpy_s(szSkypeCmd, szSkypeCmdSetStatus, sizeof(szSkypeCmdSetStatus) / sizeof(szSkypeCmdSetStatus[0]));
						::strncat_s(szSkypeCmd, ms.m_pszSkypeStatus, _countof(szSkypeCmd) - mir_strlen(szSkypeCmd));
						DWORD cLength = static_cast<DWORD>(mir_strlen(szSkypeCmd));

						COPYDATASTRUCT oCopyData;
						oCopyData.dwData = 0;
						oCopyData.lpData = szSkypeCmd;
						oCopyData.cbData = cLength + 1;
						SendMessage(wndSkypeAPIWindow, WM_COPYDATA, (WPARAM)hWnd, (LPARAM)&oCopyData);
						if (g_Options.GetSyncStatusMsgFlag()) {
							TCHAR* pszStatusMsg = NULL;
							if (ProtoServiceExists(si.Module(), PS_GETMYAWAYMSG))
								pszStatusMsg = reinterpret_cast<TCHAR*>(CallProtoService(si.Module(), PS_GETMYAWAYMSG, (WPARAM)ms.m_nMirandaStatus, SGMA_TCHAR));

							if ((NULL == pszStatusMsg) || (CALLSERVICE_NOTFOUND == INT_PTR(pszStatusMsg)))
								pszStatusMsg = reinterpret_cast<TCHAR*>(CallService(MS_AWAYMSG_GETSTATUSMSGT, (WPARAM)ms.m_nMirandaStatus, 0));

							if (pszStatusMsg && reinterpret_cast<LPARAM>(pszStatusMsg) != CALLSERVICE_NOTFOUND) {
								T2Utf pMsg(pszStatusMsg);
								mir_free(pszStatusMsg);

								const char szSkypeCmdSetStatusMsg[] = "SET PROFILE MOOD_TEXT ";
								::strncpy_s(szSkypeCmd, szSkypeCmdSetStatusMsg, sizeof(szSkypeCmdSetStatusMsg) / sizeof(szSkypeCmdSetStatusMsg[0]));
								::strncat_s(szSkypeCmd, pMsg, _countof(szSkypeCmd) - mir_strlen(szSkypeCmd));

								oCopyData.dwData = 0;
								oCopyData.lpData = szSkypeCmd;
								oCopyData.cbData = static_cast<DWORD>(mir_strlen(szSkypeCmd)) + 1;
								SendMessage(wndSkypeAPIWindow, WM_COPYDATA, (WPARAM)hWnd, (LPARAM)&oCopyData);
							}
						}
					}
				}
				break;

			case SKYPECONTROLAPI_ATTACH_PENDING_AUTHORIZATION:
				break;

			case SKYPECONTROLAPI_ATTACH_REFUSED:
				break;

			case SKYPECONTROLAPI_ATTACH_NOT_AVAILABLE:
				break;

			case SKYPECONTROLAPI_ATTACH_API_AVAILABLE:
				break;
			}
			lReturnCode = 1;
		}
		else bIssueDefProc = true;
		break;
	}

	if (true == bIssueDefProc)
		lReturnCode = DefWindowProc(hWnd, msg, wp, lp);

	return lReturnCode;
}