const TCHAR *PerfCounterMuninNodePlugin::GetPdhCounterLocalizedName(const TCHAR *englishName)
{
	TCHAR *regBuffer;
	DWORD regBufferSize = 4096;
	DWORD status;

	do {
		regBuffer = new TCHAR[regBufferSize];
		status = RegQueryValueEx(HKEY_PERFORMANCE_DATA, L"Counter 009", NULL, NULL, (LPBYTE)regBuffer, &regBufferSize);

		if (status == ERROR_MORE_DATA) {
			delete regBuffer;
			regBufferSize += 4096;
		} else {
			if (status != ERROR_SUCCESS) {
				delete regBuffer;
				_Module.LogEvent("PerfCounter plugin: %s: RegQueryValueEx error=%x", m_Name.c_str(), status);
				return englishName;
			}
		}
	} while (status != ERROR_SUCCESS);

	DWORD fIndex = -1;

	for (TCHAR *idx = regBuffer; *idx; idx += wcslen(idx) + 1) {
		TCHAR *cName = idx + wcslen(idx) + 1;
		if (_wcsicmp(cName, englishName) == 0) {
			fIndex = _wtol(idx);
			break;
		}
		idx = cName;
	}

	delete regBuffer;
	
	DWORD bufSize = 0;
	PdhLookupPerfNameByIndex(NULL, fIndex, NULL, &bufSize);
	TCHAR *localName = new TCHAR[bufSize];
	status = PdhLookupPerfNameByIndex(NULL, fIndex, localName, &bufSize);
	if (status != ERROR_SUCCESS) {
		_Module.LogError("PerfCounter plugin: %s: Could not find a local name for %ls, error=%x", m_Name.c_str(), englishName, status);
		return englishName;
	}
	return localName;
}
void MI_CALL MSFT_WindowsServiceProcess_AssociatorInstancesProcess(
    _In_opt_ MSFT_WindowsServiceProcess_Self* self,
    _In_ MI_Context* context,
    _In_opt_z_ const MI_Char* nameSpace,
    _In_opt_z_ const MI_Char* className,
    _In_ const CIM_Process* instanceName,
    _In_z_ const MI_Char* resultClass,
    _In_opt_ const MI_PropertySet* propertySet,
    _In_ MI_Boolean keysOnly,
    _In_opt_ const MI_Filter* filter)
{
    MI_Result result = MI_RESULT_OK;
    MI_Value tempHandleID;    
    MI_Type handleType;
    MI_Uint32 handleID;
    MI_UNREFERENCED_PARAMETER(self);
    MI_UNREFERENCED_PARAMETER(nameSpace);
    MI_UNREFERENCED_PARAMETER(className);
    MI_UNREFERENCED_PARAMETER(instanceName);
    MI_UNREFERENCED_PARAMETER(resultClass);
    MI_UNREFERENCED_PARAMETER(propertySet);
    MI_UNREFERENCED_PARAMETER(keysOnly);
    MI_UNREFERENCED_PARAMETER(filter);

    result = MI_Instance_GetElement(&instanceName->__instance, L"Handle", &tempHandleID, &handleType, NULL, NULL);
    if( result != MI_RESULT_OK)
    {
        MI_Context_PostResult(context, result);
        return;
    }

    if( handleType != MI_STRING)
    {
        MI_Context_PostResult(context, MI_RESULT_INVALID_PARAMETER);
        return;
    }    
    
    handleID =_wtol(tempHandleID.string);
    if( handleID == 0 )
    {
        MI_Context_PostResult(context, MI_RESULT_INVALID_PARAMETER);
        return;
    }
    GetServiceInstances(context, nameSpace, handleID, NULL);
}
bool cXMLDom::operator () (const bool value)
{
    // get the attribute as a boolean...
    if (this->getAttribute ())
    {
        // boolean can be alphanumerical...
        if (this->_attributeValue[0] == 'T') return true;
        else if (this->_attributeValue[0] == 't') return true;
        else if (this->_attributeValue[0] == 'Y') return true;
        else if (this->_attributeValue[0] == 'y') return true;
        // boolean can be numerical...
        else if (_wtol (this->_attributeValue)) return true;
        // no truths...
        return false;
    }
    // return the value as default...
    return value;
}
void T3000_Default_MainView::OnEnKillfocusEditFreid()
{
	//strTemp.Format(_T("%d"), (int)product_register_value[608]);
	//m_Edit_Network.SetWindowTextW(strTemp);
	//strTemp.Format(_T("%d"), (int)product_register_value[609]);
	//m_Edit_NodeID.SetWindowTextW(strTemp);
	CString strTemp;
	m_Edit_FrequenceID.GetWindowTextW(strTemp);
	  long Freq = _wtol(strTemp);
	/*long long Freq = ((long long)product_register_value[610]) * 65536 + ((long long)product_register_value[611]);
	*/
	unsigned short FreArray[2];
	  FreArray[0] = Freq / 65536;
	  FreArray[1] = Freq % 65536;
	  Write_Multi_org_short(g_tstat_id, FreArray, 610, 2, 5);
	  
// 	strTemp.Format(_T("%ld"), Freq);
// 	m_Edit_FrequenceID.SetWindowTextW(strTemp);
}
Esempio n. 5
0
wstring CWaveSession::ExtractChannelResponse(wstring szResponse)
{
	if (!szResponse.empty())
	{
		DWORD dwPos = szResponse.find(L'\n');

		if (dwPos != wstring::npos && dwPos > 0)
		{
			DWORD dwLength = _wtol(szResponse.substr(0, dwPos).c_str());

			if (szResponse.length() >= dwPos + 1 + dwLength)
			{
				return szResponse.substr(dwPos + 1, dwLength);
			}
		}
	}

	return L"";
}
long CSkypeMessageQueue::SupportedProtocol()
{
	try {
		if(m_lSupportedProtocol == -1) {
			WCHAR * pResult = ExecuteBlockingCommand(L"PROTOCOL 99999", L"PROTOCOL");
			if(wcslen(pResult) > 8) {
				m_lSupportedProtocol = _wtol(& pResult[9]);
				WCHAR strMsg[16];
				swprintf_s(strMsg, 16, L"PROTOCOL %d", SUPPORTED_PROTOCOL);
				InternalProcessCommand(strMsg);
			}
			free(pResult);
		}
	} catch(...) {
		return SUPPORTED_PROTOCOL;
	}

	return m_lSupportedProtocol; 
}
void ChatMessageCollection::SetItemList(LPCWSTR ItemList)
{
	try {
		m_itemList.clear();

		WCHAR * list = _wcsdup(ItemList);
		WCHAR *next_token = NULL;
		WCHAR * pItem = wcstok_s(list, L", ", &next_token);
		while(pItem) {
			long lID = _wtol(pItem);
			if(lID > 0) {
				m_itemList.push_back(lID);
			}
			pItem = wcstok_s(NULL, L", ", &next_token);
		}
	free(list);
	} catch(...) {
	}
}
Esempio n. 8
0
//
// convert unicode string to DWORD
//
HRESULT
Wstr2Dword
(
    _In_  LPCWSTR     pszSrc,
    _Out_ DWORD*      pdwDest
)
{
    HRESULT hr  =   S_OK;

    if ( (!pdwDest) || (!pszSrc) )
    {
        hr = E_INVALIDARG;
        BAIL_ON_FAILURE( hr );
    }

    (*pdwDest) = (DWORD) _wtol( pszSrc );

error:
    return hr;
}
Esempio n. 9
0
BOOL CMainDlg::GetDomainAndPortFromUrl(LPCTSTR strUrl, LPTSTR strDomain, INTERNET_PORT &nServerPort)
{
    ATLASSERT(strUrl);
    const int PORT_MAX_LENGTH = 5;
    TCHAR szPort[PORT_MAX_LENGTH];
    DWORD dwPort = PORT_MAX_LENGTH;
    HRESULT hPort = UrlGetPart(strUrl, 
        szPort, 
        &dwPort, 
        URL_PART_PORT, 
        NULL);
    if (hPort != S_OK)
    {
        nServerPort  = INTERNET_DEFAULT_HTTP_PORT;
        if( wcsnicmp(strUrl, URL_PROTOCOL_HTTPS, wcslen(URL_PROTOCOL_HTTPS)) == 0)
        {
            nServerPort  = INTERNET_DEFAULT_HTTPS_PORT;
        }
    }
    else
    {
        nServerPort = static_cast<INTERNET_PORT>(_wtol(szPort));
        ATLASSERT(nServerPort != 0);
        if (nServerPort == 0)
        {
            nServerPort = INTERNET_DEFAULT_HTTP_PORT;
        }
    }
    DWORD dwlen = static_cast<DWORD>(wcslen(strDomain));
    HRESULT hDomain = UrlGetPart(strUrl, 
        strDomain, 
        &dwlen, 
        URL_PART_HOSTNAME, 
        NULL);

    if (hDomain != S_OK)
    {
        return FALSE;
    }
    return TRUE;
}
Esempio n. 10
0
void CSkypeMessageQueue::InternalRebuildCallList()
{
	m_bNeedRebuildCallList = false;
	m_listCalls.clear();

	try {
		WCHAR * pStrCalls = gSkypeQueue.ExecuteBlockingCommand(L"SEARCH CALLS", L"CALLS");
		WCHAR * list = pStrCalls;
		WCHAR *next_token = NULL;
		WCHAR * pItem = wcstok_s(list, L", ", &next_token);
		while(pItem) {
			long lID = _wtol(pItem);
			if(lID > 0) {
				m_listCalls[lID] = prgUnknown;
			}
			pItem = wcstok_s(NULL, L", ", &next_token);
		}
		free(pStrCalls);
	} catch(const WCHAR * err) {
	}
}
Esempio n. 11
0
BOOL CSetDialogs::OnApply()
{
	UpdateData();
	if (m_cFontNames.GetSelFont())
		m_sFontName = m_cFontNames.GetSelFont()->m_strName;
	else
		m_sFontName = m_regFontName;

	Store(m_bShortDateFormat, m_regShortDateFormat);
	Store(m_bRelativeTimes, m_regRelativeTimes);
	Store(m_bAsteriskLogPrefix, m_regAsteriskLogPrefix);
	Store(m_bUseSystemLocaleForDates, m_regUseSystemLocaleForDates);

	int sel = m_cDefaultLogsScale.GetCurSel();
	Store(sel > 0 ? sel : 0, m_regDefaultLogsScale);

	int val = _wtol((LPCTSTR)m_sDefaultLogs);
	if (sel > 1 && val > 0)
		Store(val, m_regDefaultLogs);

	Store(m_sFontName, m_regFontName);
	Store(m_dwFontSize, m_regFontSize);
	Store(m_bDiffByDoubleClick, m_regDiffByDoubleClick);
	Store(m_bAbbreviateRenamings, m_regAbbreviateRenamings);
	Store(m_bSymbolizeRefNames, m_regSymbolizeRefNames);
	Store(m_bEnableLogCache, m_regEnableLogCache);
	Store(m_bEnableGravatar, m_regEnableGravatar);
	Store(m_GravatarUrl, m_regGravatarUrl);
	Store(m_bDrawBranchesTagsOnRightSide, m_regDrawBranchesTagsOnRightSide);
	Store(m_bShowDescribe, m_regShowDescribe);
	Store(m_bShowBranchRevNo, m_regShowBranchRevNo);
	Store(m_DescribeStrategy, m_regDescribeStrategy);
	Store(m_DescribeAbbreviatedSize, m_regDescribeAbbreviatedSize);
	Store(m_bDescribeAlwaysLong, m_regDescribeAlwaysLong);
	Store(m_bFullCommitMessageOnLogLine, m_regFullCommitMessageOnLogLine);
	Store(m_bMailmapOnLog, m_regMailmapOnLog);

	SetModified(FALSE);
	return ISettingsPropPage::OnApply();
}
Esempio n. 12
0
static BOOL CALLBACK
InstalledCPProc(PWSTR lpStr)
{
    LPCPAGE lpCP;
    UINT uiCP;

    lpCP = PCPage;
    uiCP = _wtol(lpStr);

    for (;;)
    {
        if (!lpCP) break;
        if (lpCP->CPage == uiCP)
        {
            lpCP->Status |= 0x0001;
            break;
        }
        lpCP = lpCP->NextItem;
    }

    return TRUE;
}
Esempio n. 13
0
void CShareOverlay::InitOverlay( const wchar_t *icon )
{
	s_bEnabled=true;
	if (icon)
	{
		Strcpy(s_IconPath,_countof(s_IconPath),icon);
		wchar_t *c=wcsrchr(s_IconPath,',');
		if (c)
		{
			*c=0;
			s_Index=-_wtol(c+1);
		}
		else
			s_Index=0;
	}
	else
	{
		Strcpy(s_IconPath,_countof(s_IconPath),L"%windir%\\system32\\imageres.dll");
		s_Index=-164;
	}
	DoEnvironmentSubst(s_IconPath,_countof(s_IconPath));
}
LRESULT CPropertyEditWindow::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    CAtlString strFontSize = LoadAtlString(IDS_FONT_SIZE_14);
    CAtlString strFontFace = LoadAtlString(IDS_FONT_FACE_ARIAL);

    LOGFONT lfLabelFont;
    lfLabelFont.lfHeight = _wtol(strFontSize);
    lfLabelFont.lfWidth = 0;
    lfLabelFont.lfEscapement = 0;
    lfLabelFont.lfOrientation = 0;
    lfLabelFont.lfWeight = FW_DONTCARE;
    lfLabelFont.lfItalic = FALSE;
    lfLabelFont.lfUnderline = FALSE;
    lfLabelFont.lfStrikeOut = FALSE;
    lfLabelFont.lfCharSet = DEFAULT_CHARSET;
    lfLabelFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
    lfLabelFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
    lfLabelFont.lfQuality = DEFAULT_QUALITY;
    lfLabelFont.lfPitchAndFamily = FF_DONTCARE | DEFAULT_PITCH;
    wcscpy_s(lfLabelFont.lfFaceName, 32, strFontFace);
    m_hLabelFont = CreateFontIndirect(&lfLabelFont);

    RECT buttonRect;
    GetClientRect(&buttonRect);
    buttonRect.right -= ms_ButtonWidth + ms_MarginWidth + ms_MarginWidth;
    buttonRect.bottom -= ms_MarginWidth;
    buttonRect.top = buttonRect.bottom - ms_ButtonHeight;
    buttonRect.left = buttonRect.right - ms_ButtonWidth;
    
    m_AddButton.Create(m_hWnd, &buttonRect, LoadAtlString(IDS_ADD), WS_CHILD | BS_DEFPUSHBUTTON, 0, IDC_ADDBUTTON);

    buttonRect.right += ms_ButtonWidth + ms_MarginWidth;
    buttonRect.left += ms_ButtonWidth + ms_MarginWidth;
    
    m_OKButton.Create(m_hWnd, &buttonRect, LoadAtlString(IDS_SAVE), WS_CHILD | BS_DEFPUSHBUTTON, 0, IDC_OKBUTTON);

    return 0;
}
Esempio n. 15
0
void CMainFrame::SetRibbonFont()
{
    CXTPOffice2007Theme* pOfficeTheme = (CXTPOffice2007Theme*)(m_cmdbars->GetPaintManager());
    CString fontname, sizestr;

    std::wstring fontcfg(GetStringValue(m_appname.c_str(), L"RibbonFont", L"."));
    if (fontcfg.size() < 2)
    {
        fontcfg = GetStringValue(L"uicorextp", L"RibbonFont", 
            getUIOptions()->GetString(L"ribbonFont", L"Tahoma,12").c_str());
    }

    AfxExtractSubString(fontname, fontcfg.c_str(), 0, ',');
    AfxExtractSubString(sizestr, fontcfg.c_str(), 1, ',');
    long fontsize = _wtol(sizestr);

    if (!fontname.IsEmpty() && pOfficeTheme->FontExists(fontname))
    {
        pOfficeTheme->m_strOfficeFont = fontname;
        XTPPaintManager()->m_strOfficeFont = fontname;
    }
    if (fontsize != 0)
    {
#if _XTPLIB_VERSION_MAJOR > 13
        pOfficeTheme->SetFontHeight(fontsize);
#else
        CXTPRibbonBar* pRibbonBar = DYNAMIC_DOWNCAST(
            CXTPRibbonBar, m_cmdbars->GetMenuBar());
        pRibbonBar->SetFontHeight(fontsize);
#endif
    }
    else
    {
        pOfficeTheme->UpdateFonts();
    }

    m_cmdbars->GetToolTipContext()->SetFont(m_cmdbars->GetPaintManager()->GetRegularFont());
}
Esempio n. 16
0
BOOL CVisualDrawContext::SelectSmallFont() 
{
    CAtlString strFontSize = LoadAtlString(IDS_FONT_SIZE_12);
    CAtlString strFontFace = LoadAtlString(IDS_FONT_FACE_ARIAL);

    LOGFONT lfLabelFont;
    lfLabelFont.lfHeight = _wtol(strFontSize);
    lfLabelFont.lfWidth = 0;
    lfLabelFont.lfEscapement = 0;
    lfLabelFont.lfOrientation = 0;
    lfLabelFont.lfWeight = FW_DONTCARE;
    lfLabelFont.lfItalic = FALSE;
    lfLabelFont.lfUnderline = FALSE;
    lfLabelFont.lfStrikeOut = FALSE;
    lfLabelFont.lfCharSet = DEFAULT_CHARSET;
    lfLabelFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
    lfLabelFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
    lfLabelFont.lfQuality = DEFAULT_QUALITY;
    lfLabelFont.lfPitchAndFamily = FF_DONTCARE | DEFAULT_PITCH;
    wcscpy_s(lfLabelFont.lfFaceName, 32, strFontFace);
    
    HFONT hSmallFont = CreateFontIndirect(&lfLabelFont);
    if(NULL == hSmallFont)
    {
        return FALSE;
    }
    
    m_State.m_hOldFont = SelectObject(m_hBgBuffer, hSmallFont);
    if(NULL == m_State.m_hOldFont)
    {
        DeleteObject(hSmallFont);
        return FALSE;
    }
    
    return true;
}
void CGraphicView::ReloadLabelsFromDB()
{
    ClearAllLabels();

    m_pCon.CreateInstance(_T("ADODB.Connection"));
    m_pRs.CreateInstance(_T("ADODB.Recordset"));
    m_pCon->Open(g_strDatabasefilepath.GetString(),_T(""),_T(""),adModeUnknown);
    CString strSql;
    //if(bac_cm5_graphic == false)
    strSql.Format(_T("select * from Screen_Label where Serial_Num =%i and Tstat_id=%i"),m_nSerialNumber,m_nTstatID);
    //else
    //strSql.Format(_T("select * from Screen_Label where Serial_Num =%i and Tstat_id=%i"),g_bac_instance,g_mac);
    //strSql.Format(_T("select * from Screen_Label where Tstat_id=%i"),m_nTstatID);
    m_pRs->Open((_variant_t)strSql,_variant_t((IDispatch *)m_pCon,true),adOpenStatic,adLockOptimistic,adCmdText);
    CString strtemp;
    strtemp.Empty();

    _variant_t temp_variant;
    int nTemp;
    CString strTemp;
    int nItem = 0;//用于记录有多少个需要刷新;
    while(VARIANT_FALSE==m_pRs->EndOfFile)
    {
        Label_information label;

        label.nSerialNum=m_nSerialNumber;
        label.tstat_id=m_nTstatID;
        label.strScreenName=m_strScreenName;

        nTemp=m_pRs->GetCollect("Cstatic_id");//
        label.cstatic_id=nTemp;

        nTemp=m_pRs->GetCollect("Point_X");//
        label.point.x=nTemp;

        nTemp=m_pRs->GetCollect("Point_Y");//
        label.point.y=nTemp;

        nTemp=m_pRs->GetCollect("Height");//
        label.height=nTemp;

        nTemp=m_pRs->GetCollect("Width");//
        label.width=nTemp;

        nTemp=m_pRs->GetCollect("Status");//
        label.status=nTemp;

        temp_variant=m_pRs->GetCollect("Tips");//
        if(temp_variant.vt!=VT_NULL)
            strtemp=temp_variant;
        else
            strtemp=_T("");
        label.strTips=strtemp;

        /*
        temp_variant=m_pRs->GetCollect("Tips");//
        if(temp_variant.vt!=VT_NULL)
        	strtemp=temp_variant;
        else
        	strtemp=_T("");
        label.strTips=strtemp;
        */


        nTemp=m_pRs->GetCollect("Input_or_Output");//
        label.input_or_output=nTemp;


        strTemp=m_pRs->GetCollect("Text_Color");//
        if(strTemp.IsEmpty())
        {
            label.clrTxt=0;
        }
        else
        {
            label.clrTxt=_wtol(strTemp);
        }


        strTemp=m_pRs->GetCollect("Back_Color");//
        if(strTemp.IsEmpty())
        {
            label.bkColor=254*255*255;
        }
        else
        {
            label.bkColor=_wtol(strTemp);
        }
        //	label.bkColor=nTemp;
        CRelayLabel* pLabel=new(CRelayLabel);
        pLabel->Create(_T(""),WS_CHILD|WS_VISIBLE|SS_CENTER,CRect(XStart+label.point.x,YStart+label.point.y,XStart+label.point.x+label.width,YStart+label.point.y+label.height), this,label.cstatic_id);

        //(int TstatID,int input_or_output,int nStatus,COLORREF textClr,COLORREF bkClr)
        pLabel->SetLabelInfo(label.tstat_id,label.input_or_output,label.status,label.clrTxt,label.bkColor);
        pLabel->MoveWindow(CRect(XStart+label.point.x,YStart+label.point.y,XStart+label.point.x+label.width,YStart+label.point.y+label.height));
        label.plabelCtrl=pLabel;
        m_RelayLabelLst.push_back(label);

        m_pRs->MoveNext();
        _Graphic_Value_Info temp1;
        m_graphic_refresh_data.push_back(temp1);
        m_graphic_refresh_data.at(nItem).deviceid = label.tstat_id;
        m_graphic_refresh_data.at(nItem).value_type = label.input_or_output;
        m_graphic_refresh_data.at(nItem).value_item = label.status;
        m_graphic_refresh_data.at(nItem).control_pt = pLabel;
        if(label.input_or_output == 0)
        {
            m_graphic_refresh_data.at(nItem).command = READINPUT_T3000;
            m_graphic_refresh_data.at(nItem).entitysize = sizeof(Str_in_point);
        }
        else if(label.input_or_output == 1)
        {
            m_graphic_refresh_data.at(nItem).command = READOUTPUT_T3000;
            m_graphic_refresh_data.at(nItem).entitysize = sizeof(Str_out_point);
        }
        else if(label.input_or_output == 2)
        {
            m_graphic_refresh_data.at(nItem).command = READVARIABLE_T3000;
            m_graphic_refresh_data.at(nItem).entitysize = sizeof(Str_variable_point);
        }
        m_graphic_refresh_data.at(nItem).hWnd = this->m_hWnd;
        nItem ++;
    }

    if(m_pRs->State)
        m_pRs->Close();
    if(m_pCon->State)
        m_pCon->Close();

}
unsigned long BuscarActualizaciones::ThreadDescargarActualizacion(void *phWnd) {
	
	TCHAR			szHead[]			= TEXT("Accept: */*\r\n\r\n");
	HINTERNET		Sesion				= InternetOpen(TEXT("BubaTronik"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, INTERNET_INVALID_PORT_NUMBER, 0);
	HINTERNET		Peticion			= InternetOpenUrl(Sesion, TEXT("http://www.devildrey33.es/BubaTronik/Instalar.exe"), szHead, 0, INTERNET_FLAG_RELOAD, 0);
//	DWORD			Longitud			= 0;
	DWORD			Descargado			= 64;
	DWORD           TotalDescargado		= 0;
	char		    Datos[4097];
	DWORD			TotalDatos			= 0;
	TCHAR			TotalDatosStr[64];
	BOOL Ret = HttpQueryInfo(Peticion, HTTP_QUERY_CONTENT_LENGTH, (LPVOID)TotalDatosStr, &Descargado, (LPDWORD)0);
	if (Ret == TRUE) TotalDatos = _wtol(TotalDatosStr);
	
	HWND hWndPlayer = reinterpret_cast<HWND>(phWnd);
	PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_MAXIMOBARRA, NULL, static_cast<LPARAM>(TotalDatos));
	Descargado = 0;
	DWL::DWLString PathFinal; // = Sistema.App.AppPath(); 
	Sistema.Directorio.AppData(PathFinal);
	PathFinal += TEXT("\\BubaTronik\\Instalar.exe");
	DWL::Archivos::DWLArchivoBinario Archivo(PathFinal(), true);
	
	while (TRUE) {
		PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_POSICIONBARRA, NULL, static_cast<LPARAM>(TotalDescargado));
		WaitForSingleObject(Mutex, INFINITE);
        if (!InternetReadFile(Peticion, (LPVOID)Datos, 4096, &Descargado) || _CancelarDescarga == true) {
            ReleaseMutex(Mutex);
			break;
		}
        ReleaseMutex(Mutex);
		Datos[Descargado] = '\0';
		TotalDescargado += Descargado;
		if (Descargado == 0)	break;
		else					Archivo.Guardar(Datos, Descargado);
	}
    
	
	InternetCloseHandle(Peticion);
	// Leemos el hash que tiene la web
	Peticion = InternetOpenUrl(Sesion, TEXT("http://www.devildrey33.es/BubaTronik/Instalar.exe.hash"), szHead, 0, INTERNET_FLAG_RELOAD, 0);
	char  TxtHash[33]	= "";
	DWORD BytesLeidos	= 0;
	BOOL  Leido			= InternetReadFile(Peticion, TxtHash, 32, &BytesLeidos);

	// Calculo el hash del archivo descargado
#define MD5LEN  16
	DWORD	sz = Archivo.Posicion(0, true);
	HCRYPTPROV hProv = 0,hHash = 0;
	BYTE	rgbHash[MD5LEN + 1] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
    DWORD	cbHash = 0;
    char	finalhash[33] = "", dig[] = "0123456789abcdef";
    BYTE   *hash = new BYTE[sz];
	size_t  l = 0;
	Archivo.Posicion(0, false);
	Archivo.Leer(hash, sz);

 	CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
	CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
	CryptHashData(hHash, hash, sz, 0);
	cbHash = MD5LEN;
	BOOL RET = CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0);
    for(DWORD i = 0; i < cbHash; i ++){
        finalhash[l] = dig[rgbHash[i] >> 4];
        l ++;
        finalhash[l] = dig[rgbHash[i] & 0xf];
        l ++;
    }
	     
    for(l = 32; l < strlen(finalhash); l++)	finalhash[l] = 0;
    CryptDestroyHash(hHash);
    CryptReleaseContext(hProv, 0);
	delete [] hash;

	if (_strcmpi(finalhash, TxtHash) != 0)
		TotalDescargado ++; // Si no son iguales sumo 1 a los bytes descargados para retornar false

	InternetCloseHandle(Peticion);


	InternetCloseHandle(Sesion);


//    ReleaseMutex(Mutex);
    CloseHandle(Mutex);

	if (_CancelarDescarga == false) PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_FINDESCARGA, NULL, static_cast<LPARAM>(TotalDescargado == TotalDatos));
	return TRUE;
}
Esempio n. 19
0
int __cdecl
wmain(ULONG argc, PWCHAR argv[])
{
	int status;
	ULONG command;
	PDOKAN_OPERATIONS dokanOperations =
			(PDOKAN_OPERATIONS)malloc(sizeof(DOKAN_OPERATIONS));
	if (dokanOperations == NULL) {
		return -1;
	}
	PDOKAN_OPTIONS dokanOptions =
			(PDOKAN_OPTIONS)malloc(sizeof(DOKAN_OPTIONS));
	if (dokanOptions == NULL) {
		free(dokanOperations);
		return -1;
	}

	if (argc < 5) {
		fprintf(stderr, "mirror.exe\n"
			"  /r RootDirectory (ex. /r c:\\test)\n"
			"  /l DriveLetter (ex. /l m)\n"
			"  /t ThreadCount (ex. /t 5)\n"
			"  /d (enable debug output)\n"
			"  /s (use stderr for output)\n"
			"  /n (use network drive)\n"
			"  /m (use removable drive)\n"
            "  /i (Timeout in Milliseconds ex. /i 30000)\n");
		return -1;
	}

	g_DebugMode = FALSE;
	g_UseStdErr = FALSE;

	ZeroMemory(dokanOptions, sizeof(DOKAN_OPTIONS));
	dokanOptions->Version = DOKAN_VERSION;
	dokanOptions->ThreadCount = 0; // use default

	for (command = 1; command < argc; command++) {
		switch (towlower(argv[command][1])) {
		case L'r':
			command++;
			wcscpy_s(RootDirectory, sizeof(RootDirectory)/sizeof(WCHAR), argv[command]);
			DbgPrint(L"RootDirectory: %ls\n", RootDirectory);
			break;
		case L'l':
			command++;
			wcscpy_s(MountPoint, sizeof(MountPoint)/sizeof(WCHAR), argv[command]);
			dokanOptions->MountPoint = MountPoint;
			break;
		case L't':
			command++;
			dokanOptions->ThreadCount = (USHORT)_wtoi(argv[command]);
			break;
		case L'd':
			g_DebugMode = TRUE;
			break;
		case L's':
			g_UseStdErr = TRUE;
			break;
		case L'n':
			dokanOptions->Options |= DOKAN_OPTION_NETWORK;
			break;
		case L'm':
			dokanOptions->Options |= DOKAN_OPTION_REMOVABLE;
			break;
        case L'i':
            command++;
            dokanOptions->Timeout = (ULONG)_wtol(argv[command]);
            break;
		default:
			fwprintf(stderr, L"unknown command: %s\n", argv[command]);
			return -1;
		}
	}

	if (g_DebugMode) {
		dokanOptions->Options |= DOKAN_OPTION_DEBUG;
	}
	if (g_UseStdErr) {
		dokanOptions->Options |= DOKAN_OPTION_STDERR;
	}

	dokanOptions->Options |= DOKAN_OPTION_KEEP_ALIVE;
	dokanOptions->Options |= DOKAN_OPTION_ALT_STREAM;

	ZeroMemory(dokanOperations, sizeof(DOKAN_OPERATIONS));
	dokanOperations->CreateFile = MirrorCreateFile;
	dokanOperations->OpenDirectory = MirrorOpenDirectory;
	dokanOperations->CreateDirectory = MirrorCreateDirectory;
	dokanOperations->Cleanup = MirrorCleanup;
	dokanOperations->CloseFile = MirrorCloseFile;
	dokanOperations->ReadFile = MirrorReadFile;
	dokanOperations->WriteFile = MirrorWriteFile;
	dokanOperations->FlushFileBuffers = MirrorFlushFileBuffers;
	dokanOperations->GetFileInformation = MirrorGetFileInformation;
	dokanOperations->FindFiles = MirrorFindFiles;
	dokanOperations->FindFilesWithPattern = NULL;
	dokanOperations->SetFileAttributes = MirrorSetFileAttributes;
	dokanOperations->SetFileTime = MirrorSetFileTime;
	dokanOperations->DeleteFile = MirrorDeleteFile;
	dokanOperations->DeleteDirectory = MirrorDeleteDirectory;
	dokanOperations->MoveFile = MirrorMoveFile;
	dokanOperations->SetEndOfFile = MirrorSetEndOfFile;
	dokanOperations->SetAllocationSize = MirrorSetAllocationSize;	
	dokanOperations->LockFile = MirrorLockFile;
	dokanOperations->UnlockFile = MirrorUnlockFile;
	dokanOperations->GetFileSecurity = MirrorGetFileSecurity;
	dokanOperations->SetFileSecurity = MirrorSetFileSecurity;
	dokanOperations->GetDiskFreeSpace = NULL;
	dokanOperations->GetVolumeInformation = MirrorGetVolumeInformation;
	dokanOperations->Unmount = MirrorUnmount;
	dokanOperations->EnumerateNamedStreams = MirrorEnumerateNamedStreams;

	status = DokanMain(dokanOptions, dokanOperations);
	switch (status) {
	case DOKAN_SUCCESS:
		fprintf(stderr, "Success\n");
		break;
	case DOKAN_ERROR:
		fprintf(stderr, "Error\n");
		break;
	case DOKAN_DRIVE_LETTER_ERROR:
		fprintf(stderr, "Bad Drive letter\n");
		break;
	case DOKAN_DRIVER_INSTALL_ERROR:
		fprintf(stderr, "Can't install driver\n");
		break;
	case DOKAN_START_ERROR:
		fprintf(stderr, "Driver something wrong\n");
		break;
	case DOKAN_MOUNT_ERROR:
		fprintf(stderr, "Can't assign a drive letter\n");
		break;
	case DOKAN_MOUNT_POINT_ERROR:
		fprintf(stderr, "Mount point error\n");
		break;
	default:
		fprintf(stderr, "Unknown error: %d\n", status);
		break;
	}

	free(dokanOptions);
	free(dokanOperations);
	return 0;
}
Esempio n. 20
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;
}
Esempio n. 21
0
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, &regtype, NULL, &regsize) == ERROR_SUCCESS)
                {
                    if (regtype != 0)
                    {
                        auto regbuf = std::make_unique<BYTE[]>(regsize);
                        if (RegQueryValueEx(hKey, sValuePath, NULL, &regtype, regbuf.get(), &regsize) == 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;
}
Esempio n. 22
0
int main( int argc, char * const argv[] )
#endif
{
	libcerror_error_t *error                 = NULL;
	libcfile_file_t *destination_file        = NULL;
	libcfile_file_t *source_file             = NULL;
	system_character_t *option_target_path   = NULL;
	system_character_t *options_string       = NULL;
	system_character_t *source               = NULL;
	uint8_t *buffer                          = NULL;
	uint8_t *uncompressed_data               = NULL;
	char *program                            = "lzxpressdecompress";
	system_integer_t option                  = 0;
	size64_t source_size                     = 0;
	size_t buffer_size                       = 0;
	size_t uncompressed_data_size            = 0;
	ssize_t read_count                       = 0;
	ssize_t write_count                      = 0;
	off_t source_offset                      = 0;
	int decompression_method                 = 1;
	int result                               = 0;
	int verbose                              = 0;

#if defined( WINAPI )
	void *workspace                          = NULL;
	unsigned short winapi_compression_method = 0;
#endif

	assorted_output_version_fprint(
	 stdout,
	 program );

#if defined( WINAPI )
	options_string = _SYSTEM_STRING( "d:ho:s:t:vV1234" );
#else
	options_string = _SYSTEM_STRING( "d:ho:s:t:vV12" );
#endif
	while( ( option = assorted_getopt(
	                   argc,
	                   argv,
	                   options_string ) ) != (system_integer_t) -1 )
	{
		switch( option )
		{
			case (system_integer_t) '?':
			default:
				fprintf(
				 stderr,
				 "Invalid argument: %" PRIs_SYSTEM "\n",
				 argv[ optind ] );

				usage_fprint(
				 stdout );

				return( EXIT_FAILURE );

			case (system_integer_t) '1':
				decompression_method = 1;

				break;

			case (system_integer_t) '2':
				decompression_method = 2;

				break;

#if defined( WINAPI )
			case (system_integer_t) '3':
				decompression_method = 3;

				break;

			case (system_integer_t) '4':
				decompression_method = 4;

				break;

#endif
			case (system_integer_t) 'd':
#if defined( HAVE_WIDE_SYSTEM_CHARACTER )
				uncompressed_data_size = _wtol( optarg );
#else
				uncompressed_data_size = atol( optarg );
#endif
				break;

			case (system_integer_t) 'h':
				usage_fprint(
				 stdout );

				return( EXIT_SUCCESS );

			case (system_integer_t) 'o':
#if defined( HAVE_WIDE_SYSTEM_CHARACTER )
				source_offset = _wtol( optarg );
#else
				source_offset = atol( optarg );
#endif
				break;

			case (system_integer_t) 's':
#if defined( HAVE_WIDE_SYSTEM_CHARACTER )
				source_size = _wtol( optarg );
#else
				source_size = atol( optarg );
#endif
				break;

			case (system_integer_t) 't':
				option_target_path = optarg;

				break;

			case (system_integer_t) 'v':
				verbose = 1;

				break;

			case (system_integer_t) 'V':
				assorted_output_copyright_fprint(
				 stdout );

				return( EXIT_SUCCESS );
		}
	}
	if( optind == argc )
	{
		fprintf(
		 stderr,
		 "Missing source file.\n" );

		usage_fprint(
		 stdout );

		return( EXIT_FAILURE );
	}
	source = argv[ optind ];

	libcnotify_stream_set(
	 stderr,
	 NULL );
	libcnotify_verbose_set(
	 verbose );

	/* Open the source file
	 */
	if( libcfile_file_initialize(
	     &source_file,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to create source file.\n" );

		goto on_error;
	}
#if defined( HAVE_WIDE_SYSTEM_CHARACTER )
	result = libcfile_file_open_wide(
	          source_file,
	          source,
	          LIBCFILE_OPEN_READ,
	          &error );
#else
	result = libcfile_file_open(
	          source_file,
	          source,
	          LIBCFILE_OPEN_READ,
	          &error );
#endif
 	if( result != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to open source file.\n" );

		goto on_error;
	}
	if( source_size == 0 )
	{
		if( libcfile_file_get_size(
		     source_file,
		     &source_size,
		     &error ) == -1 )
		{
			fprintf(
			 stderr,
			 "Unable to determine size of source file.\n" );

			goto on_error;
		}
		if( source_size <= (size64_t) source_offset )
		{
			fprintf(
			 stderr,
			 "Invalid source size value is less equal than source offset.\n" );

			goto on_error;
		}
		source_size -= source_offset;
	}
	if( source_size == 0 )
	{
		fprintf(
		 stderr,
		 "Invalid source size value is zero.\n" );

		goto on_error;
	}
	if( source_size > (size_t) SSIZE_MAX )
	{
		fprintf(
		 stderr,
		 "Invalid source size value exceeds maximum.\n" );

		goto on_error;
	}
	/* Create the input buffer
	 */
	buffer_size = source_size;

	buffer = (uint8_t *) memory_allocate(
	                      sizeof( uint8_t ) * buffer_size );

	if( buffer == NULL )
	{
		fprintf(
		 stderr,
		 "Unable to create buffer.\n" );

		goto on_error;
	}
	if( uncompressed_data_size == 0 )
	{
		uncompressed_data_size = 65536;
	}
	uncompressed_data = (uint8_t *) memory_allocate(
	                                 sizeof( uint8_t ) * uncompressed_data_size );

	if( uncompressed_data == NULL )
	{
		fprintf(
		 stderr,
		 "Unable to create uncompressed data buffer.\n" );

		goto on_error;
	}
	if( memory_set(
             uncompressed_data,
	     0,
	     uncompressed_data_size ) == NULL )
	{
		fprintf(
		 stderr,
		 "Unable to clear uncompressed data buffer.\n" );

		goto on_error;
	}
	/* Position the source file at the right offset
	 */
	if( libcfile_file_seek_offset(
	     source_file,
	     source_offset,
	     SEEK_SET,
	     &error ) == -1 )
	{
		fprintf(
		 stderr,
		 "Unable to seek offset in source file.\n" );

		goto on_error;
	}
	fprintf(
	 stdout,
	 "Starting LZXPRESS decompression of: %" PRIs_SYSTEM " at offset: %" PRIjd " (0x%08" PRIjx ").\n",
	 source,
	 source_offset,
	 source_offset );

	read_count = libcfile_file_read_buffer(
		      source_file,
		      buffer,
		      source_size,
	              &error );

	if( read_count != (ssize_t) source_size )
	{
		fprintf(
		 stderr,
		 "Unable to read from source file.\n" );

		goto on_error;
	}
	/* Decompress the data
	 */
	if( option_target_path == NULL )
	{
		fprintf(
		 stderr,
		 "Compressed data:\n" );

		libcnotify_print_data(
		 buffer,
		 source_size,
		 LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
	}
	if( decompression_method == 1 )
	{
		result = libfwnt_lzxpress_decompress(
		          buffer,
		          (size_t) source_size,
		          uncompressed_data,
		          &uncompressed_data_size,
		          &error );
	}
	else if( decompression_method == 2 )
	{
		result = libfwnt_lzxpress_huffman_decompress(
		          buffer,
		          (size_t) source_size,
		          uncompressed_data,
		          &uncompressed_data_size,
		          &error );
	}
#if defined( WINAPI )
	else if( ( decompression_method == 3 )
	      || ( decompression_method == 4 ) )
	{
		if( decompression_method == 3 )
		{
			winapi_compression_method = COMPRESSION_FORMAT_XPRESS;
		}
		else if( decompression_method == 4 )
		{
			winapi_compression_method = COMPRESSION_FORMAT_XPRESS_HUFF;
		}
/* TODO: determine workspace size: RtlGetCompressionWorkSpaceSize */
		workspace = (void *) memory_allocate(
		                      16 * 1024 * 1024 );

		if( workspace == NULL )
		{
			fprintf(
			 stderr,
			 "Unable to create workspace.\n" );

			goto on_error;
		}
		result = lzxpresscompress_RtlDecompressBufferEx(
		          winapi_compression_method,
		          (unsigned char *) uncompressed_data,
		          (unsigned long) uncompressed_data_size,
		          (unsigned char *) buffer,
		          (unsigned long) source_size,
		          (unsigned long *) &uncompressed_data_size,
		          workspace );

		memory_free(
		 workspace );

		if( result != 0 )
		{
			result = -1;
		}
		else
		{
			result = 1;
		}
	}
#endif
	if( result == -1 )
	{
		fprintf(
		 stderr,
		 "Unable to decompress data.\n" );

		libcnotify_print_data(
		 uncompressed_data,
		 uncompressed_data_size,
		 LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );

		goto on_error;
	}
	if( option_target_path == NULL )
	{
		fprintf(
		 stderr,
		 "Uncompressed data:\n" );

		libcnotify_print_data(
		 uncompressed_data,
		 uncompressed_data_size,
		 LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
	}
	else
	{
		if( libcfile_file_initialize(
		     &destination_file,
		     &error ) != 1 )
		{
			fprintf(
			 stderr,
			 "Unable to create destination file.\n" );

			goto on_error;
		}
#if defined( HAVE_WIDE_SYSTEM_CHARACTER )
		result = libcfile_file_open_wide(
		          destination_file,
		          option_target_path,
		          LIBCFILE_OPEN_WRITE,
		          &error );
#else
		result = libcfile_file_open(
		          destination_file,
		          option_target_path,
		          LIBCFILE_OPEN_WRITE,
		          &error );
#endif
	 	if( result != 1 )
		{
			fprintf(
			 stderr,
			 "Unable to open destination file.\n" );

			goto on_error;
		}
		write_count = libcfile_file_write_buffer(
			       destination_file,
			       uncompressed_data,
			       uncompressed_data_size,
			       &error );

		if( write_count != (ssize_t) uncompressed_data_size )
		{
			fprintf(
			 stderr,
			 "Unable to write to destination file.\n" );

			goto on_error;
		}
		if( libcfile_file_close(
		     destination_file,
		     &error ) != 0 )
		{
			fprintf(
			 stderr,
			 "Unable to close destination file.\n" );

			goto on_error;
		}
		if( libcfile_file_free(
		     &destination_file,
		     &error ) != 1 )
		{
			fprintf(
			 stderr,
			 "Unable to free destination file.\n" );

			goto on_error;
		}
	}
	/* Clean up
	 */
	if( libcfile_file_close(
	     source_file,
	     &error ) != 0 )
	{
		fprintf(
		 stderr,
		 "Unable to close source file.\n" );

		goto on_error;
	}
	if( libcfile_file_free(
	     &source_file,
	     &error ) != 1 )
	{
		fprintf(
		 stderr,
		 "Unable to free source file.\n" );

		goto on_error;
	}
	memory_free(
	 uncompressed_data );

	uncompressed_data = NULL;

	memory_free(
	 buffer );

	buffer = NULL;

	fprintf(
	 stdout,
	 "LZXPRESS decompression:\tSUCCESS\n" );

	return( EXIT_SUCCESS );

on_error:
	if( error != NULL )
	{
		libcnotify_print_error_backtrace(
		 error );
		libcerror_error_free(
		 &error );
	}
	if( destination_file != NULL )
	{
		libcfile_file_free(
		 &destination_file,
		 NULL );
	}
	if( uncompressed_data != NULL )
	{
		memory_free(
		 uncompressed_data );
	}
	if( buffer != NULL )
	{
		memory_free(
		 buffer );
	}
	if( source_file != NULL )
	{
		libcfile_file_free(
		 &source_file,
		 NULL );
	}
	fprintf(
	 stdout,
	 "LZXPRESS decompression:\tFAILURE\n" );

	return( EXIT_FAILURE );
}
Esempio n. 23
0
/**
\brief Início desta janela.
\details	Funções executadas neste módulo:
	- Configurar a janela para se adequar o padrão do PMA:
		- Configuração da barra de comando;
		- Criar o banner da parte superior;
		- Configurar tela cheia;
	- Configurar as colunas da lista que serão mostrados os arquivos a serem baixados e inseridos;
	- Iniciar a passagem de parâmetros a serem utilizados neste módulo;
	- Indicar configurações de proxy;
	- Indicar arquivo de estrutura de dados;
	- Criar o timer para a próxima execução

\param void
\return TRUE se a execução ocorrer com sucesso
*/
BOOL CUpdateDlg::OnInitDialog()
{
	m_wnd = CMsgWindow::getInstance();
	m_wnd->Create(this);
	m_wnd->Show(L"Processando atualizações...");

	CDialogEx::OnInitDialog();

#ifdef _WIN32_WCE
	HideSIP();

	if (!m_dlgCommandBar.Create(this))
	{
		STLOG_WRITE("CUpdateDlg::OnInitDialog() : Failed to create CommandBar");
		return FALSE;      // fail to create
	}

	_CreateBanner(IDB_HEADER, FALSE, 28, L"Atualização de dados", 5);
	m_banner.ShowWindow(SW_SHOW);


	//Prepara lista em que vai aparecer os arquivos e o total
	m_list.InsertColumn( 0, L"Nome Arquivo", LVCFMT_LEFT, DRA::SCALEX(115) );
	m_list.InsertColumn( 1, L"Total", LVCFMT_LEFT, DRA::SCALEX(90) );

	_FullScreen();
#else
	m_list.InsertColumn( 0, L"Nome Arquivo", LVCFMT_LEFT, 115 );
	m_list.InsertColumn( 1, L"Total", LVCFMT_LEFT, 90 );
#endif

	ASSERT(NULL != m_params);

	m_proxyInfo.bDiscagem = m_params->GetValue(_T("DISCAGEM")).CompareNoCase(L"TRUE") == 0;
	m_proxyInfo.bProxy	  = m_params->GetValue(_T("PROXY")).CompareNoCase(L"TRUE") == 0;
	m_proxyInfo.sServer	  = m_params->GetValue(_T("SERVER"));
	m_proxyInfo.nPort	  = _wtol(m_params->GetValue(_T("PORT")));
	m_proxyInfo.sUser	  = m_params->GetValue(_T("USER"));
	m_proxyInfo.sPass	  = m_params->GetValue(_T("PASS"));

	STLOG_WRITE(L"m_proxyInfo.bProxy %ld", m_proxyInfo.bProxy);
	STLOG_WRITE(L"m_proxyInfo.sServer %s", m_proxyInfo.sServer);
	STLOG_WRITE(L"m_proxyInfo.nPort %ld", m_proxyInfo.nPort);
	STLOG_WRITE(L"m_proxyInfo.sUser %s", m_proxyInfo.sUser);

	SetStatus(L"Procurando por atualizações...");

	//Procura pelo arquivo que contém a estrutura das tabelas
	m_sStructPath = CUtil::GetAppPath();
	if(m_sStructPath.GetAt(m_sStructPath.GetLength()-1) != '\\')
		m_sStructPath += L"\\";
	m_sStructPath += L"EstruturaBD.txt";

	STLOG_WRITE("CUpdateDlg::OnInitDialog() : arquivo de estrutura: %S", m_sStructPath);

	if(!CUtil::FileExists(m_sStructPath))
	{
		STLOG_WRITE("CUpdateDlg::OnInitDialog() : Erro arquivo %S nao encontrado", m_sStructPath);
		EndDialog(IDCANCEL);
		return FALSE;
	}

	////m_httpFile.SetProxy(&m_proxyInfo);
	////m_httpFile.SetStructFile(m_sStructPath);

	//_CreateDatabase();

	//Sleep(1000);
	//OnTimer(ID_TIMER_SERVER_FILE);
	
	SetTimer(ID_TIMER_SERVER_FILE, 1000, NULL);

	return TRUE;
}
Esempio n. 24
0
void CSubAction::DoChangeValue()
{
	CLocateDlg* pLocateDlg=GetLocateDlg();
	if (pLocateDlg==NULL || m_szValue==NULL)
		return;
	
	// Get handle to control
	CWnd Control(pLocateDlg->GetDlgItem(LOWORD(m_nControl)));
	HWND hInDialog=*pLocateDlg;

	if (Control.GetHandle()==NULL)
		Control.SetHandle(pLocateDlg->m_NameDlg.GetDlgItem(LOWORD(m_nControl)));
	if (Control.GetHandle()==NULL)
		Control.SetHandle(pLocateDlg->m_SizeDateDlg.GetDlgItem(LOWORD(m_nControl)));
	if (Control.GetHandle()==NULL)
		Control.SetHandle(pLocateDlg->m_AdvancedDlg.GetDlgItem(LOWORD(m_nControl)));

	ASSERT(Control.GetHandle()!=NULL);

	if (!Control.IsWindowEnabled())
		return;

	char szClass[100];
	GetClassName(Control,szClass,100);
	if (_stricmp(szClass,"EDIT")==0)
	{
		Control.SetWindowText(m_szValue);
		::SendMessage(Control.GetParent(),WM_COMMAND,MAKEWPARAM(m_nControl,EN_CHANGE),LPARAM((HWND)Control));
	}
	else if (_stricmp(szClass,"COMBOBOX")==0)
	{
		if ((Control.GetStyle()&CBS_DROPDOWNLIST)!=CBS_DROPDOWNLIST)
		{
			Control.SetWindowText(m_szValue);
			::SendMessage(Control.GetParent(),WM_COMMAND,MAKEWPARAM(m_nControl,CBN_EDITCHANGE),LPARAM((HWND)Control));
		}
		else
		{
			Control.SendMessage(CB_SETCURSEL,_wtoi(m_szValue));
			::SendMessage(Control.GetParent(),WM_COMMAND,MAKEWPARAM(m_nControl,CBN_SELCHANGE),LPARAM((HWND)Control));
		}
	}
	else if (_stricmp(szClass,"BUTTON")==0)
	{
		if (Control.GetStyle()&BS_CHECKBOX)  // This also takes radiobuttons
		{
			Control.SendMessage(BM_SETCHECK,_wtoi(m_szValue));
			::SendMessage(Control.GetParent(),WM_COMMAND,MAKEWPARAM(m_nControl,BN_CLICKED),LPARAM((HWND)Control));
		}
	}
	else if (_stricmp(szClass,"ComboBoxEx32")==0)
	{
		CComboBoxEx cb(Control);
		cb.SetCurSel(-1);
		cb.SetItemText(-1,m_szValue);
	}
	else if (_stricmp(szClass,"SysDateTimePick32")==0)
	{
		SYSTEMTIME st;
		GetLocalTime(&st);
		st.wHour=0;
		st.wMinute=0;
		st.wSecond=0;
		st.wMilliseconds=0;
		
		if (wcslen(m_szValue)>=8)
		{
			
		
			WCHAR szTemp[5];
			MemCopyW(szTemp,m_szValue,4);
			szTemp[4]='\0';
			st.wYear=(WORD)_wtol(szTemp);

			MemCopyW(szTemp,m_szValue+4,2);
			szTemp[2]='\0';
			st.wMonth=(WORD)_wtol(szTemp);

			MemCopyW(szTemp,m_szValue+6,2);
			szTemp[2]='\0';
			st.wDay=(WORD)_wtol(szTemp);

		}
		else
		{
			int nIndex=CTime::GetIndex(st.wDay,st.wMonth,st.wYear);
			if (m_szValue[0]='-')
				nIndex-=(WORD)_wtol(m_szValue+1);
			else 
				nIndex+=(WORD)_wtol(m_szValue);

			CTime::GetDayFromIndex(nIndex,st.wDay,st.wMonth,st.wYear);
		}
		Control.SendMessage(DTM_SETSYSTEMTIME,GDT_VALID,LPARAM(&st));
	}
}
Esempio n. 25
0
/* parse argument list. we assume that all unrecognized arguments are file names. */
void CommandLineInfo::ParseCommandLine(const WCHAR *cmdLine)
{
    WStrVec argList;
    ParseCmdLine(cmdLine, argList);
    size_t argCount = argList.Count();

#define is_arg(txt) str::EqI(TEXT(txt), argument)
#define is_arg_with_param(txt) (is_arg(txt) && (argCount > n + 1))
#define additional_param() argList.At(n + 1)
#define has_additional_param() ((argCount > n + 1) && ('-' != additional_param()[0]))
#define handle_string_param(name) name.Set(str::Dup(argList.At(++n)))
#define handle_int_param(name) name = _wtoi(argList.At(++n))

    for (size_t n = 1; n < argCount; n++) {
        WCHAR *argument = argList.At(n);
        if (is_arg("-register-for-pdf")) {
            makeDefault = true;
            exitImmediately = true;
            return;
        }
        else if (is_arg("-silent")) {
            // silences errors happening during -print-to and -print-to-default
            silent = true;
        }
        else if (is_arg("-print-to-default")) {
            printerName.Set(GetDefaultPrinterName());
            if (!printerName)
                printDialog = true;
            exitWhenDone = true;
        }
        else if (is_arg_with_param("-print-to")) {
            handle_string_param(printerName);
            exitWhenDone = true;
        }
        else if (is_arg("-print-dialog")) {
            printDialog = true;
        }
        else if (is_arg_with_param("-print-settings")) {
            // argument is a comma separated list of page ranges and
            // advanced options [even|odd] and [noscale|shrink|fit]
            // e.g. -print-settings "1-3,5,10-8,odd,fit"
            handle_string_param(printSettings);
            str::RemoveChars(printSettings, L" ");
            str::TransChars(printSettings, L";", L",");
        }
        else if (is_arg("-exit-when-done") || is_arg("-exit-on-print")) {
            // only affects -print-dialog (-print-to and -print-to-default
            // always exit on print) and -stress-test (useful for profiling)
            exitWhenDone = true;
        }
        else if (is_arg_with_param("-inverse-search")) {
            str::ReplacePtr(&gGlobalPrefs->inverseSearchCmdLine, argList.At(++n));
            gGlobalPrefs->enableTeXEnhancements = true;
        }
        else if ((is_arg_with_param("-forward-search") ||
                  is_arg_with_param("-fwdsearch")) && argCount > n + 2) {
            // -forward-search is for consistency with -inverse-search
            // -fwdsearch is for consistency with -fwdsearch-*
            handle_string_param(forwardSearchOrigin);
            handle_int_param(forwardSearchLine);
        }
        else if (is_arg_with_param("-nameddest") || is_arg_with_param("-named-dest")) {
            // -nameddest is for backwards compat (was used pre-1.3)
            // -named-dest is for consistency
            handle_string_param(destName);
        }
        else if (is_arg_with_param("-page")) {
            handle_int_param(pageNumber);
        }
        else if (is_arg("-restrict")) {
            restrictedUse = true;
        }
        else if (is_arg("-invertcolors") || is_arg("-invert-colors")) {
            // -invertcolors is for backwards compat (was used pre-1.3)
            // -invert-colors is for consistency
            // -invert-colors used to be a shortcut for -set-color-range 0xFFFFFF 0x000000
            // now it non-permanently swaps textColor and backgroundColor
            gGlobalPrefs->fixedPageUI.invertColors = true;
        }
        else if (is_arg("-presentation")) {
            enterPresentation = true;
        }
        else if (is_arg("-fullscreen")) {
            enterFullScreen = true;
        }
        else if (is_arg_with_param("-view")) {
            ParseViewMode(&startView, argList.At(++n));
        }
        else if (is_arg_with_param("-zoom")) {
            ParseZoomValue(&startZoom, argList.At(++n));
        }
        else if (is_arg_with_param("-scroll")) {
            ParseScrollValue(&startScroll, argList.At(++n));
        }
        else if (is_arg("-console")) {
            showConsole = true;
        }
        else if (is_arg_with_param("-plugin")) {
            // -plugin [<URL>] <parent HWND>
            if (argCount > n + 2 && !str::IsDigit(*argList.At(n + 1)) && *argList.At(n + 2) != '-')
                handle_string_param(pluginURL);
            // the argument is a (numeric) window handle to
            // become the parent of a frameless SumatraPDF
            // (used e.g. for embedding it into a browser plugin)
            hwndPluginParent = (HWND)_wtol(argList.At(++n));
        }
        else if (is_arg_with_param("-stress-test")) {
            // -stress-test <file or dir path> [<file filter>] [<page/file range(s)>] [<cycle count>x]
            // e.g. -stress-test file.pdf 25x  for rendering file.pdf 25 times
            //      -stress-test file.pdf 1-3  render only pages 1, 2 and 3 of file.pdf
            //      -stress-test dir 301- 2x   render all files in dir twice, skipping first 300
            //      -stress-test dir *.pdf;*.xps  render all files in dir that are either PDF or XPS
            handle_string_param(stressTestPath);
            int num;
            if (has_additional_param() && str::FindChar(additional_param(), '*'))
                handle_string_param(stressTestFilter);
            if (has_additional_param() && IsValidPageRange(additional_param()))
                handle_string_param(stressTestRanges);
            if (has_additional_param() && str::Parse(additional_param(), L"%dx%$", &num) && num > 0) {
                stressTestCycles = num;
                n++;
            }
        }
        else if (is_arg_with_param("-n")) {
            handle_int_param(stressParallelCount);
        }
        else if (is_arg("-rand")) {
            stressRandomizeFiles = true;
        }
        else if (is_arg_with_param("-bench")) {
            WCHAR *s = str::Dup(argList.At(++n));
            pathsToBenchmark.Push(s);
            s = NULL;
            if (has_additional_param() && IsBenchPagesInfo(additional_param())) {
                s = str::Dup(argList.At(++n));
            }
            pathsToBenchmark.Push(s);
            exitImmediately = true;
        } else if (is_arg("-crash-on-open")) {
            // to make testing of crash reporting system in pre-release/release
            // builds possible
            crashOnOpen = true;
        }
        else if (is_arg("-reuse-instance")) {
            // for backwards compatibility, -reuse-instance reuses whatever
            // instance has registered as DDE server
            reuseDdeInstance = true;
        }
        // TODO: remove the following deprecated options within a release or two
        else if (is_arg("-esc-to-exit")) {
            gGlobalPrefs->escToExit = true;
        }
        else if (is_arg_with_param("-bgcolor") || is_arg_with_param("-bg-color")) {
            // -bgcolor is for backwards compat (was used pre-1.3)
            // -bg-color is for consistency
            ParseColor(&gGlobalPrefs->mainWindowBackground, argList.At(++n));
        }
        else if (is_arg_with_param("-lang")) {
            lang.Set(str::conv::ToAnsi(argList.At(++n)));
        }
        else if (is_arg("-set-color-range") && argCount > n + 2) {
            ParseColor(&gGlobalPrefs->fixedPageUI.textColor, argList.At(++n));
            ParseColor(&gGlobalPrefs->fixedPageUI.backgroundColor, argList.At(++n));
        }
        else if (is_arg_with_param("-fwdsearch-offset")) {
            handle_int_param(gGlobalPrefs->forwardSearch.highlightOffset);
            gGlobalPrefs->enableTeXEnhancements = true;
        }
        else if (is_arg_with_param("-fwdsearch-width")) {
            handle_int_param(gGlobalPrefs->forwardSearch.highlightWidth);
            gGlobalPrefs->enableTeXEnhancements = true;
        }
        else if (is_arg_with_param("-fwdsearch-color")) {
            ParseColor(&gGlobalPrefs->forwardSearch.highlightColor, argList.At(++n));
            gGlobalPrefs->enableTeXEnhancements = true;
        }
        else if (is_arg_with_param("-fwdsearch-permanent")) {
            handle_int_param(gGlobalPrefs->forwardSearch.highlightPermanent);
            gGlobalPrefs->enableTeXEnhancements = true;
        }
        else if (is_arg_with_param("-manga-mode")) {
            const WCHAR *s = argList.At(++n);
            gGlobalPrefs->comicBookUI.cbxMangaMode = str::EqI(L"true", s) || str::Eq(L"1", s);
        }
#if defined(SUPPORTS_AUTO_UPDATE) || defined(DEBUG)
        else if (is_arg_with_param("-autoupdate")) {
            n++; // this should have been handled already by AutoUpdateMain
        }
#endif
#ifdef DEBUG
        else if (is_arg("-enum-printers")) {
            EnumeratePrinters();
            /* this is for testing only, exit immediately */
            exitImmediately = true;
            return;
        }
#endif
        else {
            // Remember this argument as a filename to open
            WCHAR *filePath = NULL;
            if (str::EndsWithI(argList.At(n), L".lnk"))
                filePath = ResolveLnk(argList.At(n));
            if (!filePath)
                filePath = str::Dup(argList.At(n));
            fileNames.Push(filePath);
        }
    }
#undef is_arg
#undef is_arg_with_param
#undef additional_param
#undef has_additional_param
#undef handle_string_param
#undef handle_int_param
}
Esempio n. 26
0
void CSkypeMessageQueue::ProcessQueue()
{
	std::wstring strFull;
	std::wstring str;
	std::wstring strID;

	// Retrieve the next change in status
	if(! m_queueStatus.empty()) {
		SkypeAPIAttachmentStatus status = m_queueStatus.front();
		m_queueStatus.pop();

		for(CSkypeMessageSinkList::iterator it = m_MessageSinks.begin(); it != m_MessageSinks.end(); it++) {
			(*it)->ProcessAPIStatusChange(status);
		}
	}
	
	// Retrieve the next response, if there is one
	if(! m_queueIncoming.empty()) {
		strFull = m_queueIncoming.front();
		str = strFull;
		strID = L"";
		m_queueIncoming.pop();

		if(str[0] == L'#') {
			size_t iSpace = str.find(L" ");
			if(iSpace != -1) {
				strID = str.substr(0, iSpace + 1);
				str = str.substr(iSpace + 1, str.length() - iSpace);
			}
		}

		if(_wcsicmp(str.c_str(), L"CONNSTATUS LOGGEDOUT") == 0) {
			// When connection status is logged out, start rechecking for skype
			gSkypeQueue.DeleteAllBinaryTransfers();
			RestartTimer();
		}

		if(_wcsnicmp(str.c_str(), L"PROTOCOL ", 9) == 0) {
 			if(str.length() > 8) {
				bool bSendProtocol = (m_lSupportedProtocol == -1);
				m_lSupportedProtocol = _wtol(& str.c_str()[9]);
				if(bSendProtocol) {
					WCHAR strMsg[16];
					swprintf_s(strMsg, 16, L"PROTOCOL %d", SUPPORTED_PROTOCOL);
					InternalProcessCommand(strMsg);
				}
			}
		}

#ifndef _NO_USE_LIST
		if(! m_bNeedRebuildCallList) {
			if(_wcsnicmp(str.c_str(), L"CALL", 4) == 0) {
				WCHAR * ptrStatus;
				WCHAR * ptrStatusInd = wcsstr(str.c_str(), L" STATUS ");
				if(ptrStatusInd != NULL) {
					ptrStatus = & ptrStatusInd[8];
					if(ptrStatus != NULL) { 
						long lCallID = 0;
						if(swscanf_s(str.c_str(), L"CALL %d STATUS", & lCallID) == 1) {
							if(lCallID > 0) {
								SkypeCallProgress progress = TextToSkypeCallProgress(ptrStatus);
								UpdateCallProgress(lCallID, progress);
							}
						}
					}
				}
			}
		}
		if(! m_bNeedRebuildUserList) {
			if(_wcsnicmp(str.c_str(), L"USER", 4) == 0) {
				WCHAR * ptrOnlineStatus;
				WCHAR * ptrOnlineStatusInd = wcsstr(str.c_str(), L" ONLINESTATUS ");
				if(ptrOnlineStatusInd != NULL) {
					ptrOnlineStatus = & ptrOnlineStatusInd[14];
					if(ptrOnlineStatus != NULL) {
						WCHAR userID[_MAX_LINE];
						if(swscanf_s(str.c_str(), L"USER %s ONLINESTATUS", userID, _MAX_LINE) == 1) {
							if(wcslen(userID) > 0) {
								SkypeOnlineStatus status = TextToSkypeOnlineStatus(ptrOnlineStatus);
								UpdateUserOnlineStatus(userID, status);
							}
						}
					}
				}
			}
		}
#endif
		
		bool bProcessCallbacks = ! m_bBlocking;
		bool bMatch = false;
	
		// If we are waiting on a blocking call, set up the response
		if(m_bBlocking) {
			if((m_strDesiredResult.empty()) && (! m_blockingCommandID)) {
				m_strCommandResult = str;
			} else {
				if(m_blockingCommandID) {
					if(_wcsicmp(strID.c_str(), m_strCommandID) == 0) {
						m_strCommandResult = str;
						ATLTRACE(L"Response received: %s\n", strID.c_str());
						bMatch = true;	// イベントのブロックを解除
						
						if(_wcsnicmp(str.c_str(), L"ERROR", 5) == 0) {
							ATLTRACE(L"Error for %s detected: %s\n", strID.c_str(),
								str.c_str());
							m_bBlockingError = true;
						}
					}
				} else {
					WCHAR * pCopy = _wcsdup(m_strDesiredResult.c_str());
					WCHAR *next_token = NULL;
					WCHAR * pSearch = wcstok_s(pCopy, L"|", &next_token);
					while(pSearch && (! bMatch)) {
						if(wcsstr(str.c_str(), pSearch) != NULL) {
							m_strCommandResult = str;
							bMatch = true;
							break;
						}
						pSearch = wcstok_s(NULL, L"|", &next_token);
					}
					try {
						free(pCopy);
					} catch(...) {
					}

					if(! bMatch) {
						if(_wcsnicmp(str.c_str(), L"ERROR", 5) == 0) {
							m_strCommandResult = str;
							m_bBlockingError = true;
							bMatch = true;
						}
					}
				}
			}
		}	

		// Let the blocking routine know if a match was found
		if(m_bBlocking) {
			m_bBlocking = ! bMatch;
		}

// paak
// ブロックコマンド実行中のイベントの抑制は行わない。
// イベントは常に発生させ、コールバック内で有効性をチェックすべき。
bProcessCallbacks = true;

		// Trigger the response event sinks
		for(CSkypeMessageSinkList::iterator it = m_MessageSinks.begin(); it != m_MessageSinks.end(); it++) {
			(*it)->ProcessResponse(strFull.c_str(), bProcessCallbacks);
		}
	}

	if((! m_queueOutgoing.empty()) && (m_hWndSkype != NULL)) {

		str = m_queueOutgoing.front();
		m_queueOutgoing.pop();
		
		InternalProcessCommand(str.c_str());
	}

}
Esempio n. 27
0
/*********************************************************************
 *      _wtoi    (NTDLL.@)
 *
 * Converts a unicode string to an integer.
 *
 * PARAMS
 *  str [I] Wstring to be converted
 *
 * RETURNS
 *  On success it returns the integer value otherwise it returns 0.
 *
 * NOTES
 *  Accepts: {whitespace} [+|-] {digits}
 *  No check is made for value overflow, only the lower 32 bits are assigned.
 *  If str is NULL it crashes, as the native function does.
 */
int __cdecl _wtoi( LPCWSTR str )
{
    return _wtol(str);
}
Esempio n. 28
0
static int XCOPY_ParseCommandLine(WCHAR *suppliedsource,
                                  WCHAR *supplieddestination, DWORD *pflags)
{
    const WCHAR EXCLUDE[]  = {'E', 'X', 'C', 'L', 'U', 'D', 'E', ':', 0};
    DWORD flags = *pflags;
    WCHAR *cmdline, *word, *end, *next;
    int rc = RC_INITERROR;

    cmdline = _wcsdup(GetCommandLineW());
    if (cmdline == NULL)
        return rc;

    /* Skip first arg, which is the program name */
    if ((rc = find_end_of_word(cmdline, &word)) != RC_OK)
        goto out;
    word = skip_whitespace(word);

    while (*word)
    {
        WCHAR first;
        if ((rc = find_end_of_word(word, &end)) != RC_OK)
            goto out;

        next = skip_whitespace(end);
        first = word[0];
        *end = '\0';
        strip_quotes(word, &end);
        WINE_TRACE("Processing Arg: '%s'\n", wine_dbgstr_w(word));

        /* First non-switch parameter is source, second is destination */
        if (first != '/') {
            if (suppliedsource[0] == 0x00) {
                lstrcpyW(suppliedsource, word);
            } else if (supplieddestination[0] == 0x00) {
                lstrcpyW(supplieddestination, word);
            } else {
                XCOPY_wprintf(XCOPY_LoadMessage(STRING_INVPARMS));
                goto out;
            }
        } else {
            /* Process all the switch options
                 Note: Windows docs say /P prompts when dest is created
                       but tests show it is done for each src file
                       regardless of the destination                   */
            switch (toupper(word[1])) {
            case 'I': flags |= OPT_ASSUMEDIR;     break;
            case 'S': flags |= OPT_RECURSIVE;     break;
            case 'Q': flags |= OPT_QUIET;         break;
            case 'F': flags |= OPT_FULL;          break;
            case 'L': flags |= OPT_SIMULATE;      break;
            case 'W': flags |= OPT_PAUSE;         break;
            case 'T': flags |= OPT_NOCOPY | OPT_RECURSIVE; break;
            case 'Y': flags |= OPT_NOPROMPT;      break;
            case 'N': flags |= OPT_SHORTNAME;     break;
            case 'U': flags |= OPT_MUSTEXIST;     break;
            case 'R': flags |= OPT_REPLACEREAD;   break;
            case 'H': flags |= OPT_COPYHIDSYS;    break;
            case 'C': flags |= OPT_IGNOREERRORS;  break;
            case 'P': flags |= OPT_SRCPROMPT;     break;
            case 'A': flags |= OPT_ARCHIVEONLY;   break;
            case 'M': flags |= OPT_ARCHIVEONLY |
                               OPT_REMOVEARCH;    break;

            /* E can be /E or /EXCLUDE */
            case 'E': if (CompareStringW(LOCALE_USER_DEFAULT,
                                         NORM_IGNORECASE | SORT_STRINGSORT,
                                         &word[1], 8,
                                         EXCLUDE, -1) == CSTR_EQUAL) {
                        if (XCOPY_ProcessExcludeList(&word[9])) {
                          XCOPY_FailMessage(ERROR_INVALID_PARAMETER);
                          goto out;
                        } else flags |= OPT_EXCLUDELIST;
                      } else flags |= OPT_EMPTYDIR | OPT_RECURSIVE;
                      break;

            /* D can be /D or /D: */
            case 'D': if (word[2]==':' && isdigit(word[3])) {
                          SYSTEMTIME st;
                          WCHAR     *pos = &word[3];
                          BOOL       isError = FALSE;
                          memset(&st, 0x00, sizeof(st));

                          /* Microsoft xcopy's usage message implies that the date
                           * format depends on the locale, but that is false.
                           * It is hardcoded to month-day-year.
                           */
                          st.wMonth = _wtol(pos);
                          while (*pos && isdigit(*pos)) pos++;
                          if (*pos++ != '-') isError = TRUE;

                          if (!isError) {
                              st.wDay = _wtol(pos);
                              while (*pos && isdigit(*pos)) pos++;
                              if (*pos++ != '-') isError = TRUE;
                          }

                          if (!isError) {
                              st.wYear = _wtol(pos);
                              while (*pos && isdigit(*pos)) pos++;
                              if (st.wYear < 100) st.wYear+=2000;
                          }

                          if (!isError && SystemTimeToFileTime(&st, &dateRange)) {
                              SYSTEMTIME st;
                              WCHAR datestring[32], timestring[32];

                              flags |= OPT_DATERANGE;

                              /* Debug info: */
                              FileTimeToSystemTime (&dateRange, &st);
                              GetDateFormatW(0, DATE_SHORTDATE, &st, NULL, datestring,
                                             sizeof(datestring)/sizeof(WCHAR));
                              GetTimeFormatW(0, TIME_NOSECONDS, &st,
                                             NULL, timestring, sizeof(timestring)/sizeof(WCHAR));

                              WINE_TRACE("Date being used is: %s %s\n",
                                         wine_dbgstr_w(datestring), wine_dbgstr_w(timestring));
                          } else {
                              XCOPY_FailMessage(ERROR_INVALID_PARAMETER);
                              goto out;
                          }
                      } else {
                          flags |= OPT_DATENEWER;
                      }
                      break;

            case '-': if (toupper(word[2])=='Y')
                          flags &= ~OPT_NOPROMPT;
                      break;
            case '?': XCOPY_wprintf(XCOPY_LoadMessage(STRING_HELP));
                      rc = RC_HELP;
                      goto out;
            default:
                WINE_TRACE("Unhandled parameter '%s'\n", wine_dbgstr_w(word));
                XCOPY_wprintf(XCOPY_LoadMessage(STRING_INVPARM), word);
                goto out;
            }
        }
        word = next;
    }

    /* Default the destination if not supplied */
    if (supplieddestination[0] == 0x00)
        lstrcpyW(supplieddestination, wchr_dot);

    *pflags = flags;
    rc = RC_OK;

 out:
    free(cmdline);
    return rc;
}
Esempio n. 29
0
int wmain(int argc, WCHAR *argv[])
{

	/* Display welcome message */
	printf("handle_monitor %s - Adam Kramer\n", VERSION_NUMBER);

	/* These variables hold configuration options, which can be altered by arguments passed */
	BOOL bIncludeSigned = FALSE;
	BOOL bSuspendProcess = FALSE;
	BOOL bVerbose = FALSE;
	DWORD dNumberCycles = 10;
	DWORD dHandleChangeThreshold = 10;
	DWORD dIterationPause = 1000;

	/* Process arguments */
	if (argc > 1)
	{
		for (int iNumberArgs = 1; iNumberArgs < argc; iNumberArgs++)
		{
			/* /signed - will include signed files in the alerts */
			if (!wcscmp(argv[iNumberArgs], L"/signed"))
			{
				bIncludeSigned = TRUE;
				printf("Info: Will show signed files as well as unsigned\n");
			}
			/* /suspect - will attempt to suspend suspicious processes */
			else if (!wcscmp(argv[iNumberArgs], L"/suspend"))
			{
				bSuspendProcess = TRUE;
				printf("Info: Will attempt to suspend suspicious processes\n");
			}
			/* /verbose - will display details of iterations and hidden results */
			else if (!wcscmp(argv[iNumberArgs], L"/verbose"))
			{
				bVerbose = TRUE;
				printf("Info: Will display verbose status messages\n");
			}
			/* /cycles - allows the user to set cycles completed before analysis */
			else if (WCHAR* wSetCycles = wcsstr(argv[iNumberArgs], L"/cycles="))
			{
				wSetCycles = wcschr(wSetCycles, '=');

				if (!(dNumberCycles = _wtol(++wSetCycles)))
				{
					printf("Error: Invalid /cycles parameter\n");
					return 1;
				}

				printf("Info: Setting number of cycles to %d\n", dNumberCycles);
			}
			/* /threshold - allows the user to set the threshold for minimum number of new handles which are suspicious */
			else if (WCHAR* wSetThreshold = wcsstr(argv[iNumberArgs], L"/threshold="))
			{
				wSetThreshold = wcschr(wSetThreshold, '=');

				if (!(dHandleChangeThreshold = _wtol(++wSetThreshold)))
				{
					printf("Error: Invalid /threshold parameter\n");
					return 1;
				}

				printf("Info: Setting handle threshold to %d\n", dHandleChangeThreshold);
			}
			/* /pause - allows the user to set a pause between cycles (reduce system load, increase window for finding something) */
			else if (WCHAR* wSetPause = wcsstr(argv[iNumberArgs], L"/pause="))
			{
				wSetPause = wcschr(wSetPause, '=');

				dIterationPause = _wtol(++wSetPause);
				printf("Info: Setting pause between cycles to %dms\n", dIterationPause);
			}
		}
		/* End of argument processing */
	}
	else
	{
		/* No argument passed, accordingly display the usage instructions */
		printf("Usage: handle_monitor.exe <optional parameters>\n\n");
		printf("Optional parameters:\n");
		printf("/cycles=X - Set number of cycles before a review [Default: 10]\n");
		printf("/threshold=X - Set suspicion threshold for number of new handles [Default: 10]\n");
		printf("/pause=X - Set pause in milliseconds between cycles [Default: 1000]\n");
		printf("/signed - Include signed executables in review process\n");
		printf("/suspend - Suspend processes identified as suspicious\n");
		printf("/verbose - Display verbose progress messages\n\n");
		printf("Info: No parameters specified, launching monitoring (Ctrl+C to stop)\n");
	}

	/* Import functions manually from NTDLL */
	_NtQuerySystemInformation NtQuerySystemInformation =
		(_NtQuerySystemInformation)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQuerySystemInformation");

	_NtDuplicateObject NtDuplicateObject =
		(_NtDuplicateObject)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtDuplicateObject");

	_NtQueryObject NtQueryObject =
		(_NtQueryObject)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQueryObject");

	/* Master loop! - This runs forever until a user presses Ctrl+C */
	for (;;)
	{
		/* Update user that process is starting (if /verbose mode activiated) */
		if (bVerbose)
			printf("Verbose Info: Starting sequence\n");

		/* Variables used for retrieving handles */
		NTSTATUS status;
		ULONG handleInfoSize = 0x10000;
		HANDLE processHandle;
		ULONG i;
		PSYSTEM_HANDLE_INFORMATION handleInfo;

		/* Used in each handle iteration to identify the index in iProcessArray of the specific process */
		int iCurrentProcess_ArrayIndex = -1;

		/* Handle array - PROCESS INDEX / HANDLE NUMBER / TEXT OF HANDLE
			This holds all handles which have been found per process */
		auto cHandleArray = new WCHAR[MAX_PROCESSES][MAX_FILE_HANDLES][MAX_PATH]();
		signed int iProcessArray[MAX_PROCESSES][3] = { 0 };

		/* Set process array to -1, which indicates nothing has been set */
		for (int j = 0; j < (MAX_PROCESSES - 1); j++)
			iProcessArray[j][0] = -1;

		/* Loop dNumberCycles [default: 10] times before analysing result */
		for (unsigned int iCycleCounter = 1; iCycleCounter <= dNumberCycles; iCycleCounter++)
		{
			handleInfoSize = 0x10000;
			handleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize);

			/* NtQuerySystemInformation won't give us the correct buffer size, so we guess by doubling the buffer size. */
			while ((status = NtQuerySystemInformation(SystemHandleInformation, handleInfo, handleInfoSize, NULL)) == STATUS_INFO_LENGTH_MISMATCH)
				handleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2);

			/* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */
			if (!NT_SUCCESS(status))
			{
				printf("NtQuerySystemInformation failed!\n");
				return 1;
			}

			/* Loop for each handle on the system, processing it accordingly... */
			for (i = 0; i < handleInfo->HandleCount; i++)
			{
				SYSTEM_HANDLE handle = handleInfo->Handles[i];
				HANDLE dupHandle = NULL;
				POBJECT_TYPE_INFORMATION objectTypeInfo;

				/* Open a handle to the process associated with the handle */
				if (!(processHandle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, handle.ProcessId)))
					continue;

				/* Duplicate the handle so we can query it. */
				if (!NT_SUCCESS(NtDuplicateObject(processHandle, (HANDLE)handle.Handle, GetCurrentProcess(), &dupHandle, GENERIC_READ, 0, 0)))
				{
					CloseHandle(processHandle);
					CloseHandle(dupHandle);
					continue;
				}

				/* Query the object type */
				objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000);
				if (!NT_SUCCESS(NtQueryObject(dupHandle, ObjectTypeInformation, objectTypeInfo, 0x1000, NULL)))
				{
					free(objectTypeInfo);
					CloseHandle(processHandle);
					CloseHandle(dupHandle);
					continue;
				}

				/* If it's not a file handle, go to next one (as we're only interested in file handles) */
				if (wcscmp(objectTypeInfo->Name.Buffer, L"File"))
				{
					free(objectTypeInfo);
					CloseHandle(processHandle);
					CloseHandle(dupHandle);
					continue;
				}

				/* Identify the filename from the handle we're looking at */
				WCHAR* wHandleFileName = new WCHAR[MAX_PATH]();

				if (!GetFileNameFromHandle(dupHandle, wHandleFileName))
				{
					free(objectTypeInfo);
					free(wHandleFileName);
					CloseHandle(processHandle);
					CloseHandle(dupHandle);
					continue;
				}

				/* This is where we add our findings to the database */
				iCurrentProcess_ArrayIndex = -1;

				/* Check whether we've already got an entry for the process we're looking at */
				for (int j = 0; j < (MAX_PROCESSES - 1); j++)
					if (iProcessArray[j][PROCESS_ARRAY_INDEX] == handle.ProcessId)
						iCurrentProcess_ArrayIndex = j;

				/* If not, create a new entry for the process associated with the current handle */
				if (iCurrentProcess_ArrayIndex == -1)
					for (int j = 0; j < (MAX_PROCESSES - 1); j++)
						if (iProcessArray[j][PROCESS_ARRAY_INDEX] == -1)
						{
							iProcessArray[j][PROCESS_ARRAY_INDEX] = handle.ProcessId;
							iCurrentProcess_ArrayIndex = j;
							break;
						}

				/* If there's more than MAX_PROCESSES, throw an error
					TODO: Tidy this up, identify number of running processes dynamically and set array size accordingly */
				if (iCurrentProcess_ArrayIndex == -1)
				{
					printf("Error: Too many processes running!\n");
					return 1;
				}

				/* Look through the handle array, to see whether the filename can be found */
				WCHAR cCurrentHandleText[MAX_PATH];
				for (int j = 0; j < (MAX_FILE_HANDLES - 1); j++)
				{
					/* If we hit NULL, there are no more to find, so add ours */
					swprintf_s(cCurrentHandleText, MAX_PATH, L"%ls", wHandleFileName);

					if (!wcscmp(cHandleArray[iCurrentProcess_ArrayIndex][j], L"")){
						wcscpy_s(cHandleArray[iCurrentProcess_ArrayIndex][j], cCurrentHandleText);
						break;
					}
					/* If we find ours, then stop searching */
					else if (!wcscmp(cHandleArray[iCurrentProcess_ArrayIndex][j], cCurrentHandleText))
						break;
				}

				/* If it's the first (or last) cycle, tally how many entries in the handle array for this
					particular process we have so far */

				if (iCycleCounter == 1)
					for (int j = 0; j < (MAX_FILE_HANDLES - 1); j++)
						if (!wcscmp(cHandleArray[iCurrentProcess_ArrayIndex][j], L"")){
							iProcessArray[iCurrentProcess_ArrayIndex][PROCESS_ARRAY_COUNT_START_CYCLE] = (j - 1);
							break;
						}

				if (iCycleCounter == dNumberCycles)
					for (int j = 0; j < (MAX_FILE_HANDLES - 1); j++)
						if (!wcscmp(cHandleArray[iCurrentProcess_ArrayIndex][j], L"")) {
							iProcessArray[iCurrentProcess_ArrayIndex][PROCESS_ARRAY_COUNT_END_CYCLE] = (j - 1);
							break;
						}

				free(objectTypeInfo);
				free(wHandleFileName);
				CloseHandle(dupHandle);
				CloseHandle(processHandle);
			}
			free(handleInfo);

			/* If the iteration pause is not 0, sleep for the requested time [Default: 1000ms] */
			if (dIterationPause)
				Sleep(dIterationPause);

			/* If /verbose active - inform user which cycle we are on */
			if (bVerbose)
				if (iCycleCounter == 1)
					printf("Verbose Info: Completed cycle %d", iCycleCounter);
				else if (iCycleCounter == dNumberCycles)
					printf(" %d\n", iCycleCounter);
				else
					printf(" %d", iCycleCounter);
		}

		/* If /verbose active - inform user we are now starting a review */
		if (bVerbose)
			printf("Verbose Info: Cycles completed, beginning review\n");

		/* Check if any of them met threshold*/
		for (int j = 0; j < (MAX_PROCESSES - 1); j++)
		{
			if (iProcessArray[j][PROCESS_ARRAY_COUNT_END_CYCLE] < iProcessArray[j][PROCESS_ARRAY_COUNT_START_CYCLE])
				continue;

			/* dHandleDelta is the difference between number of handles for a process from first cycle to the last one  */
			DWORD dHandleDelta = (iProcessArray[j][PROCESS_ARRAY_COUNT_END_CYCLE] - iProcessArray[j][PROCESS_ARRAY_COUNT_START_CYCLE]);

			/* Check whether the delta is equal or above the threshold */
			if (dHandleDelta >= dHandleChangeThreshold)
			{
				HANDLE pHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, iProcessArray[j][PROCESS_ARRAY_INDEX]);
				TCHAR tProcessName[MAX_PATH];
				GetModuleFileNameEx(pHandle, 0, tProcessName, MAX_PATH);
				CloseHandle(pHandle);

				/* If we don't want signed, yet it is signed, skip... */
				if (!bIncludeSigned && (is_signed(tProcessName) == 0))
				{
					if (bVerbose)
						wprintf(L"Verbose Info: Skipping alert on %s (%d) despite trigger, as it is signed (use /signed to alert on signed executables too)\n", tProcessName, iProcessArray[j][PROCESS_ARRAY_INDEX]);
					continue;
				}

				/* Inform the user if we have a suspicious process */
				wprintf(L"Alert! Process: %s (%d) has had a suspicious number of handles (%d) created in the last cycle\nNew handles created during this cycle:\n", tProcessName, iProcessArray[j][PROCESS_ARRAY_INDEX], dHandleDelta);

				for (DWORD k = 1; k <= dHandleDelta; k++)
					wprintf(L"%s\n", cHandleArray[j][iProcessArray[j][PROCESS_ARRAY_COUNT_START_CYCLE] + k]);

				if (bSuspendProcess)
				{

					printf("Info: Attempting to suspend process %d\n", iProcessArray[j][PROCESS_ARRAY_INDEX]);

					/* Attach debugger to process (freeze it!)*/
					if (!DebugActiveProcess(iProcessArray[j][PROCESS_ARRAY_INDEX]))
					{
						printf("Info: Could not attach to process %d as a debugger\n", iProcessArray[j][PROCESS_ARRAY_INDEX]);
					}
					else
					{
						DebugSetProcessKillOnExit(FALSE);

						printf("Info: Successfully attached to process %d as debugger\n", iProcessArray[j][PROCESS_ARRAY_INDEX]);
						printf("Info: It will remain frozen until this process is terminated\n");
					}
				}

				printf("------------------------------------------------------------------------------\n");

			}
		}

		if (bVerbose)
			printf("Verbose Info: Review complete\n");

		free(cHandleArray);

	}

	return 0;
}
Esempio n. 30
0
/**
* ReadLocalDirectory
*
* Description: Read files folders from directory.
*
* Param: con - describes connection information
*        dir - path. 
*		 files - output list
*
* Return: bool - true. False if file does not exist, has not been read.
*/
bool CFtpManager::ReadLocalDirectory(CConnection * con, CString &dir, std::vector<CFileContainer> &files)
{
	bool result = true;
	if(con->host.GetLength() == 0)
	{
		return false;
	}

	if(dir.GetAt( dir.GetLength() - 1 ) != '/')
	{
		dir = dir + CString(_T("/"));
	}

	CString localStorePath;
	GetLocalStorePath(con, localStorePath);

	// Read files and folders in directory.
	localStorePath = localStorePath + CString(dir);
	localStorePath.Replace('/', '\\');
	CString localStoreSearchPath = CString(localStorePath + CString(_T("*.*")));
	/*
	CFileFind finder; 
	BOOL bWorking = finder.FindFile(localStoreSearchPath);
	while (bWorking)
	{
		bWorking = finder.FindNextFile();
		if(finder.IsDirectory())
		{
			CFileContainer f;
			f.dir = 1;
			f.name = finder.GetFileName(); //  .GetFileTitle();
			f.path = CString(dir); //finder.GetFilePath();
			f.localPath = CString(localStorePath);
			if(f.name.Trim().Compare(_T(".")) != 0 && f.name.Trim().Compare(_T("..")) != 0){
				//files.push_back(f);
			}
		} 
		// else sync local file
	}
	finder.Close();
	*/

	// Read file 
	CString dirContentFile(localStorePath + _T(".files.rftp"));

	//char nameBuffer[100];
	//sprintf(nameBuffer, "%S", dirContentFile); // CString to char *
	
	CFileStatus status;
	if(CFile::GetStatus(dirContentFile, status))
	{
		CStdioFile file (dirContentFile, CStdioFile::modeRead | CFile::shareDenyNone);
		CString buffer;
		//CString string;
		while (file.ReadString(buffer))
		{
			CXml xml;

			CString type(_T(""));
			xml.GetTag(buffer, CString(_T("t")), type);
			bool isDir = false;
			if(type.Compare(_T("d")) == 0){
				isDir = true;
			}
			

			CString fileName(_T(""));
			xml.GetTag(buffer, CString(_T("n")), fileName);

			
			// size
			long size = 0;
			CString fileSize(_T(""));
			if(xml.GetTag(buffer, CString(_T("s")), fileSize)){
				fileSize = fileSize.Trim();
				if(fileSize.GetLength() > 0){
					size = _wtol(fileSize);
				}
			}

			// Date
			CString fileDate(_T(""));
			xml.GetTag(buffer, CString(_T("d")), fileDate);	
			fileDate = fileDate.Trim();
			

			// permissions
			CString filePermissions(_T(""));
			xml.GetTag(buffer, CString(_T("p")), filePermissions);	
			filePermissions = filePermissions.Trim();

			//TRACE1(" line: %s \n", buffer);
			CFileContainer f;
			if(isDir){
				f.dir = 1;
			} else {
				f.dir = 0;
			}
			f.name = fileName; 
			f.path = CString(dir); 
			f.localPath = CString(localStorePath);
			f.size = size;
			f.remoteDate = CString(fileDate);
			f.host = CString(con->host);
			//TRACE1("filePermissions %s \n " , filePermissions);
			f.permissions = CString(filePermissions);
			
			if(f.name.Trim().Compare(_T(".")) != 0 && f.name.Trim().Compare(_T("..")) != 0 ){
				int i = 0;
				files.push_back(f);
			}
		}
	} 
	else 
	{
		// Directory not read.
		//GetFtpDirectory(con, dir, NULL);
		TRACE1(" ReadLocalDirectory not found: %s \n", dir);
		result = false;
	}
	return result;
}