DWORD STDMETHODCALLTYPE CUnkownReport::Run() { HRESULT hr = S_OK; HANDLE hEvent[ 2 ] = { NULL, NULL }; WaitForSingleObject( g_hThread, INFINITE ); if ( !g_bInitFalg ) { CRunTimeLog::WriteLog(WINMOD_LLVL_ERROR, L"[CUnkownReport] Load Engine Failed" ); goto Exit0; } hr = CScanEngineProxy::Instance().BKEngCreateEngine( __uuidof(Skylark::IBKEngUploader), ( void** )&m_spiUploader ); if ( FAILED( hr ) ) { CRunTimeLog::WriteLog(WINMOD_LLVL_ERROR, L"[CUnkownReport] Upload interface create failed" ); goto Exit0; } hr = m_spiUploader->Initialize(); if ( FAILED( hr ) ) { CRunTimeLog::WriteLog(WINMOD_LLVL_ERROR, L"[CUnkownReport] Upload interface initialize failed" ); goto Exit0; } CBkBackupProxy::Instance().BKBackupCreateObject( __uuidof( Skylark::IBKFileBackupFinder ), ( void** )&m_spiBakFinder ); //if (WAIT_TIMEOUT != ::WaitForSingleObject(m_hNotifyStop, UNKNOWN_REPORT_FIRST_WAIT)) // goto Exit0; hEvent[ 0 ] = m_hNotifyStop; hEvent[ 1 ] = m_hNotifyReport; if ( WAIT_OBJECT_0 == ::WaitForMultipleObjects( 2, hEvent, FALSE, UNKNOWN_REPORT_FIRST_WAIT ) ) { goto Exit0; } //BOOL bAutoReport = FALSE; //CSvcSetting::Instance().GetAutoReport( bAutoReport ); if (!m_spiUploader) goto Exit0; CRunTimeLog::WriteLog(WINMOD_LLVL_INFO, L"report thread start ok" ); while( 1 ) { CReportFile rfile; CAtlList<CReportFile> *pReportList = NULL; if (WAIT_TIMEOUT != ::WaitForSingleObject(m_hNotifyStop, UNKNOWN_REPORT_NEXT_WAIT)) goto Exit0; if ( !GetReportFile( rfile, &pReportList ) ) { continue; } hr = S_OK; if ( ( rfile.m_nTrack & FILE_TRACK_QUARANTINE ) ) { CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] report quarantine %s", rfile.m_strFilePath ); if ( m_spiBackup == ( Skylark::IBKFileBackup* )NULL ) { hr = CBkBackupProxy::Instance().BKBackupCreateObject( __uuidof(Skylark::IBKFileBackup), ( void** )&m_spiBackup); } if ( SUCCEEDED( hr ) ) { Skylark::BKBAK_BACKUP_ID backupID; Skylark::BKENG_INIT( &backupID ); backupID.uBackupID = _wtoi64(rfile.m_strFilePath); Skylark::BKENG_UPLOAD_PARAM uploadParam; Skylark::BKENG_INIT( &uploadParam ); hr = m_spiBackup->UploadBackupFile( &backupID, m_spiUploader, &uploadParam, static_cast<Skylark::IBKProgress*>(this)); if ( SUCCEEDED( hr ) ) { CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] succeeded to report quarantine %s", rfile.m_strFilePath ); // 备份文件不需要重扫 // 上传成功,从数据库删除 //m_reportFileDB.RemoveFileInfo(rfile); rfile.m_nReportState = enumFileReported; m_reportFileDB.AddFileInfo( rfile ); } else { CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] failed to report quarantine %s : 0x%x", rfile.m_strFilePath, hr ); // 上传不成功 if ( AtlHresultFromWin32(ERROR_FILE_NOT_FOUND) == hr ) {// 隔离区中已不存在 m_reportFileDB.RemoveFileInfo( rfile ); } else { // 因为已经入库,所以下次重试 if ( rfile.m_nRetry < REPORT_MAX_RETRY_TIMES ) { rfile.m_nRetry++; pReportList->AddTail( rfile ); } else { rfile.m_nReportState = enumFileRetried; m_reportFileDB.AddFileInfo( rfile ); } } } } else { CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] failed to create IBKFileBackup : 0x%x", hr ); // 创建隔离组件不成功 // 因为已经入库,所以下次重试 } } else { CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] report file %s", rfile.m_strFilePath ); BOOL bIsReportFile = (rfile.m_nTrack & FILE_TRACK_REPORT_NONPE); Skylark::BKENG_UPLOAD_PARAM uploadParam; Skylark::BKENG_INIT( &uploadParam ); uploadParam.bUploadNonPEFile = bIsReportFile; hr = m_spiUploader->Upload( rfile.m_strFilePath, static_cast<Skylark::IBKProgress*>(this), &uploadParam); if ( SUCCEEDED( hr ) ) { CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] succeeded to report file %s", rfile.m_strFilePath ); WIN32_FILE_ATTRIBUTE_DATA fdata; // 上传成功,更新数据库,用于重扫 if ( GetFileAttributesEx( rfile.m_strFilePath, GetFileExInfoStandard, &fdata ) ) { rfile.SetCreateTime( fdata.ftLastWriteTime ); GetSystemTimeAsFileTime( &rfile.m_ReportTime ); rfile.m_nReportState = enumFileReported; m_reportFileDB.AddFileInfo( rfile ); } } else { CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] failed to report file %s : 0x%x", rfile.m_strFilePath, hr ); // 上传不成功 if ( WinMod::CWinPathApi::IsFileExisting( rfile.m_strFilePath ) ) { // 因为已经入库,所以下次重试 if ( rfile.m_nRetry < REPORT_MAX_RETRY_TIMES ) { rfile.m_nRetry++; pReportList->AddTail( rfile ); } else { rfile.m_nReportState = enumFileRetried; m_reportFileDB.AddFileInfo( rfile ); } } else { m_reportFileDB.RemoveFileInfo( rfile ); } } // 有隐患 if (bIsReportFile) ::DeleteFile(rfile.m_strFilePath); } } Exit0: if ( m_spiUploader ) { m_spiUploader->Uninitialize(); m_spiUploader.Release(); } CRunTimeLog::WriteLog(WINMOD_LLVL_INFO, L"[CUnkownReport] report thread exit" ); return 0; }
unsigned __int64 ConvertFileSizeString(const wchar_t *FileSizeStr) { if (!CheckFileSizeStringFormat(FileSizeStr)) return 0; unsigned __int64 n = _wtoi64(FileSizeStr); wchar_t c = Upper(FileSizeStr[StrLength(FileSizeStr)-1]); // http://en.wikipedia.org/wiki/SI_prefix switch (c) { case L'K': // kilo 10x3 n <<= 10; break; case L'M': // mega 10x6 n <<= 20; break; case L'G': // giga 10x9 n <<= 30; break; case L'T': // tera 10x12 n <<= 40; break; case L'P': // peta 10x15 n <<= 50; break; case L'E': // exa 10x18 n <<= 60; break; // Z - zetta 10x21 // Y - yotta 10x24 } return n; }
/*----------------------------------------------------------------------------- SetDefaultThreshold(IDiskQuotaControl* lpDiskQuotaControl) Set the default warning threshold of the volume. Parameters lpDiskQuotaControl - Pointer to an object that implements the IDiskQuotaControl interface Return Value TRUE - Success FALSE - Failure -----------------------------------------------------------------------------*/ BOOL SetDefaultThreshold(IDiskQuotaControl* lpDiskQuotaControl) { HRESULT hr; LONGLONG llLimit = 0; WCHAR szLimit[MAX_PATH] = {0}; DWORD dwCharsRead; HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE); wprintf(L"\n\nEnter the new default threshold in Bytes "); wprintf(L"(-1 == No Limit): "); // Get the limit from the command prompt ReadConsole(hStdIn, szLimit, MAX_PATH, &dwCharsRead, NULL); LfcrToNull(szLimit); llLimit = _wtoi64(szLimit); if (llLimit < -1) { wprintf(L"\nInvalid limit!"); return FALSE; } // Set the default warning threshold hr = lpDiskQuotaControl->SetDefaultQuotaThreshold(llLimit); if (FAILED(hr)) { PrintError(hr); return FALSE; } return TRUE; }
void CSDKWithoutLoginStartJoinMeetingUIGroup::DoWithoutLoginStartJoinMeetingBtnClick() { if(NULL == m_editMeetingNumber || NULL == m_editMeetingPassword || NULL == m_editScreenName ) return; ZOOM_SDK_NAMESPACE::tagJoinParam joinParam; joinParam.userType = ZOOM_SDK_NAMESPACE::SDK_UT_WITHOUT_LOGIN; ZOOM_SDK_NAMESPACE::JoinParam4WithoutLogin& withoutloginParam = joinParam.param.withoutloginuserJoin; std::wstring MeetingNumber = m_editMeetingNumber->GetText().GetData(); std::wstring MeetingPassword = m_editMeetingPassword->GetText().GetData(); std::wstring ScreenName = m_editScreenName->GetText().GetData(); withoutloginParam.meetingNumber = _wtoi64(MeetingNumber.c_str()); withoutloginParam.vanityID = NULL; withoutloginParam.userName = ScreenName.c_str(); withoutloginParam.psw = MeetingPassword.c_str(); withoutloginParam.hDirectShareAppWnd = NULL; withoutloginParam.toke4enfrocelogin = NULL; withoutloginParam.participantId = NULL; withoutloginParam.webinarToken = NULL; withoutloginParam.isDirectShareDesktop = false; withoutloginParam.isVideoOff = false; withoutloginParam.isAudioOff = false; if(MeetingNumber.size() > 0) { if(m_parentFrame) { m_parentFrame->SetCurrentPage(m_WithoutLoginStartJoinMeetingPage); m_parentFrame->SwitchToWaitingPage(_T("waiting to join meeting..."),true); } if (SDKInterfaceWrap::GetInst().IsSelectCustomizedUIMode()) { CSDKDemoAppEvent* pAppEvent = m_parentFrame->GetAppEvent(); if(pAppEvent) pAppEvent->InitCustomizedUI(); } bool ret = m_withoutLoginJoinMeetingWorkFlow.JoinMeeting(joinParam); if(ret) { m_bInMeeting = true; } return; } if (m_parentFrame) { if(MeetingNumber.size() <=0) { m_parentFrame->ShowErrorMessage(_T("Meeting number could not be NULL!")); m_editMeetingNumber->SetFocus(); } else { m_parentFrame->ShowErrorMessage(_T("Join meeting failed!")); } m_parentFrame->SetCurrentPage(m_WithoutLoginStartJoinMeetingPage); m_parentFrame->SwitchToWaitingPage(_T("waiting to join meeting...."), false); m_bInMeeting = false; } }
BOOL CUnkownReport::GetBackupFileAttributes( CString& strId, Skylark::BKBAK_BACKUP_INFO& info, BSTR* bstrOrgPath ) { Skylark::BKBAK_BACKUP_ID backid; BSTR bstrPath; Skylark::BKENG_INIT( &backid ); Skylark::BKENG_INIT( &info ); backid.uBackupID = _wtoi64( strId ); if ( m_spiBakFinder ) { if ( SUCCEEDED( m_spiBakFinder->GetBackupInfo( &backid, &info, &bstrPath ) ) ) { ::SysFreeString( bstrPath ); bstrPath = NULL; return TRUE; } } return FALSE; }
/*----------------------------------------------------------------------------- SetUserThreshold(IDiskQuotaControl* lpDiskQuotaControl) Set the warning threshold limit for a specific user Parameters lpDiskQuotaControl - Pointer to an object that implements the IDiskQuotaControl interface Return Value TRUE - Success FALSE - Failure -----------------------------------------------------------------------------*/ BOOL SetUserThreshold(IDiskQuotaControl* lpDiskQuotaControl) { HRESULT hr; IDiskQuotaUser* lpDiskQuotaUser; WCHAR szUser[MAX_PATH] = {0}; DWORD dwCharsRead; LONGLONG llLimit = 0; HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE); wprintf(L"\n\nEnter the logon name of the user "); wprintf(L"(ie. DOMAIN\\USERNAME): "); // Get the user for which to set a hard limit ReadConsole(hStdIn, szUser, MAX_PATH, &dwCharsRead, NULL); szUser[MAX_PATH-1] = L'\0'; // make sure szUSer is NULL terminated // Strip the line feed and carriage return LfcrToNull(szUser); // Check if the name is valid hr = lpDiskQuotaControl->FindUserName((LPCWSTR)szUser, &lpDiskQuotaUser); if (SUCCEEDED(hr)) { WCHAR szLimit[MAX_PATH] = {0}; wprintf(L"\nEnter the new hard limit in bytes (-1 == No Limit): "); // Read the threshold from the console ReadConsole(hStdIn, szLimit, MAX_PATH, &dwCharsRead, NULL); LfcrToNull(szLimit); llLimit = _wtoi64(szLimit); if (llLimit >= -1) { // Set the warning threshold for the user hr = lpDiskQuotaUser->SetQuotaThreshold(llLimit, TRUE); if (FAILED(hr)) { wprintf(L"\nCould not set the quota limit for %s", szUser); wprintf(L"to %i64 bytes\n", llLimit); } } else { wprintf(L"\nInvalid limit!"); } lpDiskQuotaUser->Release(); } else { PrintError(hr); } return SUCCEEDED(hr); }
DWORD wtodw(const wchar_t* num) { if(NULL == num) return 0; //in VS2003 atoi/wtoi would convert an unsigned value even though it would overflow a signed value. No more, and it causes trouble! __int64 res = _wtoi64(num); _ASSERT(res <= ULONG_MAX); return (DWORD)res; }
inline int64_t to_int64(const wchar_t* in, int base = 10) { #ifdef _MSC_VER UNUSED(base); return _wtoi64(in); #else wchar_t* end_ptr; return ::wcstoll(in, &end_ptr, base); #endif }
__int64 TVar::toInteger() { if (vType == vtString) inum = str ? _wtoi64(str) : 0; else if (vType == vtDouble) inum=(__int64)dnum; vType = vtInteger; return inum; }
__int64 TVar::getInteger() const { __int64 ret = inum; if (isString()) ret = str ? _wtoi64(str) : 0; else if (isDouble()) ret=(__int64)dnum; return ret; };
bool TryStrToInt(const std::wstring & StrValue, __int64 & Value) { bool Result = !StrValue.empty(); if (Result) { errno = 0; Value = _wtoi64(StrValue.c_str()); Result = (errno != EINVAL) && (errno != ERANGE); } return Result; }
/* Sets Innodb buffer pool size (1/8 of RAM by default), if not already specified via command line. Calculates innodb log file size as min(50, innodb buffer pool size/8) */ extern "C" UINT __stdcall PresetDatabaseProperties(MSIHANDLE hInstall) { unsigned long long InnodbBufferPoolSize= 256; unsigned long long InnodbLogFileSize= 50; wchar_t buff[MAX_PATH]; UINT er = ERROR_SUCCESS; HRESULT hr= S_OK; MEMORYSTATUSEX memstatus; hr = WcaInitialize(hInstall, __FUNCTION__); ExitOnFailure(hr, "Failed to initialize"); WcaLog(LOGMSG_STANDARD, "Initialized."); /* Check if bufferpoolsize parameter was given on the command line*/ DWORD BufferPoolsizeParamLen = MAX_PATH; MsiGetPropertyW(hInstall, L"BUFFERPOOLSIZE", buff, &BufferPoolsizeParamLen); if (BufferPoolsizeParamLen && buff[0]) { WcaLog(LOGMSG_STANDARD, "BUFFERPOOLSIZE=%s, len=%u",buff, BufferPoolsizeParamLen); InnodbBufferPoolSize= _wtoi64(buff); } else { memstatus.dwLength = sizeof(memstatus); if (!GlobalMemoryStatusEx(&memstatus)) { WcaLog(LOGMSG_STANDARD, "Error %u from GlobalMemoryStatusEx", GetLastError()); er= ERROR_INSTALL_FAILURE; goto LExit; } unsigned long long totalPhys= memstatus.ullTotalPhys; /* Give innodb 12.5% of available physical memory. */ InnodbBufferPoolSize= totalPhys/ONE_MB/8; #ifdef _M_IX86 /* For 32 bit processes, take virtual address space limitation into account. Do not try to use more than 3/4 of virtual address space, even if there is plenty of physical memory. */ InnodbBufferPoolSize= min(GetMaxBufferSize(totalPhys)/ONE_MB*3/4, InnodbBufferPoolSize); #endif swprintf_s(buff, L"%llu",InnodbBufferPoolSize); MsiSetPropertyW(hInstall, L"BUFFERPOOLSIZE", buff); } InnodbLogFileSize = min(50, InnodbBufferPoolSize); swprintf_s(buff, L"%llu",InnodbLogFileSize); MsiSetPropertyW(hInstall, L"LOGFILESIZE", buff); LExit: return WcaFinalize(er); }
CSubtitle* CSubtitleSamiReader::ReadSubTitle(CSubtitleText *reader) { wchar_t Buffer[MAX_SUBTITLE_LINE_SIZE]; CSubtitle *subtitle = new CSubtitle(); for(;;) { wchar_t *line = reader->Read(L"<SYNC Start=", L"</SYNC>"); if (line == NULL) break; int64_t start = _wtoi64(line); while (*line != L'>') line ++; int32_t i = 0; int32_t skip = 0; for(wchar_t *p = line; *p; p++) { if(*p == '>') { skip = 0; continue; } if(*p == '<') { skip = 1; continue; } if(skip) { continue; } if (i < MAX_SUBTITLE_LINE_SIZE - 1) { Buffer[i] = *p; i++; } } if (i) { Buffer[i] = 0; CSubtitleItem *item = subtitle->NewItem(); item->AddLine(Buffer); item->m_StartTime = start * AV_TIME_BASE_LL; } } if (subtitle->m_Count) return subtitle; delete subtitle; return NULL; }
// When reading Oculus registry keys, we recognize that the user may have inconsistently // used a DWORD 1 vs. a string "1", and so we support either when checking booleans. bool GetRegistryBoolW(const wchar_t* pSubKey, const wchar_t* stringName, bool defaultValue, bool wow64value, bool currentUser) { wchar_t out[MAX_PATH]; if (GetRegistryStringW(pSubKey, stringName, out, wow64value, currentUser)) { return (_wtoi64(out) != 0); } DWORD dw; if (GetRegistryDwordW(pSubKey, stringName, dw, wow64value, currentUser)) { return (dw != 0); } return defaultValue; }
HRESULT XmlProfileParser::_GetUINT64(IXMLDOMNode *pXmlNode, const char *pszQuery, UINT64 *pullValue) const { CComPtr<IXMLDOMNode> spNode = nullptr; CComVariant query(pszQuery); HRESULT hr = pXmlNode->selectSingleNode(query.bstrVal, &spNode); if (SUCCEEDED(hr) && (hr != S_FALSE)) { BSTR bstrText; hr = spNode->get_text(&bstrText); if (SUCCEEDED(hr)) { *pullValue = _wtoi64((wchar_t *)bstrText); // TODO: make sure it works on large unsigned ints } SysFreeString(bstrText); } return hr; }
bool LoadSessionData( IN MRABase& _db, IN MAKFC_CString databaseKey, OUT MAKFC_CString& sDevId, OUT MAKFC_CString& sA, OUT MAKFC_CString& sSessionKey, OUT MAKFC_CString& ts) { gigabase::dbArray<gigabase::byte> data; if ( !_db.ReadRawData( tstring(databaseKey.NetStrW()), L"", ICQ_PARTNERS_LOGIN_DATA, data ) ) { return false; } MAKFC_CString sCookies = (LPCWSTR) data.get(); if ( !sCookies.Len() ) return false; int iStart1 = 0; MAKFC_CString sToken1; while ( ( sToken1 = sCookies.Tokenize( L";", iStart1 ) ).GetLength() ) { int iStart2 = 0; MAKFC_CString sLeft = sToken1.Tokenize( L"=", iStart2 ); MAKFC_CString sRight = sToken1.Mid( iStart2 ); if ( sLeft == L"k" ) sDevId = sRight; else if ( sLeft == L"a" ) sA = sRight; else if ( sLeft == L"session_key" ) sSessionKey = sRight; else if ( sLeft == L"time_offset" ) { __int64 offset = _wtoi64( sRight ); time_t tt = 0; FileTimeToUnixTime( &tt, CFileTime( CFileTime::GetCurrentTime().GetTime() - offset ) ); ts.Format( L"%d", (DWORD) tt ); } } return true; }
bool CIMDateTimetoFiletime(__in LPCWSTR cimdatetime, __out LPFILETIME filetime, __in const bool blocaltime = true) { bool bSuccess = false; // Get a SWbemDateTime object. ISWbemDateTime *pSWbemDateTime = NULL; HRESULT hr = CoCreateInstance(CLSID_SWbemDateTime, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pSWbemDateTime)); if (SUCCEEDED(hr)) { BSTR timebstr = SysAllocString(cimdatetime); if (timebstr) { // Set time value. hr = pSWbemDateTime->put_Value(timebstr); if (SUCCEEDED(hr)) { BSTR bstrFileTime; // Get a FILETIME. hr = pSWbemDateTime->GetFileTime(blocaltime?VARIANT_TRUE:VARIANT_FALSE, &bstrFileTime); if (SUCCEEDED(hr)) { ULARGE_INTEGER tempFT; // 64-bit value representing the number of 100-nanosecond intervals // since January 1, 1601 (UTC). tempFT.QuadPart = _wtoi64(bstrFileTime); // FILETIME is a structure of two 32-bit integers. filetime->dwLowDateTime = tempFT.LowPart; filetime->dwHighDateTime = tempFT.HighPart; bSuccess = true; SysFreeString(bstrFileTime); } } SysFreeString(timebstr); } pSWbemDateTime->Release(); } return bSuccess; }
// Ищет цифры в имени файла с конца. __int64 GetDigitInFileName(const TPath &path, TString & nameWithoutDigit, size_t & leadingZeros) { TString name = path.GetName(false); size_t length = name.length(); //Находим первый не числовой символ с конца bool canRename; size_t digitPos = length; for (ptrdiff_t i = length - 1; i >= 0; digitPos = i, i-- ) { if (!iswdigit(name[i])) //если не цифра выходим break; } if (digitPos <= length - 1) //если цифра найдена canRename = true; else canRename = false; __int64 result = -1; int numOfZero = 0; if (canRename) { TString forParsing = name.substr(digitPos, length - digitPos); result = _wtoi64(forParsing.c_str()); if (result == _I64_MAX) //слишком длинный { digitPos = 0; result = -1; } leadingZeros = forParsing.length() - LengthOfLong(result); } if (digitPos > 0 && digitPos < length) nameWithoutDigit = name.substr(0, digitPos); else nameWithoutDigit = TString(); return result; }
//----------------------------------------------------------------------------- U64 MGStrOp::toU64(CChar16* src) { I64 temp = _wtoi64(src); return temp; }
BOOL CALLBACK ExpandVolSizeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { static EXPAND_VOL_THREAD_PARAMS *pVolExpandParam; WORD lw = LOWORD (wParam); switch (msg) { case WM_INITDIALOG: { wchar_t szTemp[4096]; pVolExpandParam = (EXPAND_VOL_THREAD_PARAMS*)lParam; EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_KB), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_MB), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_GB), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_TB), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE), !(pVolExpandParam->bIsLegacy && pVolExpandParam->bIsDevice)); SendDlgItemMessage (hwndDlg, IDC_INIT_NEWSPACE, BM_SETCHECK, pVolExpandParam->bInitFreeSpace ? BST_CHECKED : BST_UNCHECKED, 0); if (!pVolExpandParam->bIsDevice) SetCurrentVolSize(hwndDlg,pVolExpandParam->oldSize); SendMessage (GetDlgItem (hwndDlg, IDC_BOX_HELP), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE); GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->oldSize,pVolExpandParam->bIsDevice); SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szTemp); SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pVolExpandParam->szVolumeName); SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pVolExpandParam->FileSystem]); if (pVolExpandParam->bIsDevice) { GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->newSize,TRUE); } else { wchar_t szHostFreeStr[256]; SetWindowText (GetDlgItem (hwndDlg, IDT_NEW_SIZE), L""); GetSpaceString(szHostFreeStr,sizeof(szHostFreeStr),pVolExpandParam->hostSizeFree,FALSE); StringCbPrintfW (szTemp,sizeof(szTemp),L"%s available on host drive", szHostFreeStr); } SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szTemp); // set help text if (pVolExpandParam->bIsDevice) { StringCbPrintfW (szTemp,sizeof(szTemp),L"This is a device-based VeraCrypt volume.\n\nThe new volume size will be choosen automatically as the size of the host device."); if (pVolExpandParam->bIsLegacy) StringCbCatW(szTemp,sizeof(szTemp),L" Note: filling the new space with random data is not supported for legacy volumes."); } else { StringCbPrintfW (szTemp, sizeof(szTemp),L"Please specify the new size of the VeraCrypt volume (must be at least %I64u KB larger than the current size).",TC_MINVAL_FS_EXPAND/1024); } SetWindowText (GetDlgItem (hwndDlg, IDC_BOX_HELP), szTemp); } return 0; case WM_COMMAND: if (lw == IDCANCEL) { EndDialog (hwndDlg, lw); return 1; } if (lw == IDOK) { wchar_t szTemp[4096]; pVolExpandParam->bInitFreeSpace = IsButtonChecked (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE)); if (!pVolExpandParam->bIsDevice) // for devices new size is set by calling function { GetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTemp, ARRAYSIZE (szTemp)); pVolExpandParam->newSize = _wtoi64(szTemp) * GetSizeBoxMultiplier(hwndDlg); } EndDialog (hwndDlg, lw); return 1; } return 0; } return 0; }
LONGLONG CINIFile::GetInt64( CString strSection,CString strKey ) { CString strValue =GetString(strSection,strKey); return _wtoi64(strValue.GetBuffer()); }
bool inet_get_resource_range(const wstring& url,__int64 start,__int64 length,inet_reader& reader) { wstring url2=inet_canonicalize_url(url); bool succ=false; HINTERNET handle_internet=NULL; HINTERNET handle_url=NULL; HINTERNET handle_connect=NULL; HINTERNET handle_file=NULL; inet_url_parts parts=inet_crack_url(url2); do { if(parts.scheme==INTERNET_SCHEME_HTTP) { handle_internet=InternetOpenW(INET_USER_AGENT.c_str(),INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if(!handle_internet) break; wstring header; if(length<0) header=FORMATW(L"Range: bytes=%I64d-",start); else header=FORMATW(L"Range: bytes=%I64d-%I64d",start,start+length-1); handle_url=InternetOpenUrlW(handle_internet,url2.c_str(),header.c_str(),0,0,NULL); if(!handle_url) break; wchar_t buffer[4096]; DWORD buffer_len=sizeof(buffer); DWORD index=0; __int64 len=-1; if(HttpQueryInfoW(handle_url,HTTP_QUERY_CONTENT_LENGTH,buffer,&buffer_len,&index)) len=_wtoi64(buffer); reader.run(handle_url); } else if(parts.scheme==INTERNET_SCHEME_FTP) { handle_internet=InternetOpenW(INET_USER_AGENT.c_str(),INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if(!handle_internet) break; handle_connect=InternetConnectW(handle_internet,parts.hostname.c_str(),parts.port,parts.username.c_str(),parts.password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,NULL); if(!handle_connect) break; wstring command=FORMATW(L"REST %I64d",start); FtpCommandW(handle_connect,FALSE,FTP_TRANSFER_TYPE_BINARY,command.c_str(),NULL,NULL); handle_file=FtpOpenFileW(handle_connect,parts.url_path.c_str(),GENERIC_READ,FTP_TRANSFER_TYPE_BINARY,NULL); if(!handle_file) break; reader.run(handle_file); } else break; }while(false); if(handle_file) InternetCloseHandle(handle_file); if(handle_connect) InternetCloseHandle(handle_connect); if(handle_url) InternetCloseHandle(handle_url); if(handle_internet) InternetCloseHandle(handle_internet); return true; }
__int64 inet_get_resource_size(const wstring& url) { wstring url2=inet_canonicalize_url(url); __int64 res_size=-1; bool succ=false; HINTERNET handle_internet=NULL; HINTERNET handle_url=NULL; HINTERNET handle_connect=NULL; HINTERNET handle_file=NULL; inet_url_parts parts=inet_crack_url(url2); do { if(parts.scheme==INTERNET_SCHEME_HTTP) { handle_internet=InternetOpenW(INET_USER_AGENT.c_str(),INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if(!handle_internet) break; handle_url=InternetOpenUrlW(handle_internet,url2.c_str(),NULL,0,0,NULL); if(!handle_url) break; wchar_t buffer[4096]; DWORD buffer_len=sizeof(buffer); DWORD index=0; if(!HttpQueryInfoW(handle_url,HTTP_QUERY_CONTENT_LENGTH,buffer,&buffer_len,&index)) break; res_size=_wtoi64(buffer); succ=true; } else if(parts.scheme==INTERNET_SCHEME_FTP) { handle_internet=InternetOpenW(INET_USER_AGENT.c_str(),INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if(!handle_internet) break; handle_connect=InternetConnectW(handle_internet,parts.hostname.c_str(),parts.port,parts.username.c_str(),parts.password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,NULL); if(!handle_connect) break; handle_file=FtpOpenFile(handle_connect,parts.url_path.c_str(),GENERIC_READ,FTP_TRANSFER_TYPE_BINARY,NULL); if(!handle_file) break; DWORD low,high; low=FtpGetFileSize(handle_file,&high); if(low==(~0)) break; res_size=low|(((__int64)high)<<32); succ=true; } else break; }while(false); if(handle_file) InternetCloseHandle(handle_file); if(handle_connect) InternetCloseHandle(handle_connect); if(handle_url) InternetCloseHandle(handle_url); if(handle_internet) InternetCloseHandle(handle_internet); return res_size; }
long long wtoll(const wchar_t * _w) { return _wtoi64 (_w); }
int CALLBACK FilterSortCallback( IN LPARAM First, IN LPARAM Second, IN LPARAM Param ) { WCHAR FirstData[MAX_PATH + 1]; WCHAR SecondData[MAX_PATH + 1]; HWND hWnd; LIST_DATA_TYPE Type; int Result; LISTVIEW_OBJECT *Object; LISTVIEW_COLUMN *Column; Object = (LISTVIEW_OBJECT *)Param; FirstData[0] = 0; SecondData[0] = 0; hWnd = Object->hWnd; Column = Object->Column; ListView_GetItemText(hWnd, First, Object->LastClickedColumn, FirstData, MAX_PATH); ListView_GetItemText(hWnd, Second, Object->LastClickedColumn, SecondData, MAX_PATH); Type = Column[Object->LastClickedColumn].DataType; switch (Type) { case DataTypeInt: Result = _wtoi(FirstData) - _wtoi(SecondData); break; case DataTypeUInt: Result = (int)((UINT)_wtoi(FirstData) - (UINT)_wtoi(SecondData)); break; case DataTypeInt64: Result = (int)(_wtoi64(FirstData) - _wtoi64(SecondData)); break; case DataTypeUInt64: Result = (int)((ULONG64)_wtoi64(FirstData) - (ULONG64)_wtoi64(SecondData)); break; case DataTypeFloat: if (_wtof(FirstData) - _wtof(SecondData) >= 0) { Result = -1; } else { Result = 1; } break; case DataTypeTime: case DataTypeText: case DataTypeBool: Result = _wcsicmp(FirstData, SecondData); break; default: ASSERT(0); } return Object->SortOrder ? Result : -Result; }
STDMETHODIMP CFDMFlashVideoDownloads::ShowAddDownloadsDialog(BSTR bstrSrcWebPageUrl, SAFEARRAY *psaDownloads) { USES_CONVERSION; CComObject <CFdmUiWindow> *pUiWindow = NULL; CComObject <CFdmUiWindow>::CreateInstance (&pUiWindow); vmsAUTOLOCKSECTION (m_csLastUiWindow); m_spLastUiWindow = pUiWindow; vmsAUTOLOCKSECTION_UNLOCK (m_csLastUiWindow); if (psaDownloads == NULL) return E_INVALIDARG; UINT cDim = SafeArrayGetDim (psaDownloads); if (cDim != 1) return E_INVALIDARG; LONG lLBound = 0, lUBound = 0; SafeArrayGetLBound (psaDownloads, 1, &lLBound); SafeArrayGetUBound (psaDownloads, 1, &lUBound); std::vector <vmsNewDownloadInfo> *pvDlds = new std::vector <vmsNewDownloadInfo>; for (long i = lLBound; i <= lUBound; i++) { IDispatchPtr spDisp; SafeArrayGetElement (psaDownloads, &i, &spDisp); IFdmFlvDownloadPtr spFlvDld (spDisp); if (spFlvDld == NULL) { delete pvDlds; return E_INVALIDARG; } IWGUrlReceiverPtr spUrl; spFlvDld->get_Url (&spUrl); if (spUrl == NULL) { delete pvDlds; return E_INVALIDARG; } CComBSTR bstr; spUrl->get_Url (&bstr); CString strUrl = W2CT (bstr); bool bSkip = false; for (size_t j = 0; j < pvDlds->size (); j++) { if (pvDlds->at (j).strUrl == strUrl) { bSkip = true; break; } } if (bSkip) continue; vmsNewDownloadInfo dlInfo; dlInfo.strUrl = W2CA (bstr); spUrl->get_Referer (&bstr); dlInfo.strReferer = W2CA (bstr); spUrl->get_Comment (&bstr); dlInfo.strComment = bstr; dlInfo.dwWhatIsValid = NDIV_AP; dlInfo.ap.dwMask = DWCDAP_FLAGS; dlInfo.ap.dwFlags = DWDCDAP_F_FLASHVIDEODOWNLOAD; spUrl->get_Cookies (&bstr); if (bstr.Length ()) { dlInfo.ap.dwMask |= DWCDAP_COOKIES; dlInfo.ap.strCookies = W2CA (bstr); } spUrl->get_PostData (&bstr); if (bstr.Length ()) { dlInfo.ap.dwMask |= DWCDAP_POSTDATA; dlInfo.ap.strPostData = W2CA (bstr); } spUrl->get_FileName (&bstr); if (bstr.Length ()) { dlInfo.ap.dwMask |= DWCDAP_FILENAME; dlInfo.ap.strFileName = W2CA (bstr); } spUrl->get_FileSize (&bstr); if (bstr.Length ()) { dlInfo.ap.dwMask |= DWCDAP_FILESIZE; dlInfo.ap.uFileSize = (UINT64)_wtoi64 (bstr); } pvDlds->push_back (dlInfo); } CFlashVideoDownloadsWnd::WmFvdwLparam *lp = new CFlashVideoDownloadsWnd::WmFvdwLparam; lp->strSrcWebPageUrl = W2CA(bstrSrcWebPageUrl); lp->pvDlds = pvDlds; lp->pUiWindow = pUiWindow; if (pUiWindow) pUiWindow->AddRef (); _pwndFVDownloads->PostMessage (WM_FVDW_CREATEDOWNLOADS, 0, (LPARAM)lp); return S_OK; }
__int64 TVar::i() const { return isInteger() ? inum : (isDouble() ? (__int64)dnum : (str ? _wtoi64(str) : 0)); }
bool SyncCommand::Execute() { bool bRet = false; CRegString rSyncPath(L"Software\\TortoiseSVN\\SyncPath"); CTSVNPath syncPath = CTSVNPath(CString(rSyncPath)); CTSVNPath syncFolder = syncPath; CRegDWORD regCount(L"Software\\TortoiseSVN\\SyncCounter"); CRegDWORD regSyncAuth(L"Software\\TortoiseSVN\\SyncAuth"); bool bSyncAuth = DWORD(regSyncAuth) != 0; if (!cmdLinePath.IsEmpty()) syncPath = cmdLinePath; if (syncPath.IsEmpty() && !parser.HasKey(L"askforpath")) { return false; } syncPath.AppendPathString(L"tsvnsync.tsex"); BOOL bWithLocals = FALSE; if (parser.HasKey(L"askforpath")) { // ask for the path first, then for the password // this is used for a manual import/export CString path; bool bGotPath = FileOpenSave(path, bWithLocals, !!parser.HasKey(L"load"), GetExplorerHWND()); if (bGotPath) { syncPath = CTSVNPath(path); if (!parser.HasKey(L"load") && syncPath.GetFileExtension().IsEmpty()) syncPath.AppendRawString(L".tsex"); } else return false; } CSimpleIni iniFile; iniFile.SetMultiLine(true); SVNAuthData authData; CAutoRegKey hMainKey; RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\TortoiseSVN", 0, KEY_READ, hMainKey.GetPointer()); FILETIME filetime = { 0 }; RegQueryInfoKey(hMainKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &filetime); bool bCloudIsNewer = false; if (!parser.HasKey(L"save")) { // open the file in read mode CAutoFile hFile = CreateFile(syncPath.GetWinPathString(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile.IsValid()) { // load the file LARGE_INTEGER fsize = { 0 }; if (GetFileSizeEx(hFile, &fsize)) { auto filebuf = std::make_unique<char[]>(DWORD(fsize.QuadPart)); DWORD bytesread = 0; if (ReadFile(hFile, filebuf.get(), DWORD(fsize.QuadPart), &bytesread, NULL)) { // decrypt the file contents std::string encrypted; if (bytesread > 0) encrypted = std::string(filebuf.get(), bytesread); CRegString regPW(L"Software\\TortoiseSVN\\SyncPW"); CString password; if (parser.HasKey(L"askforpath") && parser.HasKey(L"load")) { INT_PTR dlgret = 0; bool bPasswordMatches = true; do { bPasswordMatches = true; CPasswordDlg passDlg(CWnd::FromHandle(GetExplorerHWND())); passDlg.m_bForSave = !!parser.HasKey(L"save"); dlgret = passDlg.DoModal(); password = passDlg.m_sPW1; if ((dlgret == IDOK) && (parser.HasKey(L"load"))) { std::string passworda = CUnicodeUtils::StdGetUTF8((LPCWSTR)password); std::string decrypted = CStringUtils::Decrypt(encrypted, passworda); if ((decrypted.size() < 3) || (decrypted.substr(0, 3) != "***")) { bPasswordMatches = false; } } } while ((dlgret == IDOK) && !bPasswordMatches); if (dlgret != IDOK) return false; } else { auto passwordbuf = CStringUtils::Decrypt(CString(regPW)); if (passwordbuf.get()) { password = passwordbuf.get(); } else { // password does not match or it couldn't be read from // the registry! // TaskDialog(GetExplorerHWND(), AfxGetResourceHandle(), MAKEINTRESOURCE(IDS_APPNAME), MAKEINTRESOURCE(IDS_ERR_ERROROCCURED), MAKEINTRESOURCE(IDS_SYNC_WRONGPASSWORD), TDCBF_OK_BUTTON, TD_ERROR_ICON, NULL); CString sCmd = L" /command:settings /page:21"; CAppUtils::RunTortoiseProc(sCmd); return false; } } std::string passworda = CUnicodeUtils::StdGetUTF8((LPCWSTR)password); std::string decrypted = CStringUtils::Decrypt(encrypted, passworda); if (decrypted.size() >= 3) { if (decrypted.substr(0, 3) == "***") { decrypted = decrypted.substr(3); // pass the decrypted data to the ini file iniFile.LoadFile(decrypted.c_str(), decrypted.size()); int inicount = _wtoi(iniFile.GetValue(L"sync", L"synccounter", L"")); if (inicount != 0) { if (int(DWORD(regCount)) < inicount) { bCloudIsNewer = true; regCount = inicount; } } // load the auth data, but do not overwrite already stored auth data! if (bSyncAuth) authData.ImportAuthData(syncFolder.GetWinPathString(), password); } else { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error decrypting, password may be wrong\n"); return false; } } } } } else { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error opening file %s, Error %u\n", syncPath.GetWinPath(), GetLastError()); auto lasterr = GetLastError(); if ((lasterr != ERROR_FILE_NOT_FOUND) && (lasterr != ERROR_PATH_NOT_FOUND)) return false; } } if (parser.HasKey(L"load")) bCloudIsNewer = true; if (parser.HasKey(L"save")) bCloudIsNewer = false; bool bHaveChanges = false; if (bWithLocals || parser.HasKey(L"local")) { // remove all blocks that are allowed for local exports for (const auto& allow : regBlockLocalArray) { regBlockArray.erase(std::remove(regBlockArray.begin(), regBlockArray.end(), allow), regBlockArray.end()); } } // go through all registry values and update either the registry // or the ini file, depending on which is newer for (const auto& regname : regUseArray) { bool bChanges = HandleRegistryKey(regname, iniFile, bCloudIsNewer); bHaveChanges = bHaveChanges || bChanges; } if (bWithLocals || parser.HasKey(L"local")) { for (const auto& regname : regUseLocalArray) { bool bChanges = HandleRegistryKey(regname, iniFile, bCloudIsNewer); bHaveChanges = bHaveChanges || bChanges; } } if (bCloudIsNewer) { CString regpath = L"Software\\"; CSimpleIni::TNamesDepend keys; iniFile.GetAllKeys(L"registry_dword", keys); for (const auto& k : keys) { CRegDWORD reg(regpath + k); reg = _wtol(iniFile.GetValue(L"registry_dword", k, L"")); } keys.clear(); iniFile.GetAllKeys(L"registry_qword", keys); for (const auto& k : keys) { CRegQWORD reg(regpath + k); reg = _wtoi64(iniFile.GetValue(L"registry_qword", k, L"")); } keys.clear(); iniFile.GetAllKeys(L"registry_string", keys); for (const auto& k : keys) { CRegString reg(regpath + k); reg = CString(iniFile.GetValue(L"registry_string", k, L"")); } } { // sync project monitor settings CString sDataFilePath = CPathUtils::GetAppDataDirectory(); sDataFilePath += L"\\MonitoringData.ini"; CSimpleIni monitorIni; monitorIni.SetMultiLine(true); if (bCloudIsNewer) { CSimpleIni origMonitorIni; origMonitorIni.SetMultiLine(true); origMonitorIni.LoadFile(sDataFilePath); CSimpleIni::TNamesDepend keys; iniFile.GetAllKeys(L"ini_monitor", keys); for (const auto& k : keys) { CString sKey = k; CString sSection = sKey.Left(sKey.Find('.')); sKey = sKey.Mid(sKey.Find('.') + 1); if (sKey.CompareNoCase(L"name") == 0) { // make sure the non-synced values are still used monitorIni.SetValue(sSection, L"lastchecked", origMonitorIni.GetValue(sSection, L"lastchecked", L"0")); monitorIni.SetValue(sSection, L"lastcheckedrobots", origMonitorIni.GetValue(sSection, L"lastcheckedrobots", L"0")); monitorIni.SetValue(sSection, L"lastHEAD", origMonitorIni.GetValue(sSection, L"lastHEAD", L"0")); monitorIni.SetValue(sSection, L"UnreadItems", origMonitorIni.GetValue(sSection, L"UnreadItems", L"0")); monitorIni.SetValue(sSection, L"unreadFirst", origMonitorIni.GetValue(sSection, L"unreadFirst", L"0")); monitorIni.SetValue(sSection, L"WCPathOrUrl", origMonitorIni.GetValue(sSection, L"WCPathOrUrl", L"")); } CString sValue = CString(iniFile.GetValue(L"ini_monitor", k, L"")); if ((sKey.Compare(L"username") == 0) || (sKey.Compare(L"password") == 0)) { sValue = CStringUtils::Encrypt(sValue); } monitorIni.SetValue(sSection, sKey, sValue); } FILE * pFile = NULL; errno_t err = 0; int retrycount = 5; CString sTempfile = CTempFiles::Instance().GetTempFilePathString(); do { err = _tfopen_s(&pFile, sTempfile, L"wb"); if ((err == 0) && pFile) { monitorIni.SaveFile(pFile); err = fclose(pFile); } if (err) { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error saving %s, retrycount %d\n", (LPCWSTR)sTempfile, retrycount); Sleep(500); } } while (err && retrycount--); if (err == 0) { if (!CopyFile(sTempfile, sDataFilePath, FALSE)) CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error copying %s to %s, Error %u\n", (LPCWSTR)sTempfile, (LPCWSTR)sDataFilePath, GetLastError()); else { // now send a message to a possible running monitor to force it // to reload the ini file. Otherwise it would overwrite the ini // file without using the synced data! HWND hWnd = FindWindow(NULL, CString(MAKEINTRESOURCE(IDS_MONITOR_DLGTITLE))); if (hWnd) { UINT TSVN_COMMITMONITOR_RELOADINI = RegisterWindowMessage(L"TSVNCommitMonitor_ReloadIni"); PostMessage(hWnd, TSVN_COMMITMONITOR_RELOADINI, 0, 0); } } } } else { CSimpleIni::TNamesDepend mitems; if (PathFileExists(sDataFilePath)) { int retrycount = 5; SI_Error err = SI_OK; do { err = monitorIni.LoadFile(sDataFilePath); if (err == SI_FILE) { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error loading %s, retrycount %d\n", (LPCWSTR)sDataFilePath, retrycount); Sleep(500); } } while ((err == SI_FILE) && retrycount--); if (err == SI_FILE) { return false; } monitorIni.GetAllSections(mitems); } for (const auto& mitem : mitems) { CString sSection = mitem; CString Name = monitorIni.GetValue(mitem, L"Name", L""); if (!Name.IsEmpty()) { CString newval = monitorIni.GetValue(mitem, L"WCPathOrUrl", L""); iniFile.SetValue(L"ini_monitor", sSection + L".Name", Name); CString oldval = iniFile.GetValue(L"ini_monitor", sSection + L".WCPathOrUrl", L""); bHaveChanges |= ((newval != oldval) && (!oldval.IsEmpty())); // only save monitored working copies if local settings are included, or // if the monitored path is an url. // Don't save paths to working copies for non-local stores if (bWithLocals || newval.IsEmpty() || !PathIsDirectory(newval)) iniFile.SetValue(L"ini_monitor", sSection + L".WCPathOrUrl", newval); newval = monitorIni.GetValue(mitem, L"interval", L"5"); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".interval", L"0"); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".interval", newval); newval = monitorIni.GetValue(mitem, L"minminutesinterval", L"0"); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".minminutesinterval", L"0"); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".minminutesinterval", newval); newval = CStringUtils::Decrypt(monitorIni.GetValue(mitem, L"username", L"")).get(); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".username", L""); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".username", newval); newval = CStringUtils::Decrypt(monitorIni.GetValue(mitem, L"password", L"")).get(); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".password", L""); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".password", newval); newval = monitorIni.GetValue(mitem, L"MsgRegex", L""); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".MsgRegex", L""); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".MsgRegex", newval); newval = monitorIni.GetValue(mitem, L"ignoreauthors", L""); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".ignoreauthors", L""); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".ignoreauthors", newval); newval = monitorIni.GetValue(mitem, L"parentTreePath", L""); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".parentTreePath", L""); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".parentTreePath", newval); newval = monitorIni.GetValue(mitem, L"uuid", L""); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".uuid", L""); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".uuid", newval); newval = monitorIni.GetValue(mitem, L"root", L""); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".root", L""); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".root", newval); ProjectProperties ProjProps; ProjProps.LoadFromIni(monitorIni, sSection); ProjProps.SaveToIni(iniFile, L"ini_monitor", sSection + L".pp_"); } else if (sSection.CompareNoCase(L"global") == 0) { CString newval = monitorIni.GetValue(mitem, L"PlaySound", L"1"); CString oldval = iniFile.GetValue(L"ini_monitor", sSection + L".PlaySound", L"1"); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".PlaySound", newval); newval = monitorIni.GetValue(mitem, L"ShowNotifications", L"1"); oldval = iniFile.GetValue(L"ini_monitor", sSection + L".ShowNotifications", L"1"); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_monitor", sSection + L".ShowNotifications", newval); } } } } { // sync TortoiseMerge regex filters CSimpleIni regexIni; regexIni.SetMultiLine(true); CString sDataFilePath = CPathUtils::GetAppDataDirectory(); sDataFilePath += L"\\regexfilters.ini"; if (bCloudIsNewer) { CSimpleIni origRegexIni; if (PathFileExists(sDataFilePath)) { int retrycount = 5; SI_Error err = SI_OK; do { err = origRegexIni.LoadFile(sDataFilePath); if (err == SI_FILE) { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error loading %s, retrycount %d\n", (LPCWSTR)sDataFilePath, retrycount); Sleep(500); } } while ((err == SI_FILE) && retrycount--); if (err == SI_FILE) { return false; } } CSimpleIni::TNamesDepend keys; iniFile.GetAllKeys(L"ini_tmergeregex", keys); for (const auto& k : keys) { CString sKey = k; CString sSection = sKey.Left(sKey.Find('.')); sKey = sKey.Mid(sKey.Find('.') + 1); CString sValue = CString(iniFile.GetValue(L"ini_tmergeregex", k, L"")); regexIni.SetValue(sSection, sKey, sValue); } FILE * pFile = NULL; errno_t err = 0; int retrycount = 5; CString sTempfile = CTempFiles::Instance().GetTempFilePathString(); do { err = _tfopen_s(&pFile, sTempfile, L"wb"); if ((err == 0) && pFile) { regexIni.SaveFile(pFile); err = fclose(pFile); } if (err) { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error saving %s, retrycount %d\n", (LPCWSTR)sTempfile, retrycount); Sleep(500); } } while (err && retrycount--); if (err == 0) { if (!CopyFile(sTempfile, sDataFilePath, FALSE)) CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error copying %s to %s, Error: %u\n", (LPCWSTR)sTempfile, (LPCWSTR)sDataFilePath, GetLastError()); } } else { if (PathFileExists(sDataFilePath)) { int retrycount = 5; SI_Error err = SI_OK; do { err = regexIni.LoadFile(sDataFilePath); if (err == SI_FILE) { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error loading %s, retrycount %d\n", (LPCWSTR)sDataFilePath, retrycount); Sleep(500); } } while ((err == SI_FILE) && retrycount--); if (err == SI_FILE) { return false; } } CSimpleIni::TNamesDepend mitems; regexIni.GetAllSections(mitems); for (const auto& mitem : mitems) { CString sSection = mitem; CString newval = regexIni.GetValue(mitem, L"regex", L""); CString oldval = iniFile.GetValue(L"ini_tmergeregex", sSection + L".regex", L""); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_tmergeregex", sSection + L".regex", newval); newval = regexIni.GetValue(mitem, L"replace", L"5"); oldval = iniFile.GetValue(L"ini_tmergeregex", sSection + L".replace", L"0"); bHaveChanges |= newval != oldval; iniFile.SetValue(L"ini_tmergeregex", sSection + L".replace", newval); } } } if (bHaveChanges) { iniFile.SetValue(L"sync", L"version", TSVN_SYNC_VERSION_STR); DWORD count = regCount; ++count; regCount = count; CString tmp; tmp.Format(L"%lu", count); iniFile.SetValue(L"sync", L"synccounter", tmp); // save the ini file std::string iniData; iniFile.SaveString(iniData); iniData = "***" + iniData; // encrypt the string CString password; if (parser.HasKey(L"askforpath")) { CPasswordDlg passDlg(CWnd::FromHandle(GetExplorerHWND())); passDlg.m_bForSave = true; if (passDlg.DoModal() != IDOK) return false; password = passDlg.m_sPW1; } else { CRegString regPW(L"Software\\TortoiseSVN\\SyncPW"); auto passwordbuf = CStringUtils::Decrypt(CString(regPW)); if (passwordbuf.get()) { password = passwordbuf.get(); } } std::string passworda = CUnicodeUtils::StdGetUTF8((LPCWSTR)password); std::string encrypted = CStringUtils::Encrypt(iniData, passworda); CPathUtils::MakeSureDirectoryPathExists(syncPath.GetContainingDirectory().GetWinPathString()); CString sTempfile = CTempFiles::Instance().GetTempFilePathString(); CAutoFile hFile = CreateFile(sTempfile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile.IsValid()) { DWORD written = 0; if (WriteFile(hFile, encrypted.c_str(), DWORD(encrypted.size()), &written, NULL)) { if (hFile.CloseHandle()) { if (!CopyFile(sTempfile, syncPath.GetWinPath(), FALSE)) { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error copying %s to %s, Error: %u\n", (LPCWSTR)sTempfile, syncPath.GetWinPath(), GetLastError()); } else bRet = true; } else CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error closing file %s, Error: %u\n", (LPCWSTR)sTempfile, GetLastError()); } else CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error writing to file %s, Error: %u\n", (LPCWSTR)sTempfile, GetLastError()); } else CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Error creating file %s for writing, Error: %u\n", (LPCWSTR)sTempfile, GetLastError()); if (bSyncAuth) { // now save all auth data CPathUtils::MakeSureDirectoryPathExists(syncFolder.GetWinPathString() + L"\\auth"); CPathUtils::MakeSureDirectoryPathExists(syncFolder.GetWinPathString() + L"\\auth\\svn.simple"); CPathUtils::MakeSureDirectoryPathExists(syncFolder.GetWinPathString() + L"\\auth\\svn.ssl.client-passphrase"); CPathUtils::MakeSureDirectoryPathExists(syncFolder.GetWinPathString() + L"\\auth\\svn.ssl.server"); CPathUtils::MakeSureDirectoryPathExists(syncFolder.GetWinPathString() + L"\\auth\\svn.username"); authData.ExportAuthData(syncFolder.GetWinPathString(), password); } } return bRet; }
bool SyncCommand::HandleRegistryKey(const CString& regname, CSimpleIni& iniFile, bool bCloudIsNewer) { CAutoRegKey hKey; CAutoRegKey hKeyKey; DWORD regtype = 0; DWORD regsize = 0; CString sKeyPath = L"Software"; CString sValuePath = regname; CString sIniKeyName = regname; CString sRegname = regname; CString sValue; bool bHaveChanges = false; if (regname.Find('\\') >= 0) { // handle values in sub-keys sKeyPath = L"Software\\" + regname.Left(regname.ReverseFind('\\')); sValuePath = regname.Mid(regname.ReverseFind('\\') + 1); } if (RegOpenKeyEx(HKEY_CURRENT_USER, sKeyPath, 0, KEY_READ, hKey.GetPointer()) == ERROR_SUCCESS) { bool bEnum = false; bool bEnumKeys = false; int index = 0; int keyindex = 0; // an asterisk means: use all values inside the specified key if (sValuePath == L"*") bEnum = true; if (sValuePath == L"**") { bEnumKeys = true; bEnum = true; RegOpenKeyEx(HKEY_CURRENT_USER, sKeyPath, 0, KEY_READ, hKeyKey.GetPointer()); } do { if (bEnumKeys) { bEnum = true; index = 0; wchar_t cKeyName[MAX_PATH] = { 0 }; DWORD cLen = _countof(cKeyName); if (RegEnumKeyEx(hKeyKey, keyindex, cKeyName, &cLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { bEnumKeys = false; break; } ++keyindex; sKeyPath = L"Software\\" + regname.Left(regname.ReverseFind('\\')) + L"\\" + cKeyName + L"\\"; sRegname = regname.Left(regname.ReverseFind('\\')) + L"\\" + cKeyName + L"\\"; hKey.CloseHandle(); if (RegOpenKeyEx(HKEY_CURRENT_USER, sKeyPath, 0, KEY_READ, hKey.GetPointer()) != ERROR_SUCCESS) { bEnumKeys = false; break; } } do { if (bEnum) { // start enumerating all values wchar_t cValueName[MAX_PATH] = { 0 }; DWORD cLen = _countof(cValueName); if (RegEnumValue(hKey, index, cValueName, &cLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { bEnum = false; break; } ++index; sValuePath = cValueName; CString sValueLower = sValuePath; sValueLower.MakeLower(); bool bIgnore = false; for (const auto& ignore : regBlockArray) { if (wcswildcmp(ignore, sValueLower)) { bIgnore = true; break; } } if (bIgnore) continue; sIniKeyName = sRegname.Left(sRegname.ReverseFind('\\')); if (sIniKeyName.IsEmpty()) sIniKeyName = sValuePath; else sIniKeyName += L"\\" + sValuePath; } if (RegQueryValueEx(hKey, sValuePath, NULL, ®type, NULL, ®size) == ERROR_SUCCESS) { if (regtype != 0) { auto regbuf = std::make_unique<BYTE[]>(regsize); if (RegQueryValueEx(hKey, sValuePath, NULL, ®type, regbuf.get(), ®size) == ERROR_SUCCESS) { switch (regtype) { case REG_DWORD: { DWORD value = *(DWORD*)regbuf.get(); sValue = iniFile.GetValue(L"registry_dword", sIniKeyName); DWORD nValue = DWORD(_wtol(sValue)); if (nValue != value) { if (bCloudIsNewer) { RegSetValueEx(hKey, sValuePath, NULL, regtype, (BYTE *)&nValue, sizeof(nValue)); } else { bHaveChanges = true; sValue.Format(L"%lu", value); iniFile.SetValue(L"registry_dword", sIniKeyName, sValue); } } if (bCloudIsNewer) iniFile.Delete(L"registry_dword", sIniKeyName); } break; case REG_QWORD: { QWORD value = *(QWORD*)regbuf.get(); sValue = iniFile.GetValue(L"registry_qword", sIniKeyName); QWORD nValue = QWORD(_wtoi64(sValue)); if (nValue != value) { if (bCloudIsNewer) { RegSetValueEx(hKey, sValuePath, NULL, regtype, (BYTE *)&nValue, sizeof(nValue)); } else { bHaveChanges = true; sValue.Format(L"%I64d", value); iniFile.SetValue(L"registry_qword", sIniKeyName, sValue); } } if (bCloudIsNewer) iniFile.Delete(L"registry_qword", sIniKeyName); } break; case REG_EXPAND_SZ: case REG_MULTI_SZ: case REG_SZ: { sValue = (LPCWSTR)regbuf.get(); CString iniValue = iniFile.GetValue(L"registry_string", sIniKeyName); if (iniValue != sValue) { if (bCloudIsNewer) { RegSetValueEx(hKey, sValuePath, NULL, regtype, (BYTE *)(LPCWSTR)iniValue, (iniValue.GetLength() + 1)*sizeof(WCHAR)); } else { bHaveChanges = true; iniFile.SetValue(L"registry_string", sIniKeyName, sValue); } } if (bCloudIsNewer) iniFile.Delete(L"registry_string", sIniKeyName); } break; } } } } } while (bEnum); } while (bEnumKeys); } return bHaveChanges; }
//----------------------------------------------------------------------------- Bool MGStrOp::toU64( CChar16* src,U64& dest ) { dest = _wtoi64(src); return true; }