int ZipFile( const WCHAR* inputFile, const WCHAR* outputFile, int method, int compressionLevel ) { int err = -1; if ( ( inputFile != NULL ) && ( outputFile != NULL ) ) { NSFile::CFileBinary oFile; if(oFile.OpenFile(inputFile)) { DWORD dwSizeRead; BYTE* pData = new BYTE[oFile.GetFileSize()]; if(oFile.ReadFile(pData, oFile.GetFileSize(), dwSizeRead)) { zipFile zf = zipOpenHelp(outputFile); zip_fileinfo zi; zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; zi.dosDate = 0; zi.internal_fa = 0; zi.external_fa = 0; #if defined(_WIN32) || defined (_WIN64) SYSTEMTIME currTime; GetLocalTime( &currTime ); zi.tmz_date.tm_sec = currTime.wSecond; zi.tmz_date.tm_min = currTime.wMinute; zi.tmz_date.tm_hour = currTime.wHour; zi.tmz_date.tm_mday = currTime.wDay; zi.tmz_date.tm_mon = currTime.wMonth; zi.tmz_date.tm_year = currTime.wYear; #endif wstring inputFileName( inputFile ); wstring::size_type pos = 0; static const wstring::size_type npos = -1; pos = inputFileName.find_last_of( L'\\' ); wstring zipFileName; if ( pos != npos ) { zipFileName = wstring( ( inputFileName.begin() + pos + 1 ), inputFileName.end() ); } else { zipFileName = wstring( inputFileName.begin(), inputFileName.end() ); } std::string zipFileNameA = codepage_issue_fixToOEM(zipFileName); err = zipOpenNewFileInZip( zf, zipFileNameA.c_str(), &zi, NULL, 0, NULL, 0, NULL, method, compressionLevel ); err = zipWriteInFileInZip( zf, pData, dwSizeRead ); err = zipCloseFileInZip( zf ); err = zipClose( zf, NULL ); } RELEASEARRAYOBJECTS(pData); } } return false; }
void OutLookHotmailConnector::GetDownloadConfigurationAndTempFile(ConfigurationFileActionDownload& downloadVersion, wstring& tempFile) { wchar_t szTempPath[MAX_PATH]; GetTempPath(MAX_PATH, szTempPath); downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(MSOfficeLPIActionID, wstring(L"OutlookHotmailConnector")); tempFile = szTempPath; tempFile += downloadVersion.GetFilename().c_str(); m_installerLocation = tempFile; }
/*************************************************************************** * bitwise Not operator * (1) take value from stack * (2) ~result(1) * (3) push result (2) ***************************************************************************/ void CCilVm::bitwiseNotOperator() { assert( getEvalStackSize() >= 1 ); CVariable& lhs = getEvalStackFirstEntry(); int32_t i; int64_t i64; if( lhs.iOperandType == OPERAND_OBJECTREF ) { OPERAND_TYPE lhsType = lhs.getPrimitiveType( PRIMITIVETYPE_NUMBER ); switch( lhsType ) { case OPERAND_OBJECTREF: //Throw TypeError popEvalStack(); pushEvalStackNaN(); ThrowExceptionFromVm( &wstring( ERRORSTRING_TYPEERROR_STORESTATICFIELD ), &wstring( NAME_BUILTIN_ERROR_OBJECT ), ERROR_TYPEERROR_STORESTATICFIELD ); return; case OPERAND_UNDEFINED: popEvalStack(); pushEvalStackUndefined(); return; case OPERAND_NAN: popEvalStack(); pushEvalStackNaN(); return; case OPERAND_STRING: case OPERAND_DOUBLE: case OPERAND_FLOAT: case OPERAND_INT: case OPERAND_BOOLEAN: i = ~lhs.toInt(); popEvalStack(); pushEvalStack( i ); return; case OPERAND_INT64: i64 = ~lhs.toInt64(); popEvalStack(); pushEvalStack( i64 ); return; default: Debug_Fatal( "Not implemented yet" ); } } switch( lhs.iOperandType ) { case OPERAND_INT: lhs.iValue = ~lhs.iValue; break; case OPERAND_INT64: lhs.i64Value = ~lhs.i64Value; break; case OPERAND_NAN: popEvalStack(); pushEvalStackNaN(); break; case OPERAND_UNDEFINED: popEvalStack(); pushEvalStackUndefined(); break; case OPERAND_STRING: case OPERAND_FLOAT: case OPERAND_BOOLEAN: case OPERAND_DOUBLE: case OPERAND_NULL: i = ~lhs.toInt(); popEvalStack(); pushEvalStack( i ); break; case OPERAND_OBJECTREF: Debug_Fatal( "Illegal operand" ); break; default: Debug_Fatal( "Illegal operand" ); break; } }
/** * Lifecycle: load */ void FrameServer::load(HWND toolbar, HWND target, const wstring& uuid, const wstring& title, const wstring& icon, DWORDX processId, INT_PTRX proxy) { logger->debug(L"FrameServer::load" L" -> " + boost::lexical_cast<wstring>(toolbar) + L" -> " + boost::lexical_cast<wstring>(target) + L" -> " + uuid + L" -> " + title + L" -> " + icon + L" -> " + boost::lexical_cast<wstring>(processId) + L" -> " + boost::lexical_cast<wstring>(proxy)); ATL::CComCritSecLock<CComAutoCriticalSection> lock(m_clientLock, true); if (processId != ::GetCurrentProcessId() && m_clientListeners.find(processId) == m_clientListeners.end()) { // add IPC channel for proxy if it is in a different process m_clientListeners[processId] = ClientListener(new Channel(L"IeBarMsgPoint", processId), 1); if (m_clientListeners.size() == 1) { m_activeProcessId = processId; m_activeProxy = proxy; } } // only initialize the first time if (++m_tabCount != 1) { logger->debug(L"FrameServer::load already initialized"); lock.Unlock(); return; } m_toolbar = toolbar; m_target = target; // subclass windows m_oldWndProcToolbar = (WndProcPtr)::GetWindowLongPtr(m_toolbar, GWLP_WNDPROC); ::SetWindowLongPtr(m_toolbar, GWLP_WNDPROC, (LONG_PTR)WndProcToolbarS); m_oldWndProcTarget = (WndProcPtr)::GetWindowLongPtr(m_target, GWLP_WNDPROC); ::SetWindowLongPtr(m_target, GWLP_WNDPROC, (LONG_PTR)WndProcTargetS); lock.Unlock(); // add button HRESULT hr; Button button; hr = button_addCommand(uuid.c_str(), title.c_str(), icon.c_str()).exec(toolbar, target, &button); if (FAILED(hr)) { logger->error(L"FrameServer::load failed to create button" L" -> " + logger->parse(hr)); ::MessageBox(NULL, wstring(L"Forge could not create button. Please check that " L"your icon file is a 16x16 bitmap in .ico format: " L"'" + icon + L"'").c_str(), VENDOR_COMPANY_NAME, MB_TASKMODAL | MB_ICONEXCLAMATION); return; } lock.Lock(); m_buttons[uuid] = button; lock.Unlock(); }
const std::wstring generic_wstring() const { return wstring(codecvt()); }
void MountOptionsDialog::OnMountPointButtonClick (wxCommandEvent& event) { DirectoryPath dir = Gui->SelectDirectory (this, wxEmptyString, false); if (!dir.IsEmpty()) MountPointTextCtrl->SetValue (wstring (dir)); }
void KeyfileGeneratorDialog::OnGenerateButtonClick (wxCommandEvent& event) { try { int keyfilesCount = NumberOfKeyfiles->GetValue(); int keyfilesSize = KeyfilesSize->GetValue(); bool useRandomSize = RandomSizeCheckBox->IsChecked(); wxString keyfileBaseName = KeyfilesBaseName->GetValue(); keyfileBaseName.Trim(true); keyfileBaseName.Trim(false); if (keyfileBaseName.IsEmpty()) { Gui->ShowWarning("KEYFILE_EMPTY_BASE_NAME"); return; } wxFileName baseFileName = wxFileName::FileName (keyfileBaseName); if (!baseFileName.IsOk()) { Gui->ShowWarning("KEYFILE_INVALID_BASE_NAME"); return; } DirectoryPath keyfilesDir = Gui->SelectDirectory (Gui->GetActiveWindow(), LangString["SELECT_KEYFILE_GENERATION_DIRECTORY"], false); if (keyfilesDir.IsEmpty()) return; wxFileName dirFileName = wxFileName::DirName( wstring(keyfilesDir).c_str() ); if (!dirFileName.IsDirWritable ()) { Gui->ShowWarning(L"You don't have write permission on the selected directory"); return; } wxBusyCursor busy; for (int i = 0; i < keyfilesCount; i++) { int bufferLen; if (useRandomSize) { SecureBuffer sizeBuffer (sizeof(int)); RandomNumberGenerator::GetData (sizeBuffer, true); memcpy(&bufferLen, sizeBuffer.Ptr(), sizeof(int)); /* since keyfilesSize < 1024 * 1024, we mask with 0x000FFFFF */ bufferLen = (long) (((unsigned long) bufferLen) & 0x000FFFFF); bufferLen %= ((1024*1024 - 64) + 1); bufferLen += 64; } else bufferLen = keyfilesSize; SecureBuffer keyfileBuffer (bufferLen); RandomNumberGenerator::GetData (keyfileBuffer, true); wstringstream convertStream; convertStream << i; wxString suffix = L"_"; suffix += convertStream.str().c_str(); wxFileName keyfileName; if (i == 0) { keyfileName.Assign(dirFileName.GetPath(), keyfileBaseName); } else { if (baseFileName.HasExt()) { keyfileName.Assign(dirFileName.GetPath(), baseFileName.GetName() + suffix + L"." + baseFileName.GetExt()); } else { keyfileName.Assign(dirFileName.GetPath(), keyfileBaseName + suffix); } } if (keyfileName.Exists()) { wxString msg = wxString::Format(LangString["KEYFILE_ALREADY_EXISTS"], keyfileName.GetFullPath()); if (!Gui->AskYesNo (msg, false, true)) return; } { FilePath keyfilePath((const wchar_t*) keyfileName.GetFullPath()); File keyfile; keyfile.Open (keyfilePath, File::CreateWrite); keyfile.Write (keyfileBuffer); } } Gui->ShowInfo ("KEYFILE_CREATED"); } catch (exception &e) { Gui->ShowError (e); } }
Json::String Json::multibyte() const { return UnicodeToMultibyte(wstring()); }
wstring QueryAssembler::CreateQuery(const FilledFrame& targetFrame, const NetEvaluator& evaluator, std::wstring& question) { wstring toReturn = L""; currentFrameTense = targetFrame.GetTense(); wstring qTemplate = getQueryTemplateFromDB(targetFrame.GetSemanticFrame()->GetFrameName(), pathToDb); queryTemplate = parseTemplate(qTemplate); vector<wstring> queryParts; queryParts.push_back(L""); wstring queryClause; bool timeSpecified = false; for(auto slot_p = targetFrame.GetSlotIterator(); slot_p != targetFrame.GetSlotEndIterator(); slot_p++) { if((*slot_p)->GetNetName() == CONST_QUERY) //if this is a [Query] slot, we extract key word for question type for it: why, where, when... { question = evaluator.Evaluate(*slot_p, currentFrameTense)[NetEvaluator::VALUE]; } try { if(queryTemplate.find((*slot_p)->GetNetName()) != queryTemplate.end()) { queryClause = interpolate(queryTemplate.at((*slot_p)->GetNetName()), *slot_p, evaluator); if((*slot_p)->IsExternal()) //now it just means that we encountered time expression { timeSpecified = true; } if(queryClause.find(L"SELECT") == 0) //we reserve first position for the SELECT clause { if(queryClause.find(L"WHERE") == wstring::npos) queryClause.append(L" WHERE 1=1"); queryParts[0] = queryClause; } else if(!queryClause.empty()) // other parts of the query are joined by conjunction { queryClause = wstring(L" AND ").append(queryClause); queryParts.push_back(queryClause); } } } catch(...) { throw EInvalidTemplate(targetFrame.GetSemanticFrame()->GetFrameName().c_str()); } } if(queryParts[0].empty()) //if we didn't find any slot which could determine source table we force select from Afisha { //throw 0; queryParts[0] = L"SELECT Year, Sport, Event, Athlete, Result, Medal, Country, Country_Taker, City_Taker, Season, COUNT(*) as Times FROM OlympData WHERE 1=1"; } if(!timeSpecified) //if we didn't find any slot which could determine time we set default timex slot based on tense { Slots def_timex = createDefaultTimex(currentFrameTense); shared_ptr<IMatch> def_time_match = shared_ptr<IMatch>(new TimexMatch(def_timex)); //Print("/home/stepan/zz.txt", queryTemplate); wstring sdklfdjfdskljfds = def_time_match->GetNetName(); queryClause = L" AND " + interpolate(queryTemplate.at(def_time_match->GetNetName()), def_time_match, evaluator); queryParts.push_back(queryClause); } for(size_t i = 0; i < queryParts.size(); i++) { toReturn.append(queryParts[i]); } return toReturn; }
EXPORT void Import(string scPluginCfgFile, bool emptyFail) { int boardIndex = 0; string boardIndexStr = ""; string errorMessage = ""; Data::ParameterSet parameters; INI_Reader ini; if (!ini.open(scPluginCfgFile.c_str(), false)) { Common::PrintConInfo(L"Can't read config file. Don't see any possibility to load. Aborted.", true); return; } while (ini.read_header()) { if (ini.is_header("API")) { Sync::APILogin login; Sync::APIServer server; boardIndex++; while (ini.read_value()) { if (ini.is_value("URI")) { login.URI = ini.get_value_string(0); } else if (ini.is_value("Account")) { login.Account = ini.get_value_string(0); } else if (ini.is_value("Password")) { login.Password = ini.get_value_string(0); } else if (ini.is_value("Secret")) { login.Secret = Misc::Encode::stringToInt(ini.get_value_string(0)); } else if (ini.is_value("Queue")) { login.Queue = ini.get_value_int(0); } else if (ini.is_value("Operation")) { login.Operations.push_back(ini.get_value_string(0)); } else if (ini.is_value("Response")) { login.Responses.push_back(ini.get_value_string(0)); } } if (login.URI == "" || login.Account == "" || login.Password == "") { boardIndexStr = itos(boardIndex); Common::PrintConInfo(L"There is an error on configuration: At least one of the parameter (URI, Account, Password) is missing for [API] " + wstring(boardIndexStr.begin(), boardIndexStr.end()) + L". Ignoring.\r\n", true); continue; } try { server = Sync::Client::Get(login); Data::ParameterData data; data[L"Name"] = server.Name; data[L"LastSent"] = (uint)server.LastSent; data[L"Queue"] = server.QueueLimit; data[L"Delay"] = server.Delay; Data::Parameter parameter(data); parameters.push_back(parameter); } catch (exception &e) { errorMessage = e.what(); Common::PrintConInfo(L"Got a failure when try to load setting for API " + wstring(login.URI.begin(), login.URI.end()) + L": " + wstring(errorMessage.begin(), errorMessage.end())); } } } Config::Config::APIs = parameters; ini.close(); if (emptyFail && boardIndex <= 0) { Common::PrintConInfo(L"No board information. Don't see why loading. Aborted.", true); return; } }
wstring Gine::Utils::ToWString(const string* s) { return wstring(s->begin(), s->end()); }
/// set the window text. // @function set_text def set_text(Str text) { SetWindowTextW(this->hwnd,wstring(text)); return 0; }
static wstring getDir(const wstring& path) { wchar_t drive[_MAX_DRIVE] = {0}, dir[_MAX_DIR] = {0}; _wsplitpath_s(path.c_str(), drive, _MAX_DRIVE, dir, _MAX_DIR, NULL, 0, NULL, 0); return wstring(drive) + wstring(dir); }
bool update() { writeLog(L"Update started.."); wstring updDir = L"tupdates\\temp", readyFilePath = L"tupdates\\temp\\ready", tdataDir = L"tupdates\\temp\\tdata"; { HANDLE readyFile = CreateFile(readyFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (readyFile != INVALID_HANDLE_VALUE) { CloseHandle(readyFile); } else { updDir = L"tupdates\\ready"; // old tdataDir = L"tupdates\\ready\\tdata"; } } HANDLE versionFile = CreateFile((tdataDir + L"\\version").c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (versionFile != INVALID_HANDLE_VALUE) { if (!ReadFile(versionFile, &versionNum, sizeof(DWORD), &readLen, NULL) || readLen != sizeof(DWORD)) { versionNum = 0; } else { if (versionNum == 0x7FFFFFFF) { // beta version } else if (!ReadFile(versionFile, &versionLen, sizeof(DWORD), &readLen, NULL) || readLen != sizeof(DWORD) || versionLen > 63) { versionNum = 0; } else if (!ReadFile(versionFile, versionStr, versionLen, &readLen, NULL) || readLen != versionLen) { versionNum = 0; } } CloseHandle(versionFile); writeLog(L"Version file read."); } else { writeLog(L"Could not open version file to update registry :("); } deque<wstring> dirs; dirs.push_back(updDir); deque<wstring> from, to, forcedirs; do { wstring dir = dirs.front(); dirs.pop_front(); wstring toDir = updateTo; if (dir.size() > updDir.size() + 1) { toDir += (dir.substr(updDir.size() + 1) + L"\\"); forcedirs.push_back(toDir); writeLog(L"Parsing dir '" + toDir + L"' in update tree.."); } WIN32_FIND_DATA findData; HANDLE findHandle = FindFirstFileEx((dir + L"\\*").c_str(), FindExInfoStandard, &findData, FindExSearchNameMatch, 0, 0); if (findHandle == INVALID_HANDLE_VALUE) { DWORD errorCode = GetLastError(); if (errorCode == ERROR_PATH_NOT_FOUND) { // no update is ready return true; } writeLog(L"Error: failed to find update files :("); updateError(L"Failed to find update files", errorCode); delFolder(); return false; } do { wstring fname = dir + L"\\" + findData.cFileName; if (fname.substr(0, tdataDir.size()) == tdataDir && (fname.size() <= tdataDir.size() || fname.at(tdataDir.size()) == '/')) { writeLog(L"Skipped 'tdata' path '" + fname + L"'"); } else if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (findData.cFileName != wstring(L".") && findData.cFileName != wstring(L"..")) { dirs.push_back(fname); writeLog(L"Added dir '" + fname + L"' in update tree.."); } } else { wstring tofname = updateTo + fname.substr(updDir.size() + 1); if (equal(tofname, updaterName)) { // bad update - has Updater.exe - delete all dir writeLog(L"Error: bad update, has Updater.exe! '" + tofname + L"' equal '" + updaterName + L"'"); delFolder(); return false; } else if (equal(tofname, updateTo + L"Telegram.exe") && exeName != L"Telegram.exe") { wstring fullBinaryPath = updateTo + exeName; writeLog(L"Target binary found: '" + tofname + L"', changing to '" + fullBinaryPath + L"'"); tofname = fullBinaryPath; } if (equal(fname, readyFilePath)) { writeLog(L"Skipped ready file '" + fname + L"'"); } else { from.push_back(fname); to.push_back(tofname); writeLog(L"Added file '" + fname + L"' to be copied to '" + tofname + L"'"); } } } while (FindNextFile(findHandle, &findData)); DWORD errorCode = GetLastError(); if (errorCode && errorCode != ERROR_NO_MORE_FILES) { // everything is found writeLog(L"Error: failed to find next update file :("); updateError(L"Failed to find next update file", errorCode); delFolder(); return false; } FindClose(findHandle); } while (!dirs.empty()); for (size_t i = 0; i < forcedirs.size(); ++i) { wstring forcedir = forcedirs[i]; writeLog(L"Forcing dir '" + forcedir + L"'.."); if (!forcedir.empty() && !CreateDirectory(forcedir.c_str(), NULL)) { DWORD errorCode = GetLastError(); if (errorCode && errorCode != ERROR_ALREADY_EXISTS) { writeLog(L"Error: failed to create dir '" + forcedir + L"'.."); updateError(L"Failed to create directory", errorCode); delFolder(); return false; } writeLog(L"Already exists!"); } } for (size_t i = 0; i < from.size(); ++i) { wstring fname = from[i], tofname = to[i]; BOOL copyResult; do { writeLog(L"Copying file '" + fname + L"' to '" + tofname + L"'.."); int copyTries = 0; do { copyResult = CopyFile(fname.c_str(), tofname.c_str(), FALSE); if (!copyResult) { ++copyTries; Sleep(100); } else { break; } } while (copyTries < 100); if (!copyResult) { writeLog(L"Error: failed to copy, asking to retry.."); WCHAR errMsg[2048]; wsprintf(errMsg, L"Failed to update Telegram :(\n%s is not accessible.", tofname.c_str()); if (MessageBox(0, errMsg, L"Update error!", MB_ICONERROR | MB_RETRYCANCEL) != IDRETRY) { delFolder(); return false; } } } while (!copyResult); } writeLog(L"Update succeed! Clearing folder.."); delFolder(); return true; }
Socket *CreateClientSocket(const wchar_t *host, uint16_t port, int timeoutMS) { char portstr[7] = {0}; StringFormat::snprintf(portstr, 6, "%d", port); addrinfo hints; RDCEraseEl(hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; wstring hostWide = wstring(host); string hoststr = narrow(hostWide); if(widen(hoststr) != hostWide) RDCWARN("Unicode hostname truncated: %S", hostWide.c_str()); addrinfo *result = NULL; getaddrinfo(hoststr.c_str(), portstr, &hints, &result); for(addrinfo *ptr = result; ptr != NULL; ptr = ptr->ai_next) { int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(s == -1) return NULL; int flags = fcntl(s, F_GETFL, 0); fcntl(s, F_SETFL, flags | O_NONBLOCK); int result = connect(s, ptr->ai_addr, (int)ptr->ai_addrlen); if(result == -1) { fd_set set; FD_ZERO(&set); FD_SET(s, &set); int err = errno; if(err == EWOULDBLOCK) { timeval timeout; timeout.tv_sec = (timeoutMS/1000); timeout.tv_usec = (timeoutMS%1000)*1000; result = select(0, NULL, &set, NULL, &timeout); if(result <= 0) { RDCDEBUG("connect timed out"); close(s); continue; } else { RDCDEBUG("connect before timeout"); } } else { RDCDEBUG("problem other than blocking"); close(s); continue; } } else { RDCDEBUG("connected immediately"); } int nodelay = 1; setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay)); return new Socket((ptrdiff_t)s); } RDCWARN("Failed to connect to %S:%d", host, port); return NULL; }
bptr < WideString > Util::toWideString(const std::string & s) { bptr < WideString > wstring(new WideString(s.c_str())); return wstring; };
wstring extract(const wchar_t* end_chars) { size_t start = pos; while (!end() && !is_one_of(text[pos], end_chars)) pos++; return wstring(text.data() + start, pos - start); }
bool MSOfficeLPIAction::Download(ProgressStatus progress, void *data) { bool bFile1, bFile2; ConfigurationFileActionDownload downloadVersion; assert(_getDownloadID() != NULL); downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(GetID(), wstring(_getDownloadID())); wcscpy_s(m_szFilename, downloadVersion.GetFilename().c_str()); wcscpy_s(m_szFullFilename, m_szTempPath); wcscat_s(m_szFullFilename, m_szFilename); bFile1 = m_downloadManager->GetFileAndVerifyAssociatedSha1(downloadVersion, m_szFullFilename, progress, data); if (_needsInstallConnector()) { downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(GetID(), wstring(L"OutlookHotmailConnector")); m_connectorFile = m_szTempPath; m_connectorFile += downloadVersion.GetFilename().c_str(); bFile2 = m_downloadManager->GetFileAndVerifyAssociatedSha1(downloadVersion, m_connectorFile, progress, data); return bFile1 == true && bFile2 == true; } else { return bFile1; } }
// Print the properties for the given snasphot void VssClient::PrintSnapshotProperties(VSS_SNAPSHOT_PROP & prop) { FunctionTracer ft(DBG_INFO); LONG lAttributes = prop.m_lSnapshotAttributes; ft.WriteLine(L"* SNAPSHOT ID = " WSTR_GUID_FMT L" ...", GUID_PRINTF_ARG(prop.m_SnapshotId)); ft.WriteLine(L" - Shadow copy Set: " WSTR_GUID_FMT, GUID_PRINTF_ARG(prop.m_SnapshotSetId)); ft.WriteLine(L" - Original count of shadow copies = %d", prop.m_lSnapshotsCount); ft.WriteLine(L" - Original Volume name: %s [%s]", prop.m_pwszOriginalVolumeName, GetDisplayNameForVolume(prop.m_pwszOriginalVolumeName).c_str() ); ft.WriteLine(L" - Creation Time: %s", VssTimeToString(prop.m_tsCreationTimestamp).c_str()); ft.WriteLine(L" - Shadow copy device name: %s", prop.m_pwszSnapshotDeviceObject); ft.WriteLine(L" - Originating machine: %s", prop.m_pwszOriginatingMachine); ft.WriteLine(L" - Service machine: %s", prop.m_pwszServiceMachine); if (prop.m_lSnapshotAttributes & VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY) ft.WriteLine(L" - Exposed locally as: %s", prop.m_pwszExposedName); else if (prop.m_lSnapshotAttributes & VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY) { ft.WriteLine(L" - Exposed remotely as %s", prop.m_pwszExposedName); if (prop.m_pwszExposedPath && wcslen(prop.m_pwszExposedPath) > 0) ft.WriteLine(L" - Path exposed: %s", prop.m_pwszExposedPath); } else ft.WriteLine(L" - Not Exposed"); ft.WriteLine(L" - Provider id: " WSTR_GUID_FMT, GUID_PRINTF_ARG(prop.m_ProviderId)); // Display the attributes wstring attributes; if (lAttributes & VSS_VOLSNAP_ATTR_TRANSPORTABLE) attributes += wstring(L" Transportable"); if (lAttributes & VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE) attributes += wstring(L" No_Auto_Release"); else attributes += wstring(L" Auto_Release"); if (lAttributes & VSS_VOLSNAP_ATTR_PERSISTENT) attributes += wstring(L" Persistent"); if (lAttributes & VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE) attributes += wstring(L" Client_accessible"); if (lAttributes & VSS_VOLSNAP_ATTR_HARDWARE_ASSISTED) attributes += wstring(L" Hardware"); if (lAttributes & VSS_VOLSNAP_ATTR_NO_WRITERS) attributes += wstring(L" No_Writers"); if (lAttributes & VSS_VOLSNAP_ATTR_IMPORTED) attributes += wstring(L" Imported"); if (lAttributes & VSS_VOLSNAP_ATTR_PLEX) attributes += wstring(L" Plex"); if (lAttributes & VSS_VOLSNAP_ATTR_DIFFERENTIAL) attributes += wstring(L" Differential"); ft.WriteLine(L" - Attributes: %s", attributes.c_str()); ft.WriteLine(L""); }
wstring get_console_title() { Buffer<wchar_t> buf(10000); DWORD size = GetConsoleTitleW(buf.data(), static_cast<DWORD>(buf.size())); return wstring(buf.data(), size); }
/** * ProxyListen */ DWORD FrameServer::ProxyListen(LPVOID param) { HRESULT hr; logger->debug(L"FrameServer::ProxyListen" L" -> " + boost::lexical_cast<wstring>(param)); FrameServer* pThis = (FrameServer*)param; pThis->m_channel = new Channel(L"IeBarListner", ::GetCurrentProcessId()); while (pThis->m_channel) { char buffer[Channel::SECTION_SIZE]; if (!pThis->m_channel->Read(buffer, Channel::SECTION_SIZE)) { break; } UINTX type = *(UINTX*)buffer; logger->debug(L"FrameServer::ProxyListen" L" -> " + boost::lexical_cast<wstring>(type)); switch(type) { case SendMessageCommand::COMMAND_TYPE: { SendMessageCommand *command = (SendMessageCommand*)buffer; pThis->SendMessage(command->msg, command->wparam, command->lparam); } break; case PostMessageCommand::COMMAND_TYPE: { PostMessageCommand *command = (PostMessageCommand*)buffer; pThis->PostMessage(command->msg, command->wparam, command->lparam); } break; case LoadCommand::COMMAND_TYPE: { LoadCommand *command = (LoadCommand*)buffer; logger->debug(L"FrameServer::ProxyListen LoadCommand" L" -> " + wstring(command->uuid) + L" -> " + wstring(command->title) + L" -> " + wstring(command->icon) + L" -> " + boost::lexical_cast<wstring>(command->addressBarWnd) + L" -> " + boost::lexical_cast<wstring>(command->commandTargetWnd)); pThis->load(reinterpret_cast<HWND>(command->addressBarWnd), reinterpret_cast<HWND>(command->commandTargetWnd), command->uuid, command->title, command->icon, command->processId, command->proxy); } break; case UnloadCommand::COMMAND_TYPE: { UnloadCommand *command = (UnloadCommand*)buffer; pThis->unload(command->processId, command->proxy); } break; case SelectTabCommand::COMMAND_TYPE: { SelectTabCommand *command = (SelectTabCommand*)buffer; pThis->SetCurrentProxy(command->processId, command->proxy); } break; case button_addCommand::COMMAND_TYPE: { Button button; button_addCommand *command = (button_addCommand*)buffer; hr = command->exec(pThis->m_toolbar, pThis->m_target, &button); if (FAILED(hr)) { logger->error(L"FrameServer::ProxyListen button_setIconCommand failed" L" -> " + logger->parse(hr)); } pThis->m_buttons[button.uuid] = button; } break; case button_setIconCommand::COMMAND_TYPE: { button_setIconCommand *command = (button_setIconCommand*)buffer; Button button = pThis->m_buttons[command->uuid]; hr = command->exec(pThis->m_toolbar, pThis->m_target, button.idCommand, button.iBitmap); if (FAILED(hr)) { logger->error(L"FrameServer::ProxyListen button_setIconCommand failed" L" -> " + logger->parse(hr)); } } break; case button_setTitleCommand::COMMAND_TYPE: { button_setTitleCommand *command = (button_setTitleCommand*)buffer; Button button = pThis->m_buttons[command->uuid]; hr = command->exec(pThis->m_toolbar, pThis->m_target, button.idCommand); if (FAILED(hr)) { logger->error(L"FrameServer::ProxyListen button_setTitleCommand failed" L" -> " + logger->parse(hr)); } } break; case button_setBadgeCommand::COMMAND_TYPE: { button_setBadgeCommand *command = (button_setBadgeCommand*)buffer; Button button = pThis->m_buttons[command->uuid]; hr = command->exec(pThis->m_toolbar, pThis->m_target, button.idCommand); if (FAILED(hr)) { logger->error(L"FrameServer::ProxyListen button_setBadgeCommand failed" L" -> " + logger->parse(hr)); } } break; case button_setBadgeBackgroundColorCommand::COMMAND_TYPE: { button_setBadgeBackgroundColorCommand *command = (button_setBadgeBackgroundColorCommand*)buffer; Button button = pThis->m_buttons[command->uuid]; hr = command->exec(pThis->m_toolbar, pThis->m_target, button.idCommand); if (FAILED(hr)) { logger->error(L"FrameServer::ProxyListen button_setBadgeBackgroundColorCommand failed" L" -> " + logger->parse(hr)); } } break; } } return 0; }
wstring upcase(const wstring& str) { Buffer<wchar_t> up_str(str.size()); wmemcpy(up_str.data(), str.data(), str.size()); CharUpperBuffW(up_str.data(), static_cast<DWORD>(up_str.size())); return wstring(up_str.data(), up_str.size()); }
const std::wstring wstring() const { return wstring(codecvt()); }
/*! 内容を書き込む @param[in] hWnd ウインドウハンドル・あまり意味はない @return HRESULT 終了状態コード */ HRESULT VertScriptInsert( HWND hWnd ) { LPTSTR ptText; INT iTgtRow, iMaxRow, iMaxClm; INT iRitDot, iNeedPadd; HWND hLyrWnd; INT iX, iY; RECT rect; wstring wsBuffer; // 作った文字列を入れちゃう VTIM_ITR itVtitm; VTIM_RITR itRvsVtitm; //右からなら逆にたどる。左からなら正順。Rowを基準値にして、直前位置とのスキマは空白埋め //改行とか入れまくって一繋がりの文字列にして、ステルスレイヤで貼る。 // 縦横の大きさを求める iMaxRow = 0; iMaxClm = 0; for( itVtitm = gvcVertItem.begin(); itVtitm != gvcVertItem.end(); itVtitm++ ) { if( iMaxRow < itVtitm->iRow ) iMaxRow = itVtitm->iRow; if( iMaxClm < itVtitm->iColumn ) iMaxClm = itVtitm->iColumn; } ptText = NULL; wsBuffer.clear(); for( iTgtRow = 0; iMaxRow >= iTgtRow; iTgtRow++ ) // 文字位置を上から順番に見ていく { iRitDot = 0; if( gbLeftGo ) // 左から { for( itVtitm = gvcVertItem.begin(); itVtitm != gvcVertItem.end(); itVtitm++ ) { if( iTgtRow == itVtitm->iRow ) // 注目ROWが一致したら { iNeedPadd = itVtitm->iOffset - iRitDot; // ここまでの右端からのドット数 if( 0 > iNeedPadd ) { iNeedPadd = 0; // 重なった場合とかあり得る } ptText = DocPaddingSpaceMake( iNeedPadd ); // 0ならNULLが返る if( ptText ) // 埋め分を継ぎ足す { wsBuffer += wstring( ptText ); FREE( ptText ); } wsBuffer += itVtitm->cch; // 本命の文字を入れる iRitDot += iNeedPadd; // ここまでの埋め量と iRitDot += itVtitm->iWidth; // 使用幅を埋める } } } else { // 右から for( itRvsVtitm = gvcVertItem.rbegin(); itRvsVtitm != gvcVertItem.rend(); itRvsVtitm++ ) { if( iTgtRow == itRvsVtitm->iRow ) // 注目ROWが一致したら { iNeedPadd = itRvsVtitm->iOffset - iRitDot; // ここまでの右端からのドット数 if( 0 > iNeedPadd ) { iNeedPadd = 0; // 重なった場合とかあり得る } ptText = DocPaddingSpaceMake( iNeedPadd ); // 0ならNULLが返る if( ptText ) // 埋め分を継ぎ足す { wsBuffer += wstring( ptText ); FREE( ptText ); } wsBuffer += itRvsVtitm->cch; // 本命の文字を入れる iRitDot += iNeedPadd; // ここまでの埋め量と iRitDot += itRvsVtitm->iWidth; // 使用幅を埋める } } } wsBuffer += wstring( CH_CRLFW ); // 壱行終わったら改行 } // 挿入処理には、レイヤボックスを非表示処理で使う hLyrWnd = LayerBoxVisibalise( GetModuleHandle(NULL), wsBuffer.c_str(), 0x10 ); // レイヤの位置を変更 GetWindowRect( ghVertViewWnd, &rect ); LayerBoxPositionChange( hLyrWnd, (rect.left + gstFrmSz.x), (rect.top + gstFrmSz.y) ); // 設定によれば、空白を全部透過指定にする if( gbSpTrans ) { LayerTransparentToggle( hLyrWnd, 1 ); } // 上書きする LayerContentsImportable( hLyrWnd, IDM_LYB_OVERRIDE, &iX, &iY, D_INVISI ); ViewPosResetCaret( iX, iY ); // 終わったら閉じる DestroyWindow( hLyrWnd ); return S_OK; }
const std::wstring generic_wstring(const codecvt_type& cvt) const { return wstring(cvt); }
bool mod_mimikatz_sekurlsa_livessp::getLiveSSP(vector<wstring> * arguments) { vector<pair<mod_mimikatz_sekurlsa::PFN_ENUM_BY_LUID, wstring>> monProvider; monProvider.push_back(pair<mod_mimikatz_sekurlsa::PFN_ENUM_BY_LUID, wstring>(getLiveSSPLogonData, wstring(L"livessp"))); return mod_mimikatz_sekurlsa::getLogonData(arguments, &monProvider); }
/*! 編集の選択範囲からいただく @param[in] hWnd ウインドウハンドル @param[in] bSqSel 矩形であるかどうか */ UINT DraughtItemAddFromSelect( HWND hWnd, UINT bSqSel ) { LPTSTR ptString = NULL; UINT cchSize, cbSize; LPPOINT pstPos = NULL; UINT_PTR i, j, iTexts; LONG dMin = 0; INT insDot, yLine, iLines = 0, dOffset; LPTSTR ptSpace = NULL; LPSTR pcArts; wstring wsString; // 内部処理なのでUnicode固定 cbSize = DocSelectTextGetAlloc( D_UNI | bSqSel, (LPVOID *)(&ptString), (bSqSel & D_SQUARE) ? &pstPos : NULL ); StringCchLength( ptString, STRSAFE_MAX_CCH, &cchSize ); if( 0 >= cchSize ) return 0; // 文字列ないならなにもしない // オフセット設定が有る場合、その分を埋める空白が必要 if( pstPos ) // 最小オフセット値を探して、そこを左端にする { dMin = pstPos[0].x; yLine = 0; for( i = 0; cchSize > i; i++ ) { if( CC_CR == ptString[i] && CC_LF == ptString[i+1] ) // 改行であったら { // オフセット最小をさがす if( dMin > pstPos[yLine].x ){ dMin = pstPos[yLine].x; } i++; // 0x0D,0x0Aだから、壱文字飛ばすのがポイント yLine++; // 改行したからFocusは次の行へ } } // この時点で、yLineは行数になってる iLines = yLine; // 壱行目の空白を作って閃光入力しておく insDot = 0; dOffset = pstPos[0].x - dMin; ptSpace = DocPaddingSpaceUni( dOffset, NULL, NULL, NULL ); // 前方空白は無視されるのでユニコード使って問題無い StringCchLength( ptSpace, STRSAFE_MAX_CCH, &iTexts ); for( j = 0; iTexts > j; j++ ){ wsString += ptSpace[j]; } FREE(ptSpace); } yLine = 0; insDot = 0; for( i = 0; cchSize > i; i++ ) { if( CC_CR == ptString[i] && CC_LF == ptString[i+1] ) // 改行であったら { wsString += wstring( TEXT("\r\n") ); i++; // 0x0D,0x0Aだから、壱文字飛ばすのがポイント yLine++; // 改行したからFocusは次の行へ // オフセット分の空白を作る if( pstPos && (iLines > yLine) ) { dOffset = pstPos[yLine].x - dMin; ptSpace = DocPaddingSpaceUni( dOffset, NULL, NULL, NULL ); // 前方空白は無視されるのでユニコード使って問題無い StringCchLength( ptSpace, STRSAFE_MAX_CCH, &iTexts ); for( j = 0; iTexts > j; j++ ){ wsString += ptSpace[j]; } FREE(ptSpace); } } else if( CC_TAB == ptString[i] ){ /* タブは挿入しない */ } else{ wsString += ptString[i]; } } FREE(ptString); FREE(pstPos); pcArts = SjisEncodeAlloc( wsString.c_str() ); DraughtItemAdding( hWnd, pcArts ); FREE(pcArts); return yLine; }
CommandLineInterface::CommandLineInterface (wxCmdLineParser &parser, UserInterfaceType::Enum interfaceType) : ArgCommand (CommandId::None), ArgFilesystem (VolumeCreationOptions::FilesystemType::Unknown), ArgNoHiddenVolumeProtection (false), ArgSize (0), ArgVolumeType (VolumeType::Unknown), StartBackgroundTask (false) { parser.SetSwitchChars (L"-"); parser.AddOption (L"", L"auto-mount", _("Auto mount device-hosted/favorite volumes")); parser.AddSwitch (L"", L"backup-headers", _("Backup volume headers")); parser.AddSwitch (L"", L"background-task", _("Start Background Task")); #ifdef TC_WINDOWS parser.AddSwitch (L"", L"cache", _("Cache passwords and keyfiles")); #endif parser.AddSwitch (L"C", L"change", _("Change password or keyfiles")); parser.AddSwitch (L"c", L"create", _("Create new volume")); parser.AddSwitch (L"", L"create-keyfile", _("Create new keyfile")); parser.AddSwitch (L"", L"delete-token-keyfiles", _("Delete security token keyfiles")); parser.AddSwitch (L"d", L"dismount", _("Dismount volume")); parser.AddSwitch (L"", L"display-password", _("Display password while typing")); parser.AddOption (L"", L"encryption", _("Encryption algorithm")); parser.AddSwitch (L"", L"explore", _("Open explorer window for mounted volume")); parser.AddSwitch (L"", L"export-token-keyfile",_("Export keyfile from security token")); parser.AddOption (L"", L"filesystem", _("Filesystem type")); parser.AddSwitch (L"f", L"force", _("Force mount/dismount/overwrite")); #if !defined(TC_WINDOWS) && !defined(TC_MACOSX) parser.AddOption (L"", L"fs-options", _("Filesystem mount options")); #endif parser.AddOption (L"", L"hash", _("Hash algorithm")); parser.AddSwitch (L"h", L"help", _("Display detailed command line help"), wxCMD_LINE_OPTION_HELP); parser.AddSwitch (L"", L"import-token-keyfiles", _("Import keyfiles to security token")); parser.AddOption (L"k", L"keyfiles", _("Keyfiles")); parser.AddSwitch (L"l", L"list", _("List mounted volumes")); parser.AddSwitch (L"", L"list-token-keyfiles", _("List security token keyfiles")); parser.AddSwitch (L"", L"load-preferences", _("Load user preferences")); parser.AddSwitch (L"", L"mount", _("Mount volume interactively")); parser.AddOption (L"m", L"mount-options", _("TrueCrypt volume mount options")); parser.AddOption (L"", L"new-keyfiles", _("New keyfiles")); parser.AddOption (L"", L"new-password", _("New password")); parser.AddSwitch (L"", L"non-interactive", _("Do not interact with user")); parser.AddOption (L"p", L"password", _("Password")); parser.AddOption (L"", L"protect-hidden", _("Protect hidden volume")); parser.AddOption (L"", L"protection-keyfiles", _("Keyfiles for protected hidden volume")); parser.AddOption (L"", L"protection-password", _("Password for protected hidden volume")); parser.AddOption (L"", L"random-source", _("Use file as source of random data")); parser.AddSwitch (L"", L"restore-headers", _("Restore volume headers")); parser.AddSwitch (L"", L"save-preferences", _("Save user preferences")); parser.AddSwitch (L"", L"quick", _("Enable quick format")); parser.AddOption (L"", L"size", _("Size in bytes")); parser.AddOption (L"", L"slot", _("Volume slot number")); parser.AddSwitch (L"", L"test", _("Test internal algorithms")); parser.AddSwitch (L"t", L"text", _("Use text user interface")); parser.AddOption (L"", L"token-lib", _("Security token library")); parser.AddSwitch (L"v", L"verbose", _("Enable verbose output")); parser.AddSwitch (L"", L"version", _("Display version information")); parser.AddSwitch (L"", L"volume-properties", _("Display volume properties")); parser.AddOption (L"", L"volume-type", _("Volume type")); parser.AddParam ( _("Volume path"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL); parser.AddParam ( _("Mount point"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL); wxString str; bool param1IsVolume = false; bool param1IsMountedVolumeSpec = false; bool param1IsMountPoint = false; bool param1IsFile = false; if (parser.Parse () > 0) throw_err (_("Incorrect command line specified.")); if (parser.Found (L"help")) { ArgCommand = CommandId::Help; return; } if (parser.Found (L"text") && interfaceType != UserInterfaceType::Text) { wstring msg = wstring (_("Option -t or --text must be specified as the first argument.")); wcerr << msg << endl; throw_err (msg); } if (parser.Found (L"version")) { ArgCommand = CommandId::DisplayVersion; return; } // Preferences if (parser.Found (L"load-preferences")) { // Load preferences first to allow command line options to override them Preferences.Load(); ArgMountOptions = Preferences.DefaultMountOptions; } // Commands if (parser.Found (L"auto-mount", &str)) { CheckCommandSingle(); wxStringTokenizer tokenizer (str, L","); while (tokenizer.HasMoreTokens()) { wxString token = tokenizer.GetNextToken(); if (token == L"devices") { if (ArgCommand == CommandId::AutoMountFavorites) ArgCommand = CommandId::AutoMountDevicesFavorites; else ArgCommand = CommandId::AutoMountDevices; param1IsMountPoint = true; } else if (token == L"favorites") { if (ArgCommand == CommandId::AutoMountDevices) ArgCommand = CommandId::AutoMountDevicesFavorites; else ArgCommand = CommandId::AutoMountFavorites; } else { throw_err (LangString["UNKNOWN_OPTION"] + L": " + token); } } } if (parser.Found (L"backup-headers")) { CheckCommandSingle(); ArgCommand = CommandId::BackupHeaders; param1IsVolume = true; } if (parser.Found (L"change")) { CheckCommandSingle(); ArgCommand = CommandId::ChangePassword; param1IsVolume = true; } if (parser.Found (L"create")) { CheckCommandSingle(); ArgCommand = CommandId::CreateVolume; param1IsVolume = true; } if (parser.Found (L"create-keyfile")) { CheckCommandSingle(); ArgCommand = CommandId::CreateKeyfile; param1IsFile = true; } if (parser.Found (L"delete-token-keyfiles")) { CheckCommandSingle(); ArgCommand = CommandId::DeleteSecurityTokenKeyfiles; } if (parser.Found (L"dismount")) { CheckCommandSingle(); ArgCommand = CommandId::DismountVolumes; param1IsMountedVolumeSpec = true; } if (parser.Found (L"export-token-keyfile")) { CheckCommandSingle(); ArgCommand = CommandId::ExportSecurityTokenKeyfile; } if (parser.Found (L"import-token-keyfiles")) { CheckCommandSingle(); ArgCommand = CommandId::ImportSecurityTokenKeyfiles; } if (parser.Found (L"list")) { CheckCommandSingle(); ArgCommand = CommandId::ListVolumes; param1IsMountedVolumeSpec = true; } if (parser.Found (L"list-token-keyfiles")) { CheckCommandSingle(); ArgCommand = CommandId::ListSecurityTokenKeyfiles; } if (parser.Found (L"mount")) { CheckCommandSingle(); ArgCommand = CommandId::MountVolume; param1IsVolume = true; } if (parser.Found (L"save-preferences")) { CheckCommandSingle(); ArgCommand = CommandId::SavePreferences; } if (parser.Found (L"test")) { CheckCommandSingle(); ArgCommand = CommandId::Test; } if (parser.Found (L"volume-properties")) { CheckCommandSingle(); ArgCommand = CommandId::DisplayVolumeProperties; param1IsMountedVolumeSpec = true; } // Options if (parser.Found (L"background-task")) StartBackgroundTask = true; #ifdef TC_WINDOWS if (parser.Found (L"cache")) ArgMountOptions.CachePassword = true; #endif ArgDisplayPassword = parser.Found (L"display-password"); if (parser.Found (L"encryption", &str)) { ArgEncryptionAlgorithm.reset(); foreach (shared_ptr <EncryptionAlgorithm> ea, EncryptionAlgorithm::GetAvailableAlgorithms()) { if (!ea->IsDeprecated() && wxString (ea->GetName()).IsSameAs (str, false)) ArgEncryptionAlgorithm = ea; } if (!ArgEncryptionAlgorithm) throw_err (LangString["UNKNOWN_OPTION"] + L": " + str); }
/** Helper method for reading instances from disk \param[in] preader - handle to the physical media reader \param[out] instances - vector of Application Server Instances to insert the values read from disk into */ bool PersistAppServerInstances::ReadFromDiskHelper( SCXHandle<SCXPersistDataReader>& preader, vector<SCXHandle<AppServerInstance> >& instances) { bool isThereAnElement = preader->ConsumeStartGroup(APP_SERVER_INSTANCE, false); if (isThereAnElement) { wstring id, diskPath, httpPort, httpsPort, protocol, isDeepMonitored, type, version, profile, cell, node, server; diskPath = preader->ConsumeValue(APP_SERVER_DISK_PATH); try { id = preader->ConsumeValue(APP_SERVER_ID); } catch(PersistUnexpectedDataException) { // To be backward compatible, we default to disk path if id is not in the persited data id = diskPath; SCX_LOGTRACE(m_log, L"Id not found in persited data, defaulting to disk path"); } httpPort = preader->ConsumeValue(APP_SERVER_HTTP_PORT); httpsPort = preader->ConsumeValue(APP_SERVER_HTTPS_PORT); try { protocol = preader->ConsumeValue(APP_SERVER_PROTOCOL); } catch(PersistUnexpectedDataException) { // To be backward compatible, we default to HTTP if protocol is not in the persited data protocol = PROTOCOL_HTTP; SCX_LOGTRACE(m_log, L"Protocol not found in persited data, defaulting to HTTP"); } isDeepMonitored = preader->ConsumeValue(APP_SERVER_IS_DEEP_MONITORED); type = preader->ConsumeValue(APP_SERVER_TYPE); version = preader->ConsumeValue(APP_SERVER_VERSION); try { profile = preader->ConsumeValue(APP_SERVER_PROFILE); cell = preader->ConsumeValue(APP_SERVER_CELL); node = preader->ConsumeValue(APP_SERVER_NODE); server = preader->ConsumeValue(APP_SERVER_SERVER); } catch(PersistUnexpectedDataException) { // To be backward compatible, we default profile, cell, node & server to // empty strings if they are not in the persited data profile = L""; cell = L""; node = L""; server = L""; SCX_LOGTRACE(m_log, L"WebSphere properties not found in persited data, defaulting to empty strings"); } preader->ConsumeEndGroup(true); SCXHandle<AppServerInstance> instance; bool badType = false; if (APP_SERVER_TYPE_JBOSS == type) { instance = new JBossAppServerInstance(diskPath); } else if (APP_SERVER_TYPE_TOMCAT == type) { instance = new TomcatAppServerInstance(diskPath, diskPath); } else if (APP_SERVER_TYPE_WEBLOGIC == type) { instance = new WebLogicAppServerInstance(diskPath); instance->SetServer(server); } else if (APP_SERVER_TYPE_WEBSPHERE == type) { instance = new WebSphereAppServerInstance(diskPath, cell, node, profile, server); } else { SCX_LOGWARNING(m_log, wstring(L"Unknown application server type read from cache: ").append(type)); badType = true; } if (!badType) { instance->SetHttpPort(httpPort); instance->SetHttpsPort(httpsPort); // This value is a bool, but when written to disk it is // serialized as an integer. instance->SetIsDeepMonitored(L"1" == isDeepMonitored, protocol); // If read from cache, then by default this representation // of the instance is not running instance->SetIsRunning(false); instance->SetVersion(version); instances.push_back(instance); } } return isThereAnElement; }
int ZipDir( const WCHAR* dir, const WCHAR* outputFile, const OnProgressCallback* progress, bool sorted, int method, int compressionLevel ) { if ( ( dir != NULL ) && ( outputFile != NULL ) ) { deque<wstring> StringDeque; deque<wstring> zipDeque; StringDeque.push_back( wstring( dir ) ); wstring zipDir; wstring file; wstring zipFileName; wstring szText; zipFile zf = zipOpenHelp(outputFile); zip_fileinfo zi; zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; zi.dosDate = 0; zi.internal_fa = 0; zi.external_fa = 0; #if defined(_WIN32) || defined (_WIN64) SYSTEMTIME currTime; GetLocalTime( &currTime ); zi.tmz_date.tm_sec = currTime.wSecond; zi.tmz_date.tm_min = currTime.wMinute; zi.tmz_date.tm_hour = currTime.wHour; zi.tmz_date.tm_mday = currTime.wDay; zi.tmz_date.tm_mon = currTime.wMonth; zi.tmz_date.tm_year = currTime.wYear; #endif unsigned int filesCount = get_files_count( dir ); unsigned int currentFileIndex = 0; while ( !StringDeque.empty() ) { szText = StringDeque.front(); StringDeque.pop_front(); if(zipDeque.size() > 0) { zipDir = zipDeque.front() + wstring( L"/" ); zipDeque.pop_front(); } std::vector<std::wstring> aCurFiles = NSDirectory::GetFiles(szText); std::vector<std::wstring> aCurDirectories = NSDirectory::GetDirectories(szText); if (sorted) { std::sort(aCurFiles.begin(), aCurFiles.end()); std::sort(aCurDirectories.begin(), aCurDirectories.end()); } for(size_t i = 0; i < aCurDirectories.size(); ++i) { std::wstring sDirName = NSSystemPath::GetFileName(aCurDirectories[i]); StringDeque.push_back( aCurDirectories[i] ); zipDeque.push_back( zipDir + sDirName ); } for (size_t i = 0; i < aCurFiles.size(); ++i) { std::wstring cFileName = NSSystemPath::GetFileName(aCurFiles[i]); if (std::wstring::npos != cFileName.find(L"mimetype")) // возможно и полное соответствие { file = NSSystemPath::Combine(szText, cFileName); zipFileName = zipDir + cFileName; oneZipFile(zf, zi, file, zipFileName, 0, compressionLevel); aCurFiles.erase(aCurFiles.begin() + i, aCurFiles.begin() + i + 1); break; } } for (size_t i = 0; i < aCurFiles.size(); ++i) { std::wstring cFileName = NSSystemPath::GetFileName(aCurFiles[i]); file = NSSystemPath::Combine(szText, cFileName); zipFileName = zipDir + cFileName; oneZipFile(zf, zi, file, zipFileName, method, compressionLevel); if ( progress != NULL ) { short cancel = 0; long progressValue = ( 1000000 / filesCount * currentFileIndex ); if(NULL != progress) (*progress)( UTILS_ONPROGRESSEVENT_ID, progressValue, &cancel ); if ( cancel != 0 ) { zipClose( zf, NULL ); } } currentFileIndex++; } } zipClose( zf, NULL ); if ( progress != NULL ) { short cancel = 0; long progressValue = 1000000; if(NULL != progress) (*progress)( UTILS_ONPROGRESSEVENT_ID, progressValue, &cancel ); } } return 0; }