//-----------------------------------------------------------------------------
static void load_paths_to_exclude(LPCTSTR path) {
//-----------------------------------------------------------------------------
    FILE * stream_p;
    wchar_t *get_result;
    size_t line_len;
    struct exclude_entry **link_p;
    struct exclude_entry * next_p;

    if (_wfopen_s(&stream_p, path, L"r, ccs=UTF-8")) {
        _wfopen_s(&error_file, error_path, L"w");
        _wcserror_s(error_buffer, sizeof error_buffer/sizeof(wchar_t), errno); 
        fwprintf(
            error_file, 
            L"_wfopen(%s) failed: (%d) %s\n",  
            path,
            errno,
            error_buffer 
        );
        fclose(error_file);
        ExitProcess(2);
    }

    link_p = &exclude_entry_list_p;
   
    while (1) {

        // create an exclude entry
        next_p = (struct exclude_entry *) HeapAlloc(
            GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct exclude_entry)
        );
		if (next_p == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(203);
			}
        // read in the path to watch from config.txt
        get_result = \
            fgetws(full_file_name, ARRAYSIZE(full_file_name), stream_p);

        if (NULL == get_result) {
            if (0 == ferror(stream_p)) {
                HeapFree(GetProcessHeap(), 0, next_p);
                break;
            } 
            _wfopen_s(&error_file, error_path, L"w");
            _wcserror_s(
               error_buffer, sizeof error_buffer/sizeof(wchar_t) , errno
            ); 
            fwprintf(
                error_file, 
                L"fgetws(%s) failed: (%d) %s\n",  
                path,
                errno,
                error_buffer 
            );
            fclose(error_file);
            ExitProcess(2);
        }

        // clean out the newline, if there is one
        line_len = wcslen(full_file_name);
		if (line_len && full_file_name[line_len-1] == L'\n'){
			full_file_name[line_len-1] = L'\0';
			line_len--;
			}
        if (full_file_name[0] == L'\0')
           continue;
		next_p->dir_path_len = line_len;
		next_p->dir_path = (wchar_t *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			(line_len + 1) * sizeof(wchar_t));
		if (next_p->dir_path == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(204);
		}
		wcsncpy_s(next_p->dir_path, line_len+1, full_file_name, line_len);
   
        // add this entry to the list
        *link_p = next_p;

        // point to the new entry's next pointer 
        link_p = &(*link_p)->next_p;
    } // while(1)

    fclose(stream_p);

} // load_paths_to_exclude
HRESULT CContextPlugin::WriteContextInformation( HANDLE hFile, IWMSContext *pContext )
{
    HRESULT hr = S_OK;
    ContextNameHint *pContextHintValues = NULL;
    DWORD nValue = 0;
    WMS_CONTEXT_TYPE wmsContextType = WMS_UNKNOWN_CONTEXT_TYPE;
    WCHAR wstrBuffer[MAX_PATH];
    DWORD cbWritten = 0;
    DWORD dwRet = 0;


    if( NULL == pContext )
    {
        // There is no Context, nothing to write
        return( hr );
    }

    hr = pContext->GetContextType( &wmsContextType );

    if( FAILED( hr ) )
    {
        return( hr );
    }

    ZeroMemory( wstrBuffer, MAX_PATH * sizeof( WCHAR ) );

    switch( wmsContextType )
    {
        case WMS_USER_CONTEXT_TYPE:
            // Create a header for this context type
            wcsncpy_s( wstrBuffer,MAX_PATH, CONTEXT_SAMPLE_USER_CONTEXT_HEADER, MAX_PATH );
            pContextHintValues = const_cast<ContextNameHint *>(CContextPlugin::s_UserContextHintValues);
            break;
        case WMS_PRESENTATION_CONTEXT_TYPE:
            // Create a header for this context type
            wcsncpy_s( wstrBuffer, MAX_PATH,CONTEXT_SAMPLE_PRESENTATION_CONTEXT_HEADER, MAX_PATH );
            pContextHintValues = const_cast<ContextNameHint *>(CContextPlugin::s_PresentationContextHintValues);
            break;
        case WMS_COMMAND_REQUEST_CONTEXT_TYPE:
            // Create a header for this context type
            wcsncpy_s( wstrBuffer,MAX_PATH, CONTEXT_SAMPLE_COMMAND_REQUEST_CONTEXT_HEADER, MAX_PATH );
            pContextHintValues = const_cast<ContextNameHint *>(CContextPlugin::s_CommandContextHintValues);
            break;
        case WMS_COMMAND_RESPONSE_CONTEXT_TYPE:
            // Create a header for this context type
            wcsncpy_s( wstrBuffer,MAX_PATH, CONTEXT_SAMPLE_COMMAND_RESPONSE_CONTEXT_HEADER, MAX_PATH );
            pContextHintValues = const_cast<ContextNameHint *>(CContextPlugin::s_CommandContextHintValues);
            break;
    }

    if( !::WriteFile( hFile, (LPVOID) wstrBuffer, DWORD(wcslen( wstrBuffer ) * sizeof( WCHAR )), &cbWritten, NULL ) )
    {
        dwRet = GetLastError();
        hr = HRESULT_FROM_WIN32( dwRet );
        // Failed to write the header should we still continue
        // No!
        return( hr );
    }

    if( NULL == pContextHintValues )
    {
        return( E_UNEXPECTED );
    }

    // Now we loop until -1 and Write the data
    while( ( NULL != pContextHintValues[nValue].wstrContextName ) && ( -1 != pContextHintValues[nValue].lContextHint ) )
    {
        VARIANT varValue;
        VariantInit( &varValue );
        ZeroMemory( wstrBuffer, MAX_PATH * sizeof( WCHAR ) );

        hr = pContext->GetValue( pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, &varValue, 0 );

        if( SUCCEEDED( hr ) )
        {
            // Write string with data information
            switch( V_VT( &varValue ) )
            {
                case VT_BSTR:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_BSTR_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_BSTR( &varValue ) );
                    break;
                case VT_I4:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_I4_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_I4( &varValue ), V_I4( &varValue ) );
                    break;
                case VT_UI8:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_UI8_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_UI8( &varValue ) );
                    break;
                case VT_CY:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_CY_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_CY( &varValue ) );
                    break;
                case VT_DATE:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_DATE_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_DATE( &varValue ) );
                    break;
                case VT_DECIMAL:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_DECIMAL_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_DECIMAL( &varValue ) );
                    break;
                case VT_UNKNOWN:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_UNKNOWN_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_UNKNOWN( &varValue ) );
                    break;
                case VT_DISPATCH:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_DISPATCH_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_DISPATCH( &varValue ) );
                    break;
                default:
                    _snwprintf_s( wstrBuffer,MAX_PATH, MAX_PATH, CONTEXT_SAMPLE_ARRAY_TYPE_STRING, pContextHintValues[nValue].wstrContextName, pContextHintValues[nValue].lContextHint, V_ARRAY( &varValue ) );
                    break;
            }

            if( !::WriteFile( hFile, (LPVOID) wstrBuffer, DWORD(wcslen( wstrBuffer ) * sizeof( WCHAR )), &cbWritten, NULL ) )
            {
                dwRet = GetLastError();
                hr = HRESULT_FROM_WIN32( dwRet );
            }
        }
        else
        {
            // Value probably didn't exist for this event, don't worry about it
            // good place to put breakpoint
            hr = S_OK;
        }

        // It doesn't hurt to do a VariantClear on an Empty Variant, this way we won't leak anything.
        VariantClear( &varValue );

        nValue ++;
    }

    return( hr );
}
Beispiel #3
0
void CShellUpdater::UpdateShell()
{
	// Tell the shell extension to purge its cache
	CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Setting cache invalidation event %I64u\n", GetTickCount64());
	SetEvent(m_hInvalidationEvent);

	// We use the SVN 'notify' call-back to add items to the list
	// Because this might call-back more than once per file (for example, when committing)
	// it's possible that there may be duplicates in the list.
	// There's no point asking the shell to do more than it has to, so we remove the duplicates before
	// passing the list on
	m_pathsForUpdating.RemoveDuplicates();

	// if we use the external cache, we tell the cache directly that something
	// has changed, without the detour via the shell.
	CAutoFile hPipe = CreateFile(
		GetCacheCommandPipeName(),		// pipe name
		GENERIC_READ |					// read and write access
		GENERIC_WRITE,
		0,								// no sharing
		nullptr,						// default security attributes
		OPEN_EXISTING,					// opens existing pipe
		FILE_FLAG_OVERLAPPED,			// default attributes
		nullptr);						// no template file


	if (!hPipe)
		return;

	// The pipe connected; change to message-read mode.
	DWORD dwMode = PIPE_READMODE_MESSAGE;
	if (!SetNamedPipeHandleState(
			hPipe,    // pipe handle
			&dwMode,  // new pipe mode
			nullptr,  // don't set maximum bytes
			nullptr)) // don't set maximum time
	{
		CTraceToOutputDebugString::Instance()(__FUNCTION__ ": SetNamedPipeHandleState failed");
		return;
	}

	CTGitPath path;
	for (int nPath = 0; nPath < m_pathsForUpdating.GetCount(); ++nPath)
	{
		path.SetFromWin(g_Git.CombinePath(m_pathsForUpdating[nPath]));
		CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Cache Item Update for %s (%I64u)\n", (LPCTSTR)path.GetWinPathString(), GetTickCount64());
		if (!path.IsDirectory())
		{
			// send notifications to the shell for changed files - folders are updated by the cache itself.
			SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, path.GetWinPath(), nullptr);
		}
		DWORD cbWritten;
		TGITCacheCommand cmd;
		cmd.command = TGITCACHECOMMAND_CRAWL;
		wcsncpy_s(cmd.path, path.GetDirectory().GetWinPath(), _countof(cmd.path) - 1);
		BOOL fSuccess = WriteFile(
			hPipe,			// handle to pipe
			&cmd,			// buffer to write from
			sizeof(cmd),	// number of bytes to write
			&cbWritten,		// number of bytes written
			nullptr);		// not overlapped I/O

		if (!fSuccess || sizeof(cmd) != cbWritten)
		{
			DisconnectNamedPipe(hPipe);
			return;
		}
	}

	// now tell the cache we don't need it's command thread anymore
	DWORD cbWritten;
	TGITCacheCommand cmd;
	cmd.command = TGITCACHECOMMAND_END;
	WriteFile(
		hPipe,			// handle to pipe
		&cmd,			// buffer to write from
		sizeof(cmd),	// number of bytes to write
		&cbWritten,		// number of bytes written
		nullptr);		// not overlapped I/O
	DisconnectNamedPipe(hPipe);
}
Beispiel #4
0
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	Description :
//		Sends WMI command to target after logging on.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
DWORD startWMICommand(char* command, char* target, char* username, char* password)
{	
	HRESULT hres;
	IWbemLocator *pLoc = NULL;
	IWbemServices *pSvc = NULL;
	COAUTHIDENTITY *userAcct =  NULL ;
	COAUTHIDENTITY authIdent;
	char* serverWMIA;
	PWCHAR serverWMIW;
	PWCHAR usernameW;
	PWCHAR commandW;
	PWCHAR passwordW;
	WCHAR pszDomain[CREDUI_MAX_USERNAME_LENGTH+1];
	WCHAR pszUserName[CREDUI_MAX_USERNAME_LENGTH+1];
	PWCHAR slash;
	int len = 0;

	// WCHAR
	len = strlen(target)+12;
	serverWMIA = (char*)malloc(sizeof(char)*(len));
	strcpy_s(serverWMIA, len, target);
	strcat_s(serverWMIA, len, "\\ROOT\\CIMV2");
	len = MultiByteToWideChar(CP_ACP,0,serverWMIA,-1,NULL,0);
	serverWMIW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,serverWMIA,-1,serverWMIW,len);
	free(serverWMIA);
	len = MultiByteToWideChar(CP_ACP,0,username,-1,NULL,0);
	usernameW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,username,-1,usernameW,len);
	len = MultiByteToWideChar(CP_ACP,0,password,-1,NULL,0);
	passwordW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,password,-1,passwordW,len);
	len = MultiByteToWideChar(CP_ACP,0,command,-1,NULL,0);
	commandW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,command,-1,commandW,len);

	hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		return -1;
	}
	hres =  CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_DEFAULT,RPC_C_IMP_LEVEL_IDENTIFY,NULL,EOAC_NONE,NULL);	   
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		CoUninitialize();
		return -1;
	}
	hres = CoCreateInstance(CLSID_WbemLocator,0,CLSCTX_INPROC_SERVER,IID_IWbemLocator, (LPVOID *) &pLoc);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		CoUninitialize();
		return -1;
	}

	//WMI connection
	hres = pLoc->ConnectServer(_bstr_t(serverWMIW),_bstr_t(usernameW),_bstr_t(passwordW),NULL,NULL,NULL,NULL,&pSvc);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}

	//Set ProxyBlanket options
	memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
	authIdent.PasswordLength = wcslen (passwordW);
	authIdent.Password = (USHORT*)passwordW;
	slash = wcschr (usernameW, L'\\');
	if(slash == NULL)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}
	wcscpy_s(pszUserName,CREDUI_MAX_USERNAME_LENGTH+1, slash+1);
	authIdent.User = (USHORT*)pszUserName;
	authIdent.UserLength = wcslen(pszUserName);
	wcsncpy_s(pszDomain, CREDUI_MAX_USERNAME_LENGTH+1, usernameW, slash - usernameW);
	authIdent.Domain = (USHORT*)pszDomain;
	authIdent.DomainLength = slash - usernameW;
	authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
	userAcct = &authIdent;
	
	//Set the ProxyBlanket
	hres = CoSetProxyBlanket(pSvc,RPC_C_AUTHN_DEFAULT,RPC_C_AUTHZ_DEFAULT,COLE_DEFAULT_PRINCIPAL,RPC_C_AUTHN_LEVEL_PKT_PRIVACY,RPC_C_IMP_LEVEL_IMPERSONATE,userAcct,EOAC_NONE);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}


	BSTR MethodName = SysAllocString(L"Create");
	BSTR ClassName = SysAllocString(L"Win32_Process");

	IWbemClassObject* pClass = NULL;
	hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);
	IWbemClassObject* pInParamsDefinition = NULL;
	hres = pClass->GetMethod(MethodName, 0, 
		&pInParamsDefinition, NULL);
	IWbemClassObject* pClassInstance = NULL;
	hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);

	// Create the values for the "in" parameters
	VARIANT varCommand;
	varCommand.vt = VT_BSTR;
	varCommand.bstrVal = BSTR(commandW);

	// Store the value for the "in" parameters
	hres = pClassInstance->Put(L"CommandLine", 0, &varCommand, 0);

	 // Execute Method
	IWbemClassObject* pOutParams = NULL;
	hres = pSvc->ExecMethod(ClassName, MethodName, 0,
	NULL, pClassInstance, &pOutParams, NULL);

	if (FAILED(hres))
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		VariantClear(&varCommand);
		SysFreeString(ClassName);
		SysFreeString(MethodName);
		pClass->Release();
		pInParamsDefinition->Release();
		pOutParams->Release();
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}


	free(usernameW);
	free(passwordW);
	free(commandW);
	free(serverWMIA);
	free(serverWMIW);
	SecureZeroMemory(pszUserName, sizeof(pszUserName));
	SecureZeroMemory(pszDomain, sizeof(pszDomain));
	VariantClear(&varCommand);
	SysFreeString(ClassName);
	SysFreeString(MethodName);
	pClass->Release();
	pInParamsDefinition->Release();
	pOutParams->Release();
	pSvc->Release();
	pLoc->Release();
	CoUninitialize();

	return 0;
}
Callstack::AddressDetails Win32CallstackResolver::GetAddr(DWORD64 addr)
{
  AddrInfo info;

  info.lineNum = 0;
  memset(info.fileName, 0, sizeof(info.fileName));
  memset(info.fileName, 0, sizeof(info.funcName));

  wcsncpy_s(info.fileName, L"Unknown", 126);
  wsprintfW(info.funcName, L"0x%08I64x", addr);

  for(size_t i = 0; i < modules.size(); i++)
  {
    DWORD64 base = modules[i].base;
    DWORD size = modules[i].size;
    if(addr > base && addr < base + size)
    {
      if(modules[i].moduleId != 0)
        info = DIA2::GetAddr(modules[i].moduleId, addr);

      // if we didn't get a filename, default to the module name
      if(modules[i].moduleId == 0 || info.fileName[0] == 0)
        wcsncpy_s(info.fileName, modules[i].name.c_str(), 126);

      if(modules[i].moduleId == 0 || info.funcName[0] == 0)
      {
        // if we didn't get a function name, at least indicate
        // the module it came from, and an offset
        wchar_t *baseName = info.fileName;

        wchar_t *c = wcsrchr(baseName, '\\');
        if(c)
          baseName = c + 1;

        c = wcsrchr(baseName, '/');
        if(c)
          baseName = c + 1;

        wsprintfW(info.funcName, L"%s+0x%08I64x", baseName, addr - base);

        c = wcsstr(info.funcName, L"pdb");
        if(c)
        {
          if(i == 0)
          {
            c[0] = 'e';
            c[1] = 'x';
            c[2] = 'e';
          }
          else
          {
            c[0] = 'd';
            c[1] = 'l';
            c[2] = 'l';
          }
        }
      }

      break;
    }
  }

  Callstack::AddressDetails ret;
  ret.filename = StringFormat::Wide2UTF8(wstring(info.fileName));
  ret.function = StringFormat::Wide2UTF8(wstring(info.funcName));
  ret.line = info.lineNum;

  return ret;
}
Beispiel #6
0
BOOL CALLBACK ImageHandler::MonitorEnumProcWin8(HMONITOR hMonitor, HDC /*hdcMonitor*/, LPRECT lprcMonitor, LPARAM lpData)
{
  MONITORINFOEX miex;
  miex.cbSize = sizeof(miex);
  ::GetMonitorInfo(hMonitor, &miex);

  DISPLAY_DEVICE dd;
  dd.cb = sizeof(dd);
  ::EnumDisplayDevices(miex.szDevice, 0, &dd, EDD_GET_DEVICE_INTERFACE_NAME);

#if 0
  TRACE(L"name %s String %s DeviceID %s Key %s StateFlags %lu\n",
    dd.DeviceName,
    dd.DeviceString,
    dd.DeviceID,
    dd.DeviceKey,
    dd.StateFlags);
#endif

  wchar_t szTranscodedImage [_MAX_PATH] = L"";

  TRACE(
    L"searching for %s ('%s') ...\n",
    miex.szDevice,
    dd.DeviceID);

  try
  {
    DWORD dwTranscodedImageCount = 0;
    DWORD dwType;
    DWORD dwValueSize;
    LSTATUS rc;

    HKEY hkey;
    rc = ::RegOpenKeyEx(
      HKEY_CURRENT_USER,
      L"Control Panel\\Desktop",
      0,
      KEY_READ,
      &hkey);

    if( rc != ERROR_SUCCESS )
      Win32Exception::Throw("RegOpenKeyEx", rc);

    unique_ptr<HKEY__, RegCloseKeyHelper>hkeyPtr(hkey);

    rc = ::RegQueryValueEx(
      hkeyPtr.get(),
      L"TranscodedImageCount",
      nullptr,
      &dwType,
      reinterpret_cast<LPBYTE>(&dwTranscodedImageCount),
      &(dwValueSize = static_cast<DWORD>(sizeof(dwTranscodedImageCount))));

    if( rc != ERROR_SUCCESS )
      Win32Exception::Throw("RegQueryValueEx", rc);

    for(DWORD i = 0; i < dwTranscodedImageCount; ++i)
    {
      wchar_t szValueName [32];
      _snwprintf_s(
        szValueName, ARRAYSIZE(szValueName),
        _TRUNCATE,
        L"TranscodedImageCache_%03lu",
        i);

      BYTE binTranscodedImageCache [0x320];
      rc = ::RegQueryValueEx(
        hkeyPtr.get(),
        szValueName,
        nullptr,
        &dwType,
        binTranscodedImageCache,
        &(dwValueSize = static_cast<DWORD>(sizeof(binTranscodedImageCache))));

      if( rc != ERROR_SUCCESS )
        Win32Exception::Throw("RegQueryValueEx", rc);

      TRACE(
        L"\twallpaper picture on ('%s') is '%s'\n",
        reinterpret_cast<wchar_t*>(binTranscodedImageCache + 0x220),
        reinterpret_cast<wchar_t*>(binTranscodedImageCache + 0x18));

      wchar_t* szDeviceID1 = dd.DeviceID;
      wchar_t* szDeviceID2 = reinterpret_cast<wchar_t*>(binTranscodedImageCache + 0x220);

      // when monitor device id is "Default_Monitor"
      // \\?\DISPLAY#Default_Monitor#...
      // there is no device id in TranscodedImageCache_xxx file

      if( ( *szDeviceID2 == 0 && 
            wcsncmp(szDeviceID1, L"\\\\?\\DISPLAY#Default_Monitor#", 28) == 0 ) ||
          wcsncmp(szDeviceID1, szDeviceID2, 128) == 0 )
      {
        wcsncpy_s(
          szTranscodedImage, _MAX_PATH,
          reinterpret_cast<wchar_t*>(binTranscodedImageCache + 0x18),
          _TRUNCATE);

        break;
      }
    }
  }
  catch(Win32Exception&)
  {
  }

  MonitorEnumData* pEnumData = reinterpret_cast<MonitorEnumData*>(lpData);

  std::shared_ptr<BackgroundImage> bkImage;

  if( szTranscodedImage[0] )
  {
    TRACE(
      L"wallpaper picture on %s ('%s') is '%s'\n",
      miex.szDevice,
      dd.DeviceID,
      szTranscodedImage);

    bkImage.reset(new BackgroundImage (pEnumData->bkImage->imageData));
    bkImage->imageData.strFilename = szTranscodedImage;
    bkImage->bWallpaper = true;
    ImageHandler::LoadImageW(bkImage);
  }
  else
  {
    bkImage = pEnumData->bkImage;
  }

  CRect   rectMonitor(lprcMonitor);

  // create template image
  CDC     dcTemplate;
  CBitmap	bmpTemplate;
  dcTemplate.CreateCompatibleDC(NULL);

  DWORD dwNewWidth  = rectMonitor.Width();
  DWORD dwNewHeight = rectMonitor.Height();
  ImageHandler::PaintRelativeImage(pEnumData->dcTemplate, bmpTemplate, bkImage, dwNewWidth, dwNewHeight);

  dcTemplate.SelectBitmap(bmpTemplate);

  ImageHandler::PaintTemplateImage(
    dcTemplate, 
    rectMonitor.left - ::GetSystemMetrics(SM_XVIRTUALSCREEN), 
    rectMonitor.top  - ::GetSystemMetrics(SM_YVIRTUALSCREEN), 
    dwNewWidth,
    dwNewHeight,
    rectMonitor.Width(), 
    rectMonitor.Height(), 
    pEnumData->bkImage);

  return TRUE;
}
bool SendCacheCommand(BYTE command, const WCHAR * path /* = NULL */)
{
    int retrycount = 2;
    CAutoFile hPipe;
    do
    {
        hPipe = CreateFile(
            GetCacheCommandPipeName(),      // pipe name
            GENERIC_READ |                  // read and write access
            GENERIC_WRITE,
            0,                              // no sharing
            NULL,                           // default security attributes
            OPEN_EXISTING,                  // opens existing pipe
            FILE_FLAG_OVERLAPPED,           // default attributes
            NULL);                          // no template file
        retrycount--;
        if (!hPipe)
            Sleep(10);
    } while ((!hPipe) && (retrycount));

    if (!hPipe)
    {
        CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Could not connect to pipe\n");
        return false;
    }

    // The pipe connected; change to message-read mode.
    DWORD dwMode = PIPE_READMODE_MESSAGE;
    if (SetNamedPipeHandleState(
        hPipe,    // pipe handle
        &dwMode,  // new pipe mode
        NULL,     // don't set maximum bytes
        NULL))    // don't set maximum time
    {
        DWORD cbWritten;
        TSVNCacheCommand cmd;
        SecureZeroMemory(&cmd, sizeof(TSVNCacheCommand));
        cmd.command = command;
        if (path)
            wcsncpy_s(cmd.path, path, _TRUNCATE);

        retrycount = 2;
        BOOL fSuccess = FALSE;
        do
        {
            fSuccess = WriteFile(
                hPipe,          // handle to pipe
                &cmd,           // buffer to write from
                sizeof(cmd),    // number of bytes to write
                &cbWritten,     // number of bytes written
                NULL);          // not overlapped I/O
            retrycount--;
            if (! fSuccess || sizeof(cmd) != cbWritten)
                Sleep(10);
        } while ((retrycount) && (! fSuccess || sizeof(cmd) != cbWritten));

        if (! fSuccess || sizeof(cmd) != cbWritten)
        {
            CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Could not write to pipe\n");
            DisconnectNamedPipe(hPipe);
            return false;
        }
        // now tell the cache we don't need it's command thread anymore
        SecureZeroMemory(&cmd, sizeof(TSVNCacheCommand));
        cmd.command = TSVNCACHECOMMAND_END;
        WriteFile(
            hPipe,          // handle to pipe
            &cmd,           // buffer to write from
            sizeof(cmd),    // number of bytes to write
            &cbWritten,     // number of bytes written
            NULL);          // not overlapped I/O
        DisconnectNamedPipe(hPipe);
    }
    else
    {
        CTraceToOutputDebugString::Instance()(__FUNCTION__ ": SetNamedPipeHandleState failed");
        return false;
    }

    return true;
}
Beispiel #8
0
BOOL CDDStatic::OnRenderGlobalData(LPFORMATETC lpFormatEtc, HGLOBAL* phGlobal)
{
  pws_os::Trace(L"CDDStatic::OnRenderGlobalData: %s; ci == %p\n",
          lpFormatEtc->cfFormat == CF_UNICODETEXT ? L"CF_UNICODETEXT" : L"CF_TEXT",
          m_pci);

  if (lpFormatEtc->cfFormat != CF_UNICODETEXT &&
      lpFormatEtc->cfFormat != CF_TEXT)
    return FALSE;

  if (m_hgDataTXT != NULL) {
    pws_os::Trace(L"CDDStatic::OnRenderGlobalData - Unlock/Free m_hgDataTXT\n");
    GlobalUnlock(m_hgDataTXT);
    GlobalFree(m_hgDataTXT);
    m_hgDataTXT = NULL;
  }

  if (m_hgDataUTXT != NULL) {
    pws_os::Trace(L"CDDStatic::OnRenderGlobalData - Unlock/Free m_hgDataUTXT\n");
    GlobalUnlock(m_hgDataUTXT);
    GlobalFree(m_hgDataUTXT);
    m_hgDataUTXT = NULL;
  }

  StringX cs_dragdata;
  if (m_pci == NULL) {
    if (m_groupname.empty()) {
      pws_os::Trace(L"CDDStatic::OnRenderGlobalData - mpci == NULL\n");
      return FALSE;
    } else {
      cs_dragdata = m_groupname;
    }
  } else { // m_pci != NULL
    const CItemData *pci(m_pci);

    // Handle shortcut or alias
    if ((m_nID == IDC_STATIC_DRAGPASSWORD && pci->IsAlias()) ||
        (pci->IsShortcut() && (m_nID != IDC_STATIC_DRAGGROUP &&
                               m_nID != IDC_STATIC_DRAGTITLE &&
                               m_nID != IDC_STATIC_DRAGUSER))) {
      pci = app.GetMainDlg()->GetBaseEntry(pci);
    }
    cs_dragdata = GetData(pci);
    if (cs_dragdata.empty() && m_nID != IDC_STATIC_DRAGAUTO)
      return FALSE;
  }

  const size_t ilen = cs_dragdata.length();
  if (ilen == 0 && m_nID != IDC_STATIC_DRAGAUTO) {
    // Nothing to do - why were we even called???
    return FALSE;
  }

  DWORD dwBufLen;
  LPSTR lpszA(NULL);
  LPWSTR lpszW(NULL);

  if (lpFormatEtc->cfFormat == CF_UNICODETEXT) {
    // So is requested data!
    dwBufLen = (DWORD)((ilen + 1) * sizeof(wchar_t));
    lpszW = new WCHAR[ilen + 1];
    //pws_os::Trace(L"lpszW allocated %p, size %d\n", lpszW, dwBufLen);
    if (ilen == 0) {
      lpszW[ilen] = L'\0';
    } else {
      (void) wcsncpy_s(lpszW, ilen + 1, cs_dragdata.c_str(), ilen);
    }
  } else {
    // They want it in ASCII - use lpszW temporarily
    if (ilen == 0) {
      dwBufLen = 1;
      lpszA = new char[dwBufLen];
      lpszA = '\0';
    } else {
      lpszW = const_cast<LPWSTR>(cs_dragdata.c_str());
      dwBufLen = WideCharToMultiByte(CP_ACP, 0, lpszW, -1, NULL, 0, NULL, NULL);
      ASSERT(dwBufLen != 0);
      lpszA = new char[dwBufLen];
      pws_os::Trace(L"lpszA allocated %p, size %d\n", lpszA, dwBufLen);
      WideCharToMultiByte(CP_ACP, 0, lpszW, -1, lpszA, dwBufLen, NULL, NULL);
      lpszW = NULL;
    }
  }

  LPVOID lpData(NULL);
  LPVOID lpDataBuffer;
  HGLOBAL *phgData;
  if (lpFormatEtc->cfFormat == CF_UNICODETEXT) {
    lpDataBuffer = (LPVOID)lpszW;
    phgData = &m_hgDataUTXT;
  } else {
    lpDataBuffer = (LPVOID)lpszA;
    phgData = &m_hgDataTXT;
  }

  BOOL retval(FALSE);
  if (*phGlobal == NULL) {
    //pws_os::Trace(L"CDDStatic::OnRenderGlobalData - Alloc global memory\n");
    *phgData = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, dwBufLen);
    ASSERT(*phgData != NULL);
    if (*phgData == NULL)
      goto bad_return;

    lpData = GlobalLock(*phgData);
    ASSERT(lpData != NULL);
    if (lpData == NULL)
      goto bad_return;

    // Copy data
    memcpy(lpData, lpDataBuffer, dwBufLen);
    *phGlobal = *phgData;
    retval = TRUE;
  } else {
    pws_os::Trace(L"CDDStatic::OnRenderGlobalData - *phGlobal NOT NULL!\n");
    SIZE_T inSize = GlobalSize(*phGlobal);
    SIZE_T ourSize = GlobalSize(*phgData);
    if (inSize < ourSize) {
      // Pre-allocated space too small.  Not allowed to increase it - FAIL
      pws_os::Trace(L"CDDStatic::OnRenderGlobalData - NOT enough room - FAIL\n");
    } else {
      // Enough room - copy our data into supplied area
      pws_os::Trace(L"CDDStatic::OnRenderGlobalData - enough room - copy our data\n");
      LPVOID pInGlobalLock = GlobalLock(*phGlobal);
      ASSERT(pInGlobalLock != NULL);
      if (pInGlobalLock == NULL)
        goto bad_return;

      memcpy(pInGlobalLock, lpDataBuffer, ourSize);
      GlobalUnlock(*phGlobal);
      retval = TRUE;
    }
  }

bad_return:
  // Finished with buffer - trash it
  trashMemory(lpDataBuffer, dwBufLen);
  // Free the strings (only one is actually in use)
  //pws_os::Trace(L"lpszA freed %p\n", lpszA);
  delete[] lpszA;
  //pws_os::Trace(L"lpszW freed %p\n", lpszW);
  delete[] lpszW;
  // Since lpDataBuffer pointed to one of the above - just zero the pointer
  lpDataBuffer = NULL;

  // If retval == TRUE, recipient is responsible for freeing the global memory
  // if D&D succeeds (see after StartDragging in OnMouseMove)
  if (retval == FALSE) {
    pws_os::Trace(L"CDDStatic::OnRenderGlobalData - returning FALSE!\n");
    if (lpData != NULL) {
      GlobalFree(*phgData);
      *phgData = NULL;
    }
  } else {
    pws_os::Trace(L"CDDStatic::OnRenderGlobalData - D&D Data:");
    if (lpFormatEtc->cfFormat == CF_UNICODETEXT) {
      pws_os::Trace(L"\"%ls\"\n", (LPWSTR)lpData);  // data is Unicode
    } else {
      pws_os::Trace(L"\"%hs\"\n", (LPSTR)lpData);  // data is NOT Unicode
    }
  }
  // Unlock our buffer
  if (lpData != NULL)
    GlobalUnlock(*phgData);

  return retval;
}
BOOL SetOwner(LPCTSTR filename, LPCTSTR newOwner)
{
  PSID sid = nullptr;
  BOOL res = TRUE;
  PACL pacl = nullptr;

  // get the SID for the new owner
  TCHAR domainUnused[4096];
  DWORD sidSize = 0;
  DWORD domainBufSize = 4096;
  SID_NAME_USE sidUse;
  // pre-flight to determine required size of the sid
  LookupAccountName(nullptr, newOwner, nullptr, &sidSize, domainUnused, &domainBufSize, &sidUse);
  sid = (PSID)malloc(sidSize);
  // determine sid for account name
  if (!LookupAccountName(nullptr, newOwner, sid, &sidSize, domainUnused, &domainBufSize, &sidUse)) {
    qCritical("failed to look up account name: %ls", newOwner);
    res = FALSE;
  } else {
    EXPLICIT_ACCESS access;
    ZeroMemory(&access, sizeof(EXPLICIT_ACCESS));

    wchar_t ownerTemp[UNLEN + 1];
    wcsncpy(ownerTemp, newOwner, UNLEN + 1);

    // Set full control for Administrators.
    access.grfAccessPermissions = GENERIC_ALL;
    access.grfAccessMode = SET_ACCESS;
    access.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
    access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
    access.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
    access.Trustee.ptstrName = (LPTSTR)sid;

    DWORD secRes = SetEntriesInAcl(1, &access, nullptr, &pacl);
    if (secRes != ERROR_SUCCESS) {
      qCritical("failed to set up acls: %lu", secRes);
      return FALSE;
    }


    // filename parameter for SetNamedSecurityInfo isn't const
    // which is odd since it is documented to be a input parameter...
    TCHAR *fileNameBuf = new TCHAR[32768];
    wcsncpy_s(fileNameBuf, 32768, filename, 32768);
    // Set the owner on the file and give him full access
    secRes = SetNamedSecurityInfo(
        fileNameBuf, SE_FILE_OBJECT,
        OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
        sid, nullptr, pacl, nullptr);

    delete [] fileNameBuf;
    if (secRes != NOERROR) {
      qCritical("failed to set file owner: %d", secRes);
      res = false;
    }
  }

  if (sid != nullptr) {
    free(sid);
  }

  return res;
}
Beispiel #10
0
// dumpmemoryw - Dumps a nicely formatted rendition of a region of memory.
//   Includes both the hex value of each byte and its Unicode equivalent.
//
//  - address (IN): Pointer to the beginning of the memory region to dump.
//
//  - size (IN): The size, in bytes, of the region to dump.
//
//  Return Value:
//
//    None.
//
VOID dumpmemoryw (LPCVOID address, SIZE_T size)
{
    BYTE   byte;
    SIZE_T byteindex;
    SIZE_T bytesdone;
    SIZE_T dumplen;
    WCHAR  formatbuf [BYTEFORMATBUFFERLENGTH];
    WCHAR  hexdump [HEXDUMPLINELENGTH] = {0};
    SIZE_T hexindex;
    WORD   word;
    WCHAR  unidump [18] = {0};
    SIZE_T uniindex;

    // Each line of output is 16 bytes.
    if ((size % 16) == 0) {
        // No padding needed.
        dumplen = size;
    }
    else {
        // We'll need to pad the last line out to 16 bytes.
        dumplen = size + (16 - (size % 16));
    }

    // For each word of data, get both the Unicode equivalent and the hex
    // representation.
    bytesdone = 0;
    for (byteindex = 0; byteindex < dumplen; byteindex++) {
        hexindex = 3 * ((byteindex % 16) + ((byteindex % 16) / 4));   // 3 characters per byte, plus a 3-character space after every 4 bytes.
        uniindex = ((byteindex / 2) % 8) + ((byteindex / 2) % 8) / 8; // 1 character every other byte, plus a 1-character space after every 8 bytes.
        if (byteindex < size) {
            byte = ((PBYTE)address)[byteindex];
            _snwprintf_s(formatbuf, BYTEFORMATBUFFERLENGTH, _TRUNCATE, L"%.2X ", byte);
            formatbuf[BYTEFORMATBUFFERLENGTH - 1] = '\0';
            wcsncpy_s(hexdump + hexindex, HEXDUMPLINELENGTH - hexindex, formatbuf, 4);
            if (((byteindex % 2) == 0) && ((byteindex + 1) < dumplen)) {
                // On every even byte, print one character.
                word = ((PWORD)address)[byteindex / 2];
                if ((word == 0x0000) || (word == 0x0020)) {
                    unidump[uniindex] = L'.';
                }
                else {
                    unidump[uniindex] = word;
                }
            }
        }
        else {
            // Add padding to fill out the last line to 16 bytes.
            wcsncpy_s(hexdump + hexindex, HEXDUMPLINELENGTH - hexindex, L"   ", 4);
            unidump[uniindex] = L'.';
        }
        bytesdone++;
        if ((bytesdone % 16) == 0) {
            // Print one line of data for every 16 bytes. Include the
            // ASCII dump and the hex dump side-by-side.
            report(L"    %s    %s\n", hexdump, unidump);
        }
        else {
            if ((bytesdone % 8) == 0) {
                // Add a spacer in the ASCII dump after every 8 bytes.
                unidump[uniindex + 1] = L' ';
            }
            if ((bytesdone % 4) == 0) {
                // Add a spacer in the hex dump after every 4 bytes.
                wcsncpy_s(hexdump + hexindex + 3, HEXDUMPLINELENGTH - hexindex - 3, L"   ", 4);
            }
        }
    }
}
Beispiel #11
0
// dumpmemorya - Dumps a nicely formatted rendition of a region of memory.
//   Includes both the hex value of each byte and its ASCII equivalent (if
//   printable).
//
//  - address (IN): Pointer to the beginning of the memory region to dump.
//
//  - size (IN): The size, in bytes, of the region to dump.
//
//  Return Value:
//
//    None.
//
VOID dumpmemorya (LPCVOID address, SIZE_T size)
{
    WCHAR  ascdump [18] = {0};
    SIZE_T ascindex;
    BYTE   byte;
    SIZE_T byteindex;
    SIZE_T bytesdone;
    SIZE_T dumplen;
    WCHAR  formatbuf [BYTEFORMATBUFFERLENGTH];
    WCHAR  hexdump [HEXDUMPLINELENGTH] = {0};
    SIZE_T hexindex;

    // Each line of output is 16 bytes.
    if ((size % 16) == 0) {
        // No padding needed.
        dumplen = size;
    }
    else {
        // We'll need to pad the last line out to 16 bytes.
        dumplen = size + (16 - (size % 16));
    }

    // For each byte of data, get both the ASCII equivalent (if it is a
    // printable character) and the hex representation.
    bytesdone = 0;
    for (byteindex = 0; byteindex < dumplen; byteindex++) {
        hexindex = 3 * ((byteindex % 16) + ((byteindex % 16) / 4)); // 3 characters per byte, plus a 3-character space after every 4 bytes.
        ascindex = (byteindex % 16) + (byteindex % 16) / 8;         // 1 character per byte, plus a 1-character space after every 8 bytes.
        if (byteindex < size) {
            byte = ((PBYTE)address)[byteindex];
            _snwprintf_s(formatbuf, BYTEFORMATBUFFERLENGTH, _TRUNCATE, L"%.2X ", byte);
            formatbuf[3] = '\0';
            wcsncpy_s(hexdump + hexindex, HEXDUMPLINELENGTH - hexindex, formatbuf, 4);
            if (isgraph(byte)) {
                ascdump[ascindex] = (WCHAR)byte;
            }
            else {
                ascdump[ascindex] = L'.';
            }
        }
        else {
            // Add padding to fill out the last line to 16 bytes.
            wcsncpy_s(hexdump + hexindex, HEXDUMPLINELENGTH - hexindex, L"   ", 4);
            ascdump[ascindex] = L'.';
        }
        bytesdone++;
        if ((bytesdone % 16) == 0) {
            // Print one line of data for every 16 bytes. Include the
            // ASCII dump and the hex dump side-by-side.
            report(L"    %s    %s\n", hexdump, ascdump);
        }
        else {
            if ((bytesdone % 8) == 0) {
                // Add a spacer in the ASCII dump after every 8 bytes.
                ascdump[ascindex + 1] = L' ';
            }
            if ((bytesdone % 4) == 0) {
                // Add a spacer in the hex dump after every 4 bytes.
                wcsncpy_s(hexdump + hexindex + 3, HEXDUMPLINELENGTH - hexindex - 3, L"   ", 4);
            }
        }
    }
}
Beispiel #12
0
HRESULT CLAVSplitterSettingsProp::OnActivate()
{
  HRESULT hr = S_OK;
  INITCOMMONCONTROLSEX icc;
  icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
  icc.dwICC = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES;
  if (InitCommonControlsEx(&icc) == FALSE)
  {
    return E_FAIL;
  }
  ASSERT(m_pLAVF != nullptr);

  const WCHAR *version = TEXT(LAV_SPLITTER) L" " TEXT(LAV_VERSION_STR);
  SendDlgItemMessage(m_Dlg, IDC_SPLITTER_FOOTER, WM_SETTEXT, 0, (LPARAM)version);

  hr = LoadData();
  memset(m_subLangBuffer, 0, sizeof(m_advSubBuffer));
  memset(m_advSubBuffer, 0, sizeof(m_advSubBuffer));

  m_selectedSubMode = LAVSubtitleMode_Default;
  if (m_pszAdvSubConfig)
    wcsncpy_s(m_advSubBuffer, m_pszAdvSubConfig, _TRUNCATE);

  // Notify the UI about those settings
  SendDlgItemMessage(m_Dlg, IDC_PREF_LANG, WM_SETTEXT, 0, (LPARAM)m_pszPrefLang);
  SendDlgItemMessage(m_Dlg, IDC_PREF_LANG_SUBS, WM_SETTEXT, 0, (LPARAM)m_pszPrefSubLang);

  // Init the Combo Box
  SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_RESETCONTENT, 0, 0);
  WideStringFromResource(stringBuffer, IDS_SUBMODE_NO_SUBS);
  SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer);
  WideStringFromResource(stringBuffer, IDS_SUBMODE_FORCED_SUBS);
  SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer);
  WideStringFromResource(stringBuffer, IDS_SUBMODE_DEFAULT);
  SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer);
  WideStringFromResource(stringBuffer, IDS_SUBMODE_ADVANCED);
  SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer);

  SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_SETCURSEL, m_subtitleMode, 0);
  addHint(IDC_SUBTITLE_MODE, L"Configure how subtitles are selected.");

  SendDlgItemMessage(m_Dlg, IDC_BD_SEPARATE_FORCED_SUBS, BM_SETCHECK, m_PGSForcedStream, 0);
  addHint(IDC_BD_SEPARATE_FORCED_SUBS, L"Enabling this causes the creation of a new \"Forced Subtitles\" stream, which will try to always display forced subtitles matching your selected audio language.\n\nNOTE: This option may not work on all Blu-ray discs.\nRequires restart to take effect.");

  SendDlgItemMessage(m_Dlg, IDC_BD_ONLY_FORCED_SUBS, BM_SETCHECK, m_PGSOnlyForced, 0);
  addHint(IDC_BD_ONLY_FORCED_SUBS, L"When enabled, all Blu-ray (PGS) subtitles will be filtered, and only forced subtitles will be sent to the renderer.\n\nNOTE: When this option is active, you will not be able to get the \"full\" subtitles.");

  SendDlgItemMessage(m_Dlg, IDC_VC1TIMESTAMP, BM_SETCHECK, m_VC1Mode, 0);
  addHint(IDC_VC1TIMESTAMP, L"Checked - Frame timings will be corrected.\nUnchecked - Frame timings will be sent untouched.\nIndeterminate (Auto) - Only enabled for decoders that rely on the splitter doing the corrections.\n\nNOTE: Only for debugging, if unsure, set to \"Auto\".");

  SendDlgItemMessage(m_Dlg, IDC_MKV_EXTERNAL, BM_SETCHECK, m_MKVExternal, 0);

  SendDlgItemMessage(m_Dlg, IDC_SUBSTREAMS, BM_SETCHECK, m_substreams, 0);
  addHint(IDC_SUBSTREAMS, L"Controls if sub-streams should be exposed as a separate stream.\nSub-streams are typically streams for backwards compatibility, for example the AC3 part of TrueHD streams on Blu-rays.");

  SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_REMOVE_AUDIO, BM_SETCHECK, m_StreamSwitchRemoveAudio, 0);
  addHint(IDC_STREAM_SWITCH_REMOVE_AUDIO, L"Remove the old Audio Decoder from the Playback Chain before switching the audio stream, forcing DirectShow to select a new one.\n\nThis option ensures that the preferred decoder is always used, however it does not work properly with all players.");

  addHint(IDC_SELECT_AUDIO_QUALITY, L"Controls if the stream with the highest quality (matching your language preferences) should always be used.\nIf disabled, the first stream is always used.");
  SendDlgItemMessage(m_Dlg, IDC_SELECT_AUDIO_QUALITY, BM_SETCHECK, m_PreferHighQualityAudio, 0);

  SendDlgItemMessage(m_Dlg, IDC_IMPAIRED_AUDIO, BM_SETCHECK, m_ImpairedAudio, 0);

  SendDlgItemMessage(m_Dlg, IDC_QUEUE_MEM_SPIN, UDM_SETRANGE32, 0, 2048);

  addHint(IDC_QUEUE_MEM, L"Set the maximum memory a frame queue can use for buffering (in megabytes).\nNote that this is the maximum value, only very high bitrate files will usually even reach the default maximum value.");
  addHint(IDC_QUEUE_MEM_SPIN, L"Set the maximum memory a frame queue can use for buffering (in megabytes).\nNote that this is the maximum value, only very high bitrate files will usually even reach the default maximum value.");

  WCHAR stringBuffer[100];
  swprintf_s(stringBuffer, L"%d", m_QueueMaxMem);
  SendDlgItemMessage(m_Dlg, IDC_QUEUE_MEM, WM_SETTEXT, 0, (LPARAM)stringBuffer);

  SendDlgItemMessage(m_Dlg, IDC_QUEUE_PACKETS_SPIN, UDM_SETRANGE32, 100, 100000);

  addHint(IDC_QUEUE_PACKETS, L"Set the maximum numbers of packets to buffer in the frame queue.\nNote that the frame queue will never exceed the memory limited set above.");
  addHint(IDC_QUEUE_PACKETS_SPIN, L"Set the maximum numbers of packets to buffer in the frame queue.\nNote that the frame queue will never exceed the memory limited set above.");

  swprintf_s(stringBuffer, L"%d", m_QueueMaxPackets);
  SendDlgItemMessage(m_Dlg, IDC_QUEUE_PACKETS, WM_SETTEXT, 0, (LPARAM)stringBuffer);

  SendDlgItemMessage(m_Dlg, IDC_STREAM_ANADUR_SPIN, UDM_SETRANGE32, 200, 10000);

  addHint(IDC_STREAM_ANADUR, L"Set the duration (in milliseconds) a network stream is analyzed for before playback starts.\nA longer duration ensures the stream parameters are properly detected, however it will delay playback start.\n\nDefault: 1000 (1 second)");
  addHint(IDC_STREAM_ANADUR_SPIN, L"Set the duration (in milliseconds) a network stream is analyzed for before playback starts.\nA longer duration ensures the stream parameters are properly detected, however it will delay playback start.\n\nDefault: 1000 (1 second)");

  swprintf_s(stringBuffer, L"%d", m_NetworkAnalysisDuration);
  SendDlgItemMessage(m_Dlg, IDC_STREAM_ANADUR, WM_SETTEXT, 0, (LPARAM)stringBuffer);

  UpdateSubtitleMode(m_subtitleMode);

  SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_SETCHECK, m_TrayIcon, 0);

  return hr;
}
Beispiel #13
0
BOOL ShellCache::IsPathAllowed(LPCTSTR path)
{
    ValidatePathFilter();
    Locker lock(m_critSec);
    svn_tristate_t allowed = pathFilter.IsPathAllowed (path);
    if (allowed != svn_tristate_unknown)
        return allowed == svn_tristate_true ? TRUE : FALSE;

    UINT drivetype = 0;
    int drivenumber = PathGetDriveNumber(path);
    if ((drivenumber >=0)&&(drivenumber < 25))
    {
        drivetype = drivetypecache[drivenumber];
        if ((drivetype == -1)||((GetTickCount64() - drivetypeticker)>DRIVETYPETIMEOUT))
        {
            if ((DWORD(drivefloppy) == 0)&&((drivenumber == 0)||(drivenumber == 1)))
                drivetypecache[drivenumber] = DRIVE_REMOVABLE;
            else
            {
                drivetypeticker = GetTickCount64();
                TCHAR pathbuf[MAX_PATH + 4] = { 0 };      // MAX_PATH ok here. PathStripToRoot works with partial paths too.
                wcsncpy_s(pathbuf, path, _countof(pathbuf)-1);
                PathStripToRoot(pathbuf);
                PathAddBackslash(pathbuf);
                CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": GetDriveType for %s, Drive %d\n", pathbuf, drivenumber);
                drivetype = GetDriveType(pathbuf);
                drivetypecache[drivenumber] = drivetype;
            }
        }
    }
    else
    {
        TCHAR pathbuf[MAX_PATH + 4] = { 0 };      // MAX_PATH ok here. PathIsUNCServer works with partial paths too.
        wcsncpy_s(pathbuf, path, _countof(pathbuf)-1);
        if (PathIsUNCServer(pathbuf))
            drivetype = DRIVE_REMOTE;
        else
        {
            PathStripToRoot(pathbuf);
            PathAddBackslash(pathbuf);
            if (wcsncmp(pathbuf, drivetypepathcache, MAX_PATH-1)==0)       // MAX_PATH ok.
                drivetype = drivetypecache[26];
            else
            {
                CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L"GetDriveType for %s\n", pathbuf);
                drivetype = GetDriveType(pathbuf);
                drivetypecache[26] = drivetype;
                wcsncpy_s(drivetypepathcache, pathbuf, MAX_PATH);            // MAX_PATH ok.
            }
        }
    }
    if ((drivetype == DRIVE_REMOVABLE)&&(!IsRemovable()))
        return FALSE;
    if ((drivetype == DRIVE_FIXED)&&(!IsFixed()))
        return FALSE;
    if (((drivetype == DRIVE_REMOTE)||(drivetype == DRIVE_NO_ROOT_DIR))&&(!IsRemote()))
        return FALSE;
    if ((drivetype == DRIVE_CDROM)&&(!IsCDRom()))
        return FALSE;
    if ((drivetype == DRIVE_RAMDISK)&&(!IsRAM()))
        return FALSE;
    if ((drivetype == DRIVE_UNKNOWN)&&(IsUnknown()))
        return FALSE;

    return TRUE;
}
//-----------------------------------------------------------------------------
static void process_dir_watcher_results(
    watch_entry *watch_entry_p,
	DWORD           buffer_size){
//-----------------------------------------------------------------------------
    HANDLE hChangeLog;
    PFILE_NOTIFY_INFORMATION buffer_p;
    DWORD buffer_index;
    BOOL more;
    SSIZE_T path_len;
    int compare_result;
    BOOL exclude;
    struct exclude_entry * exclude_entry_p;
    DWORD error_code;
	errno_t copy_result;
	LPWSTR fmt, slash_pos;

	hChangeLog = INVALID_HANDLE_VALUE;
    more = TRUE;
    buffer_index = 0;

	// If buffer size is 0, indicates that too many changes occurred to fit in the buffer
	// Write out the top level dir to trigger the monitor to do a full pass of it
	if (buffer_size == 0){
		more = FALSE;
		copy_result = wcsncpy_s(full_file_name, ARRAYSIZE(full_file_name),
			watch_entry_p->dir_path, watch_entry_p->dir_path_len);
		if (copy_result != 0){
			report_error(L"wcsncpy_s failed", copy_result);
			ExitProcess(28);
			}
		write_path_to_temp_file(full_file_name, ARRAYSIZE(full_file_name), &hChangeLog);
	}

	while (more) {
		buffer_p = (PFILE_NOTIFY_INFORMATION) &watch_entry_p->changes_buffer[buffer_index];
		// Cannot use just sizeof(FILE_NOTIFY_INFORMATION) as it includes 2 bytes of struct padding,
		// causing this check to fail for single-character filenames
		size_t entry_size = offsetof(FILE_NOTIFY_INFORMATION, FileName) + buffer_p->FileNameLength;
        if ((buffer_index + entry_size) > buffer_size) {
            _wfopen_s(&error_file, error_path, L"w");
            fwprintf(
                error_file, 
                L"process_dir_watcher_results buffer overrun %d %d\n",  
                buffer_index,
                buffer_size
            );
            fclose(error_file);
            ExitProcess(18);
        }

        copy_result = wcsncpy_s(relative_file_name, ARRAYSIZE(relative_file_name),
			buffer_p->FileName, buffer_p->FileNameLength/sizeof(wchar_t));
		if (copy_result != 0){
			report_error(L"wcsncpy_s failed", copy_result);
			ExitProcess(25);
			}

        // 2010-09-05 dougfort -- if the dir_path ends in a slash 
        // (probably something like c:\) then we don't want to
        // interpolate another slash
		if (watch_entry_p->dir_path[watch_entry_p->dir_path_len-1] == L'\\')
			fmt = L"%s%s";
		else
			fmt = L"%s\\%s";
		path_len = _snwprintf_s(full_file_name, ARRAYSIZE(full_file_name), _TRUNCATE,
			fmt, watch_entry_p->dir_path, relative_file_name);
		if (path_len == -1){
			report_error(L"_snwprintf_s failed, path too long",
				(DWORD)(watch_entry_p->dir_path_len + wcslen(relative_file_name)));
			ExitProcess(26);
		}

		// We want the directory where the event took place, 
		// for consistency with OSX.
		// Needs to be done before calling GetLongPathName since in the case of
		// a rename or delete the actual file itself is already gone
		if (full_file_name[path_len-1] != L'\\') {
			slash_pos = wcsrchr(full_file_name, L'\\');
			if (slash_pos)
				*slash_pos = L'\0';
		}

		// Need to translate short names before checking excludes
		// According to MSDN docs, you can reuse the same buffer for output
		path_len = GetLongPathNameW(
			full_file_name,
			full_file_name,
			ARRAYSIZE(full_file_name)
		);
		// Note that most of errors that occurred here were due to a buffer overflow
		// which has since been fixed.  In case of error, pass orig filename unchanged and
		// let code that picks up output deal with removed folders, etc
		if (path_len == 0) {
			error_code = GetLastError();
			report_error(L"GetLongPathNameW", error_code);
			path_len=wcslen(full_file_name);
		}
		else if (path_len > ARRAYSIZE(full_file_name)){
			// Shouldn't happen since buffer is maximum possible path length
			report_error(L"GetLongPathNameW result would overflow buffer", (DWORD)path_len);
			ExitProcess(27);
		}

		// Can check for excludes last since we only ever exclude folders
        exclude = FALSE;
        for (
            exclude_entry_p=exclude_entry_list_p; 
            exclude_entry_p != NULL; 
            exclude_entry_p = exclude_entry_p->next_p
        ) {
            compare_result = _wcsnicmp(
                full_file_name,
                exclude_entry_p->dir_path,
                exclude_entry_p->dir_path_len
            );
            if (0 == compare_result) {
                exclude = TRUE;
                break;
            }
        }

        if (exclude) {
            if (0 == buffer_p->NextEntryOffset) {
                more = FALSE;
            } else {
                buffer_index += buffer_p->NextEntryOffset;
            }
            continue;
        }

		write_path_to_temp_file(full_file_name, ARRAYSIZE(full_file_name), &hChangeLog);

        if (0 == buffer_p->NextEntryOffset) {
            more = FALSE;
        } else {
            buffer_index += buffer_p->NextEntryOffset;
        }
    } // while (more)

    if (hChangeLog != INVALID_HANDLE_VALUE) {
        CloseHandle(hChangeLog);

        notification_sequence++;
        wsprintf(          
            notification_file_path,         // LPTSTR pszDest,
            L"%s\\%08d.txt",                // LPCTSTR pszFormat 
            notification_path,
            notification_sequence
        );
        if (_wrename(temp_file_path, notification_file_path) != 0) {
            _wfopen_s(&error_file, error_path, L"w");
            _wcserror_s(
               error_buffer, sizeof error_buffer/sizeof(wchar_t), errno
            ); 
            fwprintf(
                error_file, 
                L"_wrename(%s, %s) failed: (%d) %s\n",  
                temp_file_path,
                notification_file_path,
                errno,
                error_buffer 
            );
            fclose(error_file);
            ExitProcess(24);
        }
    }

} // static void process_dir_watcher_results(
 SimpleEventListener(LPWSTR type)
 {
     wcsncpy_s(m_eventType, 100, type, 100);
     m_eventType[99] = 0;
 }
/////////////////////////////////////////////////////////
//
// GetComponentInfo
//
//        This helper function, provided with a component
//        ProgId, gathers the component's name and version
//        info and formats them into output strings
//
// Parameters:
//        CLSID  clsid  : [in] component's CLSID
//        SInfo& info   : [in, out] a structure of buffers
//                        to get the formatted strings into
//
// Return Values:
//        TRUE, if the function succeeds
//        FALSE, if it fails
//
/////////////////////////////////////////////////////////
BOOL GetComponentInfo(CLSID clsid, SInfo& info)
{
    info.wchName[0] = info.wchVersion[0] = 0;

    // Format Registry Key string
    WCHAR wszKey[45] = L"CLSID\\";  // the key buffer should be large enough for a string
                                    // like "CLSID\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"
    // Convert CLSID to String
    UINT uPos = lstrlenW(wszKey);
    if (0 == StringFromGUID2(clsid, &wszKey[uPos], countof(wszKey) - uPos))
        return FALSE;
    wszKey[countof(wszKey)-1] = 0;

    // Open key to find path of application
    HKEY hKeyRoot;
    if (RegOpenKeyExW(HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hKeyRoot) != ERROR_SUCCESS)
        return FALSE;

    // Query value of key to get the name of the component
    ULONG cSize = sizeof(info.wchName);  // size of the buffer in bytes
    if (RegQueryValueExW(hKeyRoot, NULL, NULL, NULL, (BYTE*)info.wchName, &cSize) != ERROR_SUCCESS)
    {
        RegCloseKey(hKeyRoot);
        return FALSE;
    }
    info.wchName[countof(info.wchName) - 1] = 0;

    // Open the version info subkey
    UINT iVersionMaxLen = countof(info.wchVersion);
    HKEY hKey = NULL;
    if (RegOpenKeyExW(hKeyRoot, L"Version", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
    {
        const WCHAR* pcwsVersion = L"version ";
        UINT iLen = lstrlenW(pcwsVersion);
        // Query value of key to get version string
        if (iLen < iVersionMaxLen)
        {
            // copy the "version " string including terminating 0
            wcsncpy_s(info.wchVersion, iVersionMaxLen, pcwsVersion, iLen + 1);

            // get the version string
            cSize = (iVersionMaxLen - iLen) * sizeof(WCHAR); // the size is in bytes
            if (RegQueryValueExW(hKey, NULL, NULL, NULL,
                                 (BYTE*)&info.wchVersion[iLen],
                                 &cSize) == ERROR_SUCCESS)
            {
                info.wchVersion[iVersionMaxLen-1] = 0;
            }
        }
        RegCloseKey(hKey);
    }

    // Open InprocServer32 subkey to get the path to the component
    if (RegOpenKeyExW(hKeyRoot, L"InprocServer32", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
    {
        // Query value of key to get the path string
        WCHAR wchPath[MAX_PATH];
        cSize = sizeof(wchPath);
        if (RegQueryValueExW(hKey, NULL, NULL, NULL, (BYTE*)wchPath, &cSize) == ERROR_SUCCESS)
        {
            // Get the build number from the file version info
            DWORD dwHandle = 0;
            cSize = GetFileVersionInfoSizeW(wchPath, &dwHandle); // returns the size in bytes
            WCHAR* pwchFileVerInfo = NULL;
            if (cSize)
            {
                pwchFileVerInfo = (WCHAR*)new BYTE[cSize];
            }
            if (NULL != pwchFileVerInfo)
            {
                // Retrieve version information for the file
                if (GetFileVersionInfoW(wchPath, 0, cSize, pwchFileVerInfo))
                {
                    // Get the default language id and code page number
                    UINT *pdwLang;
                    UINT cch = 0;
                    if (VerQueryValueW(pwchFileVerInfo, L"\\VarFileInfo\\Translation",
                                       (void**)&pdwLang, &cch) == TRUE)
                    {
                        // Read the file description for the language and code page.
                        const int MAX_SUBBLOCK = 40;
                        WCHAR wchSubBlock[MAX_SUBBLOCK];  // large enough for the string
                        StringCchPrintfExW(wchSubBlock,
                                          MAX_SUBBLOCK,
                                          NULL,
                                          NULL,
                                          STRSAFE_NULL_ON_FAILURE,
                                          L"\\StringFileInfo\\%04x%04x\\FileVersion",
                                          LOWORD(*pdwLang), HIWORD(*pdwLang));

                        WCHAR* pwchBuildVer = NULL;
                        if ((VerQueryValueW(pwchFileVerInfo, wchSubBlock,
                                            (void**)&pwchBuildVer, &cch) == TRUE)
                            && (NULL != pwchBuildVer))
                        {
                            // Format the version string
                            UINT iLen = (UINT)lstrlenW(info.wchVersion);
                            if (0 < iLen)
                            {
                                if (iLen < iVersionMaxLen)
                                {
                                    const WCHAR* pcwsBuild = L", build ";
                                    wcsncpy_s(info.wchVersion + iLen, iVersionMaxLen - iLen, pcwsBuild, iVersionMaxLen - iLen);
                                    iLen += lstrlenW(pcwsBuild);
                                    if (iLen < iVersionMaxLen)
                                    {
                                        wcsncpy_s(info.wchVersion + iLen, iVersionMaxLen - iLen, pwchBuildVer, iVersionMaxLen - iLen);
                                    }
                                }
                            }
                            else
                            {
                                wcsncpy_s(info.wchVersion, iVersionMaxLen, pwchBuildVer, iVersionMaxLen);
                            }
                            info.wchVersion[iVersionMaxLen-1] = 0;
                        }
                    }
                }
                delete [] pwchFileVerInfo;
            }

        }
        RegCloseKey(hKey);
    }

    RegCloseKey(hKeyRoot);

    return TRUE;
}
Beispiel #17
0
void CNHSQLServerDBO::SetLogFilePath(const wchar_t *const pFilePath)
{
    assert(NULL != pFilePath);
    wcsncpy_s(m_wchLogFilePath, _countof(m_wchLogFilePath), pFilePath, _TRUNCATE);
}
Beispiel #18
0
bool CCacheDlg::GetStatusFromRemoteCache(const CTGitPath& Path, bool bRecursive)
{
	if(!EnsurePipeOpen())
	{
		STARTUPINFO startup;
		PROCESS_INFORMATION process;
		memset(&startup, 0, sizeof(startup));
		startup.cb = sizeof(startup);
		memset(&process, 0, sizeof(process));

		CString sCachePath = _T("TGitCache.exe");
		if (CreateProcess(sCachePath.GetBuffer(sCachePath.GetLength()+1), _T(""), NULL, NULL, FALSE, 0, 0, 0, &startup, &process)==0)
		{
			// It's not appropriate to do a message box here, because there may be hundreds of calls
			sCachePath.ReleaseBuffer();
			ATLTRACE("Failed to start cache\n");
			return false;
		}
		sCachePath.ReleaseBuffer();

		// Wait for the cache to open
		long endTime = (long)GetTickCount()+1000;
		while(!EnsurePipeOpen())
		{
			if(((long)GetTickCount() - endTime) > 0)
			{
				return false;
			}
		}
	}


	DWORD nBytesRead;
	TGITCacheRequest request;
	request.flags = TGITCACHE_FLAGS_NONOTIFICATIONS;
	if(bRecursive)
	{
		request.flags |= TGITCACHE_FLAGS_RECUSIVE_STATUS;
	}
	wcsncpy_s(request.path, Path.GetWinPath(), MAX_PATH);
	SecureZeroMemory(&m_Overlapped, sizeof(OVERLAPPED));
	m_Overlapped.hEvent = m_hEvent;
	// Do the transaction in overlapped mode.
	// That way, if anything happens which might block this call
	// we still can get out of it. We NEVER MUST BLOCK THE SHELL!
	// A blocked shell is a very bad user impression, because users
	// who don't know why it's blocked might find the only solution
	// to such a problem is a reboot and therefore they might loose
	// valuable data.
	// Sure, it would be better to have no situations where the shell
	// even can get blocked, but the timeout of 5 seconds is long enough
	// so that users still recognize that something might be wrong and
	// report back to us so we can investigate further.

	TGITCacheResponse ReturnedStatus;
	BOOL fSuccess = TransactNamedPipe(m_hPipe,
		&request, sizeof(request),
		&ReturnedStatus, sizeof(ReturnedStatus),
		&nBytesRead, &m_Overlapped);

	if (!fSuccess)
	{
		if (GetLastError()!=ERROR_IO_PENDING)
		{
			ClosePipe();
			return false;
		}

		// TransactNamedPipe is working in an overlapped operation.
		// Wait for it to finish
		DWORD dwWait = WaitForSingleObject(m_hEvent, INFINITE);
		if (dwWait == WAIT_OBJECT_0)
		{
			fSuccess = GetOverlappedResult(m_hPipe, &m_Overlapped, &nBytesRead, FALSE);
			return TRUE;
		}
		else
			fSuccess = FALSE;
	}

	ClosePipe();
	return false;
}
void LoadConfig()
{
	BOOL servtmp;
	WCHAR hosttmp[MAX_SKKSERVER_HOST];	//ホスト
	WCHAR porttmp[MAX_SKKSERVER_PORT];	//ポート
	DWORD encodingtmp;
	DWORD timeouttmp;
	std::wstring strxmlval;

	ReadValue(pathconfigxml, SectionServer, ValueServerServ, strxmlval);
	servtmp = _wtoi(strxmlval.c_str());
	if(servtmp != TRUE && servtmp != FALSE)
	{
		servtmp = FALSE;
	}

	ReadValue(pathconfigxml, SectionServer, ValueServerHost, strxmlval);
	wcsncpy_s(hosttmp, strxmlval.c_str(), _TRUNCATE);

	ReadValue(pathconfigxml, SectionServer, ValueServerPort, strxmlval);
	wcsncpy_s(porttmp, strxmlval.c_str(), _TRUNCATE);

	ReadValue(pathconfigxml, SectionServer, ValueServerEncoding, strxmlval);
	encodingtmp = _wtoi(strxmlval.c_str());
	if(encodingtmp != 1)
	{
		encodingtmp = 0;
	}

	ReadValue(pathconfigxml, SectionServer, ValueServerTimeOut, strxmlval);
	timeouttmp = _wtoi(strxmlval.c_str());
	if(timeouttmp > 60000)
	{
		timeouttmp = 1000;
	}

	//変更があったら接続し直す
	if(servtmp != serv || wcscmp(hosttmp, host) != 0 || wcscmp(porttmp, port) != 0 ||
		encodingtmp != encoding || timeouttmp != timeout)
	{
		serv = servtmp;
		wcsncpy_s(host, hosttmp, _TRUNCATE);
		wcsncpy_s(port, porttmp, _TRUNCATE);
		encoding = encodingtmp;
		timeout = timeouttmp;

		DisconnectSKKServer();

		if(serv)
		{
			ConnectSKKServer();
			GetSKKServerInfo(SKK_VER);
		}
	}

	ReadValue(pathconfigxml, SectionBehavior, ValuePrecedeOkuri, strxmlval);
	precedeokuri = _wtoi(strxmlval.c_str());
	if(precedeokuri != TRUE && precedeokuri != FALSE)
	{
		precedeokuri = FALSE;
	}

	ReadValue(pathconfigxml, SectionBehavior, ValueCompIncBack, strxmlval);
	compincback = _wtoi(strxmlval.c_str());
	if(compincback != TRUE && compincback != FALSE)
	{
		compincback = FALSE;
	}
}
Beispiel #20
0
void CCacheDlg::RemoveFromCache(const CString& path)
{
	// if we use the external cache, we tell the cache directly that something
	// has changed, without the detour via the shell.
	HANDLE hPipe = CreateFile( 
		GetCacheCommandPipeName(),	// pipe name 
		GENERIC_READ |					// read and write access 
		GENERIC_WRITE, 
		0,								// no sharing 
		NULL,							// default security attributes
		OPEN_EXISTING,					// opens existing pipe 
		FILE_FLAG_OVERLAPPED,			// default attributes 
		NULL);							// no template file 


	if (hPipe != INVALID_HANDLE_VALUE) 
	{
		// The pipe connected; change to message-read mode. 
		DWORD dwMode; 

		dwMode = PIPE_READMODE_MESSAGE; 
		if(SetNamedPipeHandleState( 
			hPipe,    // pipe handle 
			&dwMode,  // new pipe mode 
			NULL,     // don't set maximum bytes 
			NULL))    // don't set maximum time 
		{
			DWORD cbWritten; 
			TGITCacheCommand cmd;
			cmd.command = TGITCACHECOMMAND_CRAWL;
			wcsncpy_s(cmd.path, path, MAX_PATH);
			BOOL fSuccess = WriteFile( 
				hPipe,			// handle to pipe 
				&cmd,			// buffer to write from 
				sizeof(cmd),	// number of bytes to write 
				&cbWritten,		// number of bytes written 
				NULL);			// not overlapped I/O 

			if (! fSuccess || sizeof(cmd) != cbWritten)
			{
				DisconnectNamedPipe(hPipe); 
				CloseHandle(hPipe); 
				hPipe = INVALID_HANDLE_VALUE;
			}
			if (hPipe != INVALID_HANDLE_VALUE)
			{
				// now tell the cache we don't need it's command thread anymore
				DWORD cbWritten; 
				TGITCacheCommand cmd;
				cmd.command = TGITCACHECOMMAND_END;
				WriteFile( 
					hPipe,			// handle to pipe 
					&cmd,			// buffer to write from 
					sizeof(cmd),	// number of bytes to write 
					&cbWritten,		// number of bytes written 
					NULL);			// not overlapped I/O 
				DisconnectNamedPipe(hPipe); 
				CloseHandle(hPipe); 
				hPipe = INVALID_HANDLE_VALUE;
			}
		}
		else
		{
			ATLTRACE("SetNamedPipeHandleState failed"); 
			CloseHandle(hPipe);
		}
	}
}
int CMediaLibrary::GetExtendedFileInfo(const wchar_t *fn, const wchar_t *Metadata, wchar_t *dest, size_t destlen)
{

	bool FindTag;
	int RetCode;

	::EnterCriticalSection(&CriticalSection);

	if (std::wstring(fn) != FileName)
	{
		FindTag = GetTagInfo(fn);
	}
	else
	{
		FindTag = true;
	}

	if (FindTag) {
		wchar_t	Buff[MAX_MUSICTEXT];
		const char *MetaData = reinterpret_cast<const char*>(Metadata);

		if (_stricmp(MetaData, "length") == 0) {
			_ultow_s(TagDataW.Length, dest, destlen, 10);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "formatinformation") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Format.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "type") == 0) {
			Buff[0] = '0';
			Buff[1] = 0;
			wcsncpy_s(dest, destlen, Buff, _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "family") == 0) {
			wcsncpy_s(dest, destlen, L"The True Audio File", _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "lossless") == 0) {
			Buff[0] = '1';
			wcsncpy_s(dest, destlen, Buff, _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "title") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Title.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "artist") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Artist.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "albumartist") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.AlbumArtist.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "comment") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Comment.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "album") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Album.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "year") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Year.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "genre") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Genre.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "track") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Track.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "composer") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Composer.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "publisher") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Publisher.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "disc") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.Disc.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else if (_stricmp(MetaData, "bpm") == 0) {
			wcsncpy_s(dest, destlen, TagDataW.BPM.c_str(), _TRUNCATE);
			RetCode = 1;
		}
		else {
			RetCode = 0;
		}

	}
	else {
		FileName = L"";
		RetCode = 0;
	}

	::LeaveCriticalSection(&CriticalSection);
	return RetCode;
}
Beispiel #22
0
// helper function to parse node in tldString
int readTldString(tldnode* node, const wchar_t* s, int len, int pos) {

	int start = pos;
	int state = 0;

	memset(node, 0, sizeof(tldnode));
	do {
		wchar_t c = *(s+pos);

		switch(state) {
			case 0: // general read

				if (c==L',' || c==L')' || c==L'(') {
					// add last domain
					int count = node->attr == THIS ? pos - start : pos - start + 1;
					node->dom = (wchar_t*) malloc(count * sizeof(wchar_t));
					wcsncpy_s(node->dom, count, s+start, _TRUNCATE);

					if (c==L'(') {
						// read number of children
						start = pos;
						state = 1;
					} else if (c==L')' || c==L',') {
						// return to parent domains
						return pos;
					}

				} else if (c==L'!') {
					node->attr=THIS;
				}

				break;
			case 1: // reading number of elements (<number>:

				if (c==L':') {
					int count = pos - start;
					wchar_t* buf = (wchar_t*) malloc(count * sizeof(wchar_t));
					wcsncpy_s(buf, count, s+start+1, _TRUNCATE);
					node->num_children = wcstol(buf, NULL, 10);
					free(buf);

					// allocate space for children
					node->subnodes = (tldnode**) malloc(node->num_children * sizeof(tldnode*));

					int i;
					for (i=0; i<node->num_children; i++) {
						tldnode* subnode = (tldnode*)malloc(sizeof(tldnode));
						pos = readTldString(subnode, s, len, pos + 1);
						node->subnodes[i] = subnode;
					}

					// sort alphabetically for better search performance
					sort(node->subnodes, node->subnodes + node->num_children,
						[] (const tldnode* node1, const tldnode* node2) -> bool {
							// asterisks always comes first
							if (wcscmp(node1->dom, ALL) == 0) return true;
							if (wcscmp(node2->dom, ALL) == 0) return false;
							
							return wcscmp(node1->dom, node2->dom) < 0;
						}
					);

					return pos + 1;
				}

				break;
		}

		pos++;
	} while (pos < len);

	return pos;
}
Beispiel #23
0
AddrInfo GetAddr(uint32_t module, uint64_t addr)
{
  AddrInfo ret;
  ZeroMemory(&ret, sizeof(ret));

  if(module > 0 && module <= modules.size())
  {
    SymTagEnum tag = SymTagFunction;
    IDiaSymbol *pFunc = NULL;
    HRESULT hr = modules[module - 1].pSession->findSymbolByVA(addr, tag, &pFunc);

    if(hr != S_OK)
    {
      if(pFunc)
        pFunc->Release();

      // try again looking for public symbols
      tag = SymTagPublicSymbol;
      hr = modules[module - 1].pSession->findSymbolByVA(addr, tag, &pFunc);

      if(hr != S_OK)
      {
        if(pFunc)
          pFunc->Release();
        return ret;
      }
    }

    DWORD opts = 0;
    opts |= UNDNAME_NO_LEADING_UNDERSCORES;
    opts |= UNDNAME_NO_MS_KEYWORDS;
    opts |= UNDNAME_NO_FUNCTION_RETURNS;
    opts |= UNDNAME_NO_ALLOCATION_MODEL;
    opts |= UNDNAME_NO_ALLOCATION_LANGUAGE;
    opts |= UNDNAME_NO_THISTYPE;
    opts |= UNDNAME_NO_ACCESS_SPECIFIERS;
    opts |= UNDNAME_NO_THROW_SIGNATURES;
    opts |= UNDNAME_NO_MEMBER_TYPE;
    opts |= UNDNAME_NO_RETURN_UDT_MODEL;
    opts |= UNDNAME_32_BIT_DECODE;
    opts |= UNDNAME_NO_LEADING_UNDERSCORES;

    // first try undecorated name
    BSTR file;
    hr = pFunc->get_undecoratedNameEx(opts, &file);

    // if not, just try name
    if(hr != S_OK)
    {
      hr = pFunc->get_name(&file);

      if(hr != S_OK)
      {
        pFunc->Release();
        SysFreeString(file);
        return ret;
      }

      wcsncpy_s(ret.funcName, file, 126);
    }
    else
    {
      wcsncpy_s(ret.funcName, file, 126);

      wchar_t *voidparam = wcsstr(ret.funcName, L"(void)");

      // remove stupid (void) for empty parameters
      if(voidparam != NULL)
      {
        *(voidparam + 1) = L')';
        *(voidparam + 2) = 0;
      }
    }

    pFunc->Release();
    pFunc = NULL;

    SysFreeString(file);

    // find the line numbers touched by this address.
    IDiaEnumLineNumbers *lines = NULL;
    hr = modules[module - 1].pSession->findLinesByVA(addr, DWORD(4), &lines);
    if(FAILED(hr))
    {
      if(lines)
        lines->Release();
      return ret;
    }

    IDiaLineNumber *line = NULL;
    ULONG count = 0;

    // just take the first one
    if(SUCCEEDED(lines->Next(1, &line, &count)) && count == 1)
    {
      IDiaSourceFile *dia_source = NULL;
      hr = line->get_sourceFile(&dia_source);
      if(FAILED(hr))
      {
        line->Release();
        lines->Release();
        if(dia_source)
          dia_source->Release();
        return ret;
      }

      hr = dia_source->get_fileName(&file);
      if(FAILED(hr))
      {
        line->Release();
        lines->Release();
        dia_source->Release();
        return ret;
      }

      wcsncpy_s(ret.fileName, file, 126);

      SysFreeString(file);

      dia_source->Release();
      dia_source = NULL;

      DWORD line_num = 0;
      hr = line->get_lineNumber(&line_num);
      if(FAILED(hr))
      {
        line->Release();
        lines->Release();
        return ret;
      }

      ret.lineNum = line_num;

      line->Release();
    }

    lines->Release();
  }

  return ret;
}
Beispiel #24
0
DWORD PE::AddSection(LPBYTE pBuffer,DWORD dwSize,PCHAR pszSectionName)
{
	//修改文件头中的区段数量
	m_pNt->FileHeader.NumberOfSections++;
	//增加区段表项
	memset(m_pLastSection,0,sizeof(IMAGE_SECTION_HEADER));
	//写入区段名
	strcpy_s((char*)m_pLastSection->Name,IMAGE_SIZEOF_SHORT_NAME,pszSectionName);
	//区段虚拟大小
	DWORD dwVirtualSize=0;
	//区段文件大小
	DWORD dwSizeOfRawData=0;
	//把文件加载到内存所需要的大小  
	DWORD dwSizeOfImage=m_pNt->OptionalHeader.SizeOfImage;
	//取余 查看内存是否对齐 
	if (dwSizeOfImage%m_dwMemAlign)
	{
		// 取商再原来基础上+1  比如说dwSizeOfImage=1726 对齐粒度m_dwMemAlign=200 
		//此时dwSizeOfImage=1800
		dwSizeOfImage=(dwSizeOfImage/m_dwMemAlign+1)*m_dwMemAlign;
	}
	else
	{
		dwSizeOfImage=(dwSizeOfImage/m_dwMemAlign)*m_dwMemAlign;
	}

	//区段对齐后的RVA(dwSize) /内存对齐粒度 m_dwMemAlign
	if (dwSize%m_dwMemAlign)
	{
		dwVirtualSize=(dwSize/m_dwMemAlign+1)*m_dwMemAlign;
	}
	else
	{
		dwVirtualSize=(dwSize/m_dwMemAlign)*m_dwMemAlign;
	}

	//区段对齐后的RVA(dwSize) /文件对齐粒度 m_dwMemAlign
	if (dwSize%m_dwFileAlign)
	{
		dwSizeOfRawData=(dwSize/m_dwFileAlign+1)*m_dwFileAlign;
	}
	else
	{
		dwSizeOfRawData=(dwSize/m_dwFileAlign)*m_dwFileAlign;
	}

	//获取到新的相对虚拟地址 RVA
	m_pLastSection->VirtualAddress=(m_pLastSection[-1].VirtualAddress+(dwSize/m_dwMemAlign)*m_dwMemAlign);
	//区段在文件中的偏移
	m_pLastSection->PointerToRawData=m_dwFileSize;
	//区段在文件中大小
	m_pLastSection->SizeOfRawData=dwSizeOfRawData;
	//区段在内存中大小
	m_pLastSection->Misc.VirtualSize=dwVirtualSize;
	//区段属性
	m_pLastSection->Characteristics=0Xe0000040;

	//增加 文件大小 创建文件 添加代码段 确定入口点
	m_pNt->OptionalHeader.SizeOfImage=dwSizeOfImage+dwVirtualSize;
	m_pNt->OptionalHeader.AddressOfEntryPoint=m_dwNewOEP+m_pLastSection->VirtualAddress;

	//生成输出文件路径
	CString strPath=m_objFIle.GetFilePath();
	TCHAR SzOutPath[MAX_PATH]={0};
	//获取文件后缀名
	LPWSTR strSuffix=PathFindExtension(strPath);
	//目标文件路径到SzOutPath
	wcsncpy_s(SzOutPath,MAX_PATH,strPath,wcslen(strPath));

	//移除后缀名
	PathRemoveExtension(SzOutPath);
	// 在路径最后附加“_1”
	wcscat_s(SzOutPath,MAX_PATH,L"_1");
	// 在路径最后附加刚刚保存的后缀名
	wcscat_s(SzOutPath, MAX_PATH, strSuffix);                           

	//创建文件
	CFile objFile(SzOutPath,CFile::modeCreate|CFile::modeReadWrite);
	objFile.Write(m_pFileBase,(DWORD)m_objFIle.GetLength());
	//移到文件尾
	objFile.SeekToEnd();
	//将pBuffer 按照大小dwSize 写入文件
	objFile.Write(pBuffer,dwSize);
	//返回操作完成后的最后一个区段的相对虚拟地址 RAV
	return m_pLastSection->VirtualAddress;

}
Beispiel #25
0
static LRESULT CALLBACK MainWndSubclassProc(
    _In_ HWND hWnd,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam,
    _In_ UINT_PTR uIdSubclass,
    _In_ ULONG_PTR dwRefData
    )
{
    if (uMsg == TaskbarButtonCreatedMsgId)
    {
        if (!TaskbarButtonsCreated)
        {
            BlackIcon = PhGetBlackIcon();
            ButtonsImageList = ImageList_Create(16, 16, ILC_COLOR32 | ILC_MASK, 0, 0);
            ImageList_SetImageCount(ButtonsImageList, 4);
            PhSetImageListBitmap(ButtonsImageList, 0, PluginInstance->DllBase, MAKEINTRESOURCE(IDB_CHART_LINE_BMP));
            PhSetImageListBitmap(ButtonsImageList, 1, PluginInstance->DllBase, MAKEINTRESOURCE(IDB_FIND_BMP));
            PhSetImageListBitmap(ButtonsImageList, 2, PluginInstance->DllBase, MAKEINTRESOURCE(IDB_APPLICATION_BMP));
            PhSetImageListBitmap(ButtonsImageList, 3, PluginInstance->DllBase, MAKEINTRESOURCE(IDB_APPLICATION_GO_BMP));

            ButtonsArray[0].dwMask = THB_FLAGS | THB_BITMAP | THB_TOOLTIP;
            ButtonsArray[0].dwFlags = THBF_ENABLED | THBF_DISMISSONCLICK;
            ButtonsArray[0].iId = PHAPP_ID_VIEW_SYSTEMINFORMATION;
            ButtonsArray[0].iBitmap = 0;
            wcsncpy_s(ButtonsArray[0].szTip, ARRAYSIZE(ButtonsArray[0].szTip), L"System Information", _TRUNCATE);

            ButtonsArray[1].dwMask = THB_FLAGS | THB_BITMAP | THB_TOOLTIP;
            ButtonsArray[1].dwFlags = THBF_ENABLED | THBF_DISMISSONCLICK;
            ButtonsArray[1].iId = PHAPP_ID_HACKER_FINDHANDLESORDLLS;
            ButtonsArray[1].iBitmap = 1;
            wcsncpy_s(ButtonsArray[1].szTip, ARRAYSIZE(ButtonsArray[1].szTip), L"Find Handles or DLLs", _TRUNCATE);

            ButtonsArray[2].dwMask = THB_FLAGS | THB_BITMAP | THB_TOOLTIP;
            ButtonsArray[2].dwFlags = THBF_ENABLED | THBF_DISMISSONCLICK;
            ButtonsArray[2].iId = PHAPP_ID_HELP_LOG;
            ButtonsArray[2].iBitmap = 2;
            wcsncpy_s(ButtonsArray[2].szTip, ARRAYSIZE(ButtonsArray[2].szTip), L"Application Log", _TRUNCATE);

            ButtonsArray[3].dwMask = THB_FLAGS | THB_BITMAP | THB_TOOLTIP;
            ButtonsArray[3].dwFlags = THBF_ENABLED | THBF_DISMISSONCLICK;
            ButtonsArray[3].iId = PHAPP_ID_TOOLS_INSPECTEXECUTABLEFILE;
            ButtonsArray[3].iBitmap = 3;
            wcsncpy_s(ButtonsArray[3].szTip, ARRAYSIZE(ButtonsArray[3].szTip), L"Inspect Executable File", _TRUNCATE);

            TaskbarButtonsCreated = TRUE;
        }

        if (TaskbarListClass)
        {
            // Set the ThumbBar image list
            ITaskbarList3_ThumbBarSetImageList(TaskbarListClass, PhMainWndHandle, ButtonsImageList);
            // Set the ThumbBar buttons array
            ITaskbarList3_ThumbBarAddButtons(TaskbarListClass, PhMainWndHandle, ARRAYSIZE(ButtonsArray), ButtonsArray);

            if (TaskbarIconType != TASKBAR_ICON_NONE)
            {
                // Set the initial ThumbBar icon
                ITaskbarList3_SetOverlayIcon(TaskbarListClass, PhMainWndHandle, BlackIcon, NULL);
            }
        }
    }

    return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
// 处理过程
BOOL CSDMdlAttrParaSpecifiedValueCheck::DoAction(void *pData, const CheckData &checkData)
{
	ProMdl pMdl = (ProMdl)pData;
	if (NULL == pMdl)
		return FALSE;

	ProModelitem mdlItem;
	ProMdlToModelitem(pMdl, &mdlItem);

	CStringArray arrItems;
	CStringToCStringArray(checkData.checkRule.arrRuleContent[0], arrItems, L";");

	ErrorItemArray arr;
	CStringArray arrFailedPara;	// 修复失败的参数列表
	arr.Copy(checkData.checkResult.arrErrorItems);
	for (int i=0, nIndex=0; i<arr.GetCount(); i++)
	{
		// 获取参数类型和是否指定
		int nParaType;
		BOOL bDesignation;
		CString strParaValue;
		nIndex = arr[i].nID;
		int nCount = arrItems[nIndex].Find(L")") - arrItems[nIndex].Find(L"(")-1;
		CString strProperty;
		strProperty = arrItems[nIndex].Mid(arrItems[nIndex].Find(L"(") + 1, nCount);
		CStringArray arrPropertys;
		CStringToCStringArray(strProperty, arrPropertys, L",");
		nParaType = _wtoi(arrPropertys[0]);
		strParaValue = arrPropertys[1];
		ParseParaValue(mdlItem, strParaValue, strParaValue);
		bDesignation = _wtoi(arrPropertys[1]);

		// 如果类型不匹配,先删除原参数
		if(arr[i].nType == PARAERROR_TYPE)
		{
			if (!DelSDParameter(&mdlItem, arr[i].strItemName, FALSE))
			{
				arrFailedPara.Add(arr[i].strItemName);
				continue;
			}
		}
		else if (arr[i].nType == PARAERROR_DESIGNATION)
		{
			GetSDParameter(&mdlItem, arr[i].strItemName, strParaValue, FALSE);
		}
		
		// 创建参数
		if (PARAM_STRING == nParaType)
		{
			if (!SetSDParameter(&mdlItem, arr[i].strItemName, strParaValue, FALSE))
			{
				arrFailedPara.Add(arr[i].strItemName);
				continue;
			}
		}
		else if (PARAM_REAL == nParaType)
		{
			double dVal = _wtof(strParaValue);
			if (!SetSDParameter(&mdlItem, arr[i].strItemName, dVal, FALSE))
			{
				arrFailedPara.Add(arr[i].strItemName);
				continue;
			}
		}
		else if (PARAM_INTEGER == nParaType)
		{
			int nVal = _wtoi(strParaValue);
			if (!SetSDParameter(&mdlItem, arr[i].strItemName, nVal, FALSE))
			{
				arrFailedPara.Add(arr[i].strItemName);
				continue;
			}
		}
		else if (PARAM_BOOL == nParaType)
		{
			ProBoolean bVal;
			if (_wtoi(strParaValue) == 0)
				bVal = PRO_B_FALSE;
			else
				bVal = PRO_B_TRUE;
			if (!SetSDParameter(&mdlItem, arr[i].strItemName, bVal, FALSE))
			{
				arrFailedPara.Add(arr[i].strItemName);
				continue;
			}
		}
		
		// 修改指定关系
		ProName paraname;
		wcsncpy_s(paraname, PRO_NAME_SIZE, (LPCTSTR)arr[i].strItemName, _TRUNCATE);
		ProParameter para;
		if (GetSDParameter(&mdlItem, paraname, para))
		{
			if (bDesignation)
			{
				ProParameterDesignationAdd(&para);
			}
			else
				ProParameterDesignationRemove(&para);
		}
	}

	if (arrFailedPara.GetCount() > 0)
	{
		CString strResult;
		strResult.Format(L"%s等%d个参数修复失败,请手动修复", arrFailedPara[0], arrFailedPara.GetCount());
		MessageBox(NULL, strResult, L"提示", MB_OK|MB_ICONINFORMATION);
		return FALSE;
	}

	return TRUE;
}
bool InstallService(PWSTR pszServiceName,
	PWSTR pszDisplayName,
	DWORD dwStartType,
	PWSTR pszDependencies,
	PWSTR pszAccount,
	PWSTR pszPassword)
{

	UninstallService(pszServiceName);
	//std::ofstream file("c:\\users\\slee\\desktop\\text.txt", std::ios::app);
	wchar_t szPath[MAX_PATH];
	bool ret = false;
	if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)) == 0) {
		//file << "GetModuleFileName failed w/err " << GetLastError() << std::endl;
		//wprintf(L"GetModuleFileName failed w/err 0x%08lx\n", GetLastError());
		return false;
	}

	std::wstring tmp(szPath);
	tmp = L"\"" + tmp + L"\"";
	wcsncpy_s(szPath, tmp.c_str(), tmp.size()+1);

	auto schSCManager = RAIISC_HANDLE(OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE));
	if (schSCManager.get() == nullptr) {
		//file << "OpenSCManager failed w/err " << GetLastError() << std::endl;
		//wprintf(L"OpenSCManager failed w/err 0x%08lx\n", GetLastError());
	}
	else {
		wcscat_s(szPath, L" -service_mon");
		// Install the service into SCM by calling CreateService
		auto schService = RAIISC_HANDLE(CreateService(
			schSCManager.get(),                   // SCManager database
			pszServiceName,                 // Name of service
			pszDisplayName,                 // Name to display
			SERVICE_ALL_ACCESS,           // Desired access
			SERVICE_WIN32_OWN_PROCESS,      // Service type
			dwStartType,                    // Service start type
			SERVICE_ERROR_NORMAL,           // Error control type
			szPath,                         // Service's binary
			NULL,                           // No load ordering group
			NULL,                           // No tag identifier
			pszDependencies,                // Dependencies
			pszAccount,                     // Service running account
			pszPassword                     // Password of the account
			));
		if (schService.get() == nullptr){
	/*		file << "CreateService failed w/err " << GetLastError() << std::endl;
			DEBUG_MSG("CreateService failed w / err %", GetLastError());*/
			return false;
		}
		else {
		//	RemoteDesktop::EventLog::WriteLog(L"Service Installed " + std::wstring(pszServiceName), RemoteDesktop::EventLog::EventType::INFORMATIONAL, RemoteDesktop::EventLog::EventCategory::NETWORK_CATEGORY, RemoteDesktop::EventLog::EventID::SERVICE);
		//	file << "Service is installed" << std::endl;
			//wprintf(L"%s is installed.\n", pszServiceName);

			SERVICE_STATUS_PROCESS ssStatus;
			DWORD dwOldCheckPoint;
			DWORD dwStartTickCount;
			DWORD dwWaitTime;
			DWORD dwBytesNeeded;

			// Check the status in case the service is not stopped. 

			if (!QueryServiceStatusEx(
				schService.get(),                     // handle to service 
				SC_STATUS_PROCESS_INFO,         // information level
				(LPBYTE)&ssStatus,             // address of structure
				sizeof(SERVICE_STATUS_PROCESS), // size of structure
				&dwBytesNeeded))              // size needed if buffer is too small
			{
				//printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
				return false;
			}

			// Check if the service is already running. It would be possible 
			// to stop the service here, but for simplicity this example just returns. 

			if (ssStatus.dwCurrentState != SERVICE_STOPPED && ssStatus.dwCurrentState != SERVICE_STOP_PENDING)
			{
				//printf("Cannot start the service because it is already running\n");
				return false;
			}

			// Save the tick count and initial checkpoint.

			dwStartTickCount = GetTickCount();
			dwOldCheckPoint = ssStatus.dwCheckPoint;

			// Wait for the service to stop before attempting to start it.

			while (ssStatus.dwCurrentState == SERVICE_STOP_PENDING)
			{
				// Do not wait longer than the wait hint. A good interval is 
				// one-tenth of the wait hint but not less than 1 second  
				// and not more than 10 seconds. 

				dwWaitTime = ssStatus.dwWaitHint / 10;

				if (dwWaitTime < 1000)
					dwWaitTime = 1000;
				else if (dwWaitTime > 10000)
					dwWaitTime = 10000;

				Sleep(dwWaitTime);

				// Check the status until the service is no longer stop pending. 

				if (!QueryServiceStatusEx(
					schService.get(),                     // handle to service 
					SC_STATUS_PROCESS_INFO,         // information level
					(LPBYTE)&ssStatus,             // address of structure
					sizeof(SERVICE_STATUS_PROCESS), // size of structure
					&dwBytesNeeded))              // size needed if buffer is too small
				{
					//printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
					return false;
				}

				if (ssStatus.dwCheckPoint > dwOldCheckPoint)
				{
					// Continue to wait and check.

					dwStartTickCount = GetTickCount();
					dwOldCheckPoint = ssStatus.dwCheckPoint;
				}
				else
				{
					if (GetTickCount() - dwStartTickCount > ssStatus.dwWaitHint)
					{
						//printf("Timeout waiting for service to stop\n");
						return false;
					}
				}
			}

			// Attempt to start the service.

			if (!StartService( schService.get(),  0, NULL)) 
			{
				//printf("StartService failed (%d)\n", GetLastError());
				return false;
			}
		//	else printf("Service start pending...\n");

			// Check the status until the service is no longer start pending. 

			if (!QueryServiceStatusEx(
				schService.get(),                     // handle to service 
				SC_STATUS_PROCESS_INFO,         // info level
				(LPBYTE)&ssStatus,             // address of structure
				sizeof(SERVICE_STATUS_PROCESS), // size of structure
				&dwBytesNeeded))              // if buffer too small
			{
				//printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
				return false;
			}

			// Save the tick count and initial checkpoint.

			dwStartTickCount = GetTickCount();
			dwOldCheckPoint = ssStatus.dwCheckPoint;

			while (ssStatus.dwCurrentState == SERVICE_START_PENDING)
			{
				// Do not wait longer than the wait hint. A good interval is 
				// one-tenth the wait hint, but no less than 1 second and no 
				// more than 10 seconds. 

				dwWaitTime = ssStatus.dwWaitHint / 10;

				if (dwWaitTime < 1000)
					dwWaitTime = 1000;
				else if (dwWaitTime > 10000)
					dwWaitTime = 10000;

				Sleep(dwWaitTime);

				// Check the status again. 

				if (!QueryServiceStatusEx(
					schService.get(),             // handle to service 
					SC_STATUS_PROCESS_INFO, // info level
					(LPBYTE)&ssStatus,             // address of structure
					sizeof(SERVICE_STATUS_PROCESS), // size of structure
					&dwBytesNeeded))              // if buffer too small
				{
					//printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
					break;
				}

				if (ssStatus.dwCheckPoint > dwOldCheckPoint)
				{
					// Continue to wait and check.

					dwStartTickCount = GetTickCount();
					dwOldCheckPoint = ssStatus.dwCheckPoint;
				}
				else
				{
					if (GetTickCount() - dwStartTickCount > ssStatus.dwWaitHint)
					{
						// No progress made within the wait hint.
						break;
					}
				}
			}

			// Determine whether the service is running.

			if (ssStatus.dwCurrentState == SERVICE_RUNNING)
			{
				//printf("Service started successfully.\n");
				return true;
			}
			else
			{
		/*		printf("Service not started. \n");
				printf("  Current State: %d\n", ssStatus.dwCurrentState);
				printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode);
				printf("  Check Point: %d\n", ssStatus.dwCheckPoint);
				printf("  Wait Hint: %d\n", ssStatus.dwWaitHint);*/
				return false;
			}
			//return StartService(schService.get(), 0, NULL) == TRUE;
		}
	}
	return false;
}
// 检查开始
int CSDMdlAttrParaSpecifiedValueCheck::CheckAction(void *pData, const CheckRule &checkRule, CheckResult &checkResult)
{
	ProMdl pMdl = (ProMdl)pData;
	if (NULL == pMdl)
	{
		checkResult.nResultType = CHECK_RESULT_INVALID_MODEL;
		return checkResult.nResultType;
	}

	if (!IsMdlTypeValid(pMdl, checkRule.dwMdlFilter))
	{
		checkResult.nResultType = CHECK_RESULT_INVALID_MODEL;
		return checkResult.nResultType;
	}

	// 模型是否符合过滤器要求
	if (!IsFilterValid(checkRule.strRuleName, pMdl))
	{
		checkResult.nResultType = CHECK_RESULT_INVALID_MODEL;
		return checkResult.nResultType;
	}

	// 检查输入值有效性
	if (checkRule.arrRuleContent.GetCount() < 1)
	{
		checkResult.nResultType = CHECK_RESULT_INVALID_INPUT;
		return checkResult.nResultType;
	}

	//-----------------------------------------------------------------------------------

	ProModelitem mdlItem;
	ProMdlToModelitem(pMdl, &mdlItem);

	checkResult.arrErrorItems.RemoveAll();

	// 解析参数
	CStringArray arrItems;
	CStringToCStringArray(checkRule.arrRuleContent[0], arrItems, L";");
	CString strParaName;
	int nParaType;
	CString strParaValue;
	BOOL bDesignation;
	for (int i = 0; i < arrItems.GetSize(); i ++)
	{
		strParaName = arrItems[i].Left(arrItems[i].Find(L"("));
		int nCount = arrItems[i].Find(L")") - arrItems[i].Find(L"(")-1;
		CString strProperty;
		strProperty = arrItems[i].Mid(arrItems[i].Find(L"(") + 1, nCount);
		CStringArray arrPropertys;
		CStringToCStringArray(strProperty, arrPropertys, L",");
		nParaType = _wtoi(arrPropertys[0]);
		strParaValue = arrPropertys[1];
		ParseParaValue(mdlItem, strParaValue, strParaValue);
		bDesignation = _wtoi(arrPropertys[2]);
		
		ProName paraname;
		wcsncpy_s(paraname, PRO_NAME_SIZE, (LPCTSTR)strParaName, _TRUNCATE);
		ProParameter para;

		// 判断参数是否存在
		ErrorItem item;
		item.strItemName = strParaName;
		item.nID = i;
		if (GetSDParameter(&mdlItem, paraname, para))
		{
			// 检查参数类型
			ProParamvalue proval;
			ProParameterValueGet(&para, &proval);
			int nType = GetParaType(proval.type);
			if (nType != nParaType)
			{
				item.nType = PARAERROR_TYPE;
				checkResult.arrErrorItems.Add(item);
			}
			else
			{
				// 检查参数值
				if (PARAM_STRING == nParaType)
				{
					if (strParaValue.Compare(proval.value.s_val) != 0)
					{
						item.nType = PARAERROR_VALUE;
						checkResult.arrErrorItems.Add(item);
						continue;
					}
				}
				else if (PARAM_REAL == nParaType)
				{
					if (!DEQUAL(proval.value.d_val, _wtof(strParaValue)))
					{
						item.nType = PARAERROR_VALUE;
						checkResult.arrErrorItems.Add(item);
						continue;
					}
				}
				else if (PARAM_INTEGER == nParaType)
				{
					if (proval.value.i_val != _wtoi(strParaValue))
					{
						item.nType = PARAERROR_VALUE;
						checkResult.arrErrorItems.Add(item);
						continue;
					}
				}
				else if (PARAM_BOOL == nParaType)
				{
					if (proval.value.l_val != _wtoi(strParaValue))
					{
						item.nType = PARAERROR_VALUE;
						checkResult.arrErrorItems.Add(item);
						continue;
					}
				}
				// 检查是否指定
				ProBoolean designation;
				ProParameterDesignationVerify(&para, &designation);
				if (bDesignation != designation)
				{
					item.nType = PARAERROR_DESIGNATION;
					checkResult.arrErrorItems.Add(item);
				}
			}
		}
		else
		{
			item.nType = PARAERROR_NOEXIST;
			checkResult.arrErrorItems.Add(item);
		}
	}

	if (checkResult.arrErrorItems.GetCount() > 0)
		checkResult.nResultType = CHECK_RESULT_ERROR_VALUE;
	else
		checkResult.nResultType = CHECK_RESULT_NO_ERROR;

	return checkResult.nResultType;
}
Beispiel #29
0
BOOL CALLBACK MsdDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	int port;
	static wchar_t buff[4096] = { 0 };

	switch (uMsg) {
	case WM_INITDIALOG:
	{
		memset(buff, 0, sizeof(buff));
		port = (int)lParam;
		SetWindowLong(hW, GWL_USERDATA, (LONG)lParam);
		CONFIGVARIANT var(N_CONFIG_PATH, CONFIG_TYPE_WCHAR);
		if (LoadSetting(port, APINAME, var))
			wcsncpy_s(buff, var.wstrValue.c_str(), ARRAYSIZE(buff));
		SetWindowTextW(GetDlgItem(hW, IDC_EDIT1), buff);
		return TRUE;
	}
	case WM_CREATE:
		SetWindowLong(hW, GWL_USERDATA, (LONG)lParam);
		break;
	case WM_COMMAND:

		if (HIWORD(wParam) == BN_CLICKED) {
			switch (LOWORD(wParam)) {
			case IDC_BUTTON1:
				ZeroMemory(&ofn, sizeof(ofn));
				ofn.lStructSize = sizeof(ofn);
				ofn.hwndOwner = hW;
				ofn.lpstrTitle = L"USB image file";
				ofn.lpstrFile = buff;
				ofn.nMaxFile = ARRAYSIZE(buff);
				ofn.lpstrFilter = L"All\0*.*\0";
				ofn.nFilterIndex = 1;
				ofn.lpstrFileTitle = NULL;
				ofn.nMaxFileTitle = 0;
				ofn.lpstrInitialDir = NULL;
				ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;

				if (GetOpenFileName(&ofn) == TRUE) {
					SetWindowText(GetDlgItem(hW, IDC_EDIT1), ofn.lpstrFile);
				}
				break;
			case IDOK:
			{
				INT_PTR res = RESULT_OK;
				GetWindowTextW(GetDlgItem(hW, IDC_EDIT1), buff, ARRAYSIZE(buff));
				port = (int)GetWindowLong(hW, GWL_USERDATA);
				CONFIGVARIANT var(N_CONFIG_PATH, CONFIG_TYPE_WCHAR);
				var.wstrValue = buff;
				if (!SaveSetting(port, APINAME, var))
					res = RESULT_FAILED;
				//strcpy_s(conf.usb_img, ofn.lpstrFile);
				EndDialog(hW, res);
				return TRUE;
			}
			case IDCANCEL:
				EndDialog(hW, FALSE);
				return TRUE;
			}
		}
	}
	return FALSE;
}
//-----------------------------------------------------------------------------
static void load_paths_to_watch(LPCTSTR path, HANDLE completion_port_h) {
//-----------------------------------------------------------------------------
    FILE * stream_p;
    wchar_t *get_result;
    HANDLE create_result;
    size_t line_len;
    struct watch_entry **link_p;
    struct watch_entry * next_p;

    if (_wfopen_s(&stream_p, path, L"r, ccs=UTF-8")) {
        _wfopen_s(&error_file, error_path, L"w");
        _wcserror_s(error_buffer, ARRAYSIZE(error_buffer), errno); 
        fwprintf(
            error_file, 
            L"_wfopen(%s) failed: (%d) %s\n",  
            path,
            errno,
            error_buffer 
        );
        fclose(error_file);
        ExitProcess(2);
    }

    link_p = &watch_entry_list_p;
   
    while (1) {

        // create a watch entry
        next_p = (struct watch_entry *) HeapAlloc(
            GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct watch_entry)
        );
		if (next_p == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(200);
			}
        // read in the path to watch from config.txt
        get_result = \
            fgetws(full_file_name, ARRAYSIZE(full_file_name), stream_p);

        if (NULL == get_result) {
            if (0 == ferror(stream_p)) {
                HeapFree(GetProcessHeap(), 0, next_p);
                break;
            } 
            _wfopen_s(&error_file, error_path, L"w");
            _wcserror_s(
               error_buffer, sizeof error_buffer/sizeof(wchar_t) , errno
            ); 
            fwprintf(
                error_file, 
                L"fgetws(%s) failed: (%d) %s\n",  
                path,
                errno,
                error_buffer 
            );
            fclose(error_file);
            ExitProcess(2);
        }

        // clean out the newline, if there is one
        line_len = wcslen(full_file_name);
		if (line_len && full_file_name[line_len-1] == L'\n'){
			full_file_name[line_len-1] = L'\0';
			line_len--;
			}
        if (full_file_name[0] == L'\0')
           continue;
		next_p->dir_path_len = line_len;
		next_p->dir_path = (wchar_t *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			(line_len + 1) * sizeof(wchar_t));
		if (next_p->dir_path == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(201);
		}
		wcsncpy_s(next_p->dir_path, line_len+1, full_file_name, line_len);
		next_p->changes_buffer = (BYTE *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			CHANGES_BUFFER_SIZE);
		if (next_p->changes_buffer == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(202);
		}
        // 2020-09-05 dougfort -- we don't clean out trailing slash here
        // because if they are backing up something like c:\\, we need
        // the trailing slash. This will come back to bite us when we are
        // checking for excludes

        // open a file handle to watch the directory in overlapped mode
        next_p->hDirectory = CreateFile(
            next_p->dir_path,
            FILE_LIST_DIRECTORY,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            NULL,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
            NULL
        );

        // 2009-03-11 dougfort -- if we can't create this file, 
        // assume it is a top-level directory
        // which no longer exists; so ignore it and move on.
        if (INVALID_HANDLE_VALUE == next_p->hDirectory) {
            report_error(L"CreateFile", GetLastError());
            continue;
        }

        // add this file handle to the IO Complete port
        create_result = CreateIoCompletionPort(
            next_p->hDirectory,         // FileHandle,
            completion_port_h,          // ExistingCompletionPort,
            0,                          // CompletionKey,
            0                           // NumberOfConcurrentThreads
        );

        if (NULL == create_result) {
            report_error(L"CreateIOCompletionPort (add)", GetLastError());
            ExitProcess(102);
        }

        if (create_result != completion_port_h) {
            ExitProcess(103);
        }

        start_watch(next_p);

        // add this entry to the list
        *link_p = next_p;

        // point to the new entry's next pointer 
        link_p = &(*link_p)->next_p;
    } // while(1)

    fclose(stream_p);

} // load_paths_to_watch