Exemplo n.º 1
0
BOOL CProcessViewerApp::InitInstance()
{
	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
#if _MSC_VER < 1400
	Enable3dControls();			// Call this when using MFC in a shared DLL
#endif
#else
#if _MSC_VER < 1400
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif
#endif

	if( !IsUserAnAdmin() )
	{
		Utils::ShowWarning( _T( "You are not an administrator, some features won't be accessible!" ));
	}

	ChangeProcessPriority();
	CProcessViewerDlg dlg;
	m_pMainWnd = &dlg;
	dlg.DoModal();
	return FALSE;
}
Exemplo n.º 2
0
bool vmsFdmFilesDeleter::DeleteBrowserPluginFiles(std::vector <std::auto_ptr <vmsBrowserPluginFileDeleter> >& vFiles)
{
	bool bOK = true;
	vmsWinOsVersion osver;

	std::vector <vmsKnownBrowsers::Browser> vPluginsToDeleteElevated;

	for (size_t i = 0; i < vFiles.size (); i++)
	{
		vFiles [i]->setOnDeleteErrorHandler (onBrowserPluginFileDeleteError);

		if (vFiles [i]->DeleteFileEx ())
			continue;

		
		if (vFiles [i]->getErrorType () == vmsFileDeleter::NotEnoughRights && 
			osver.isVistaOrHigher () && !IsUserAnAdmin ())
		{
			vPluginsToDeleteElevated.push_back (vFiles [i]->getBrowser ());
			continue;
		}

		bOK = false;
	}

	if (!vPluginsToDeleteElevated.empty ())
	{
		if (!vmsElevatedFdm::o ().InstallIntegration (vPluginsToDeleteElevated, false, true))
			bOK = false;
	}
	
	return bOK;
}
Exemplo n.º 3
0
/*!
 @brief ユーザ情報の表示
*/
void CUserInfoDlg::ExecUserInfo()
{
	TCHAR szUserName[UNLEN + 1];
	DWORD nUserNameSize = sizeof(szUserName) / sizeof(TCHAR);
	GetUserName(szUserName, &nUserNameSize);
	m_strUserName = szUserName;

	TCHAR szDomainName[DNLEN + 1];
	DWORD nDomainNameSize = sizeof(szDomainName) / sizeof(TCHAR);
	GetComputerNameEx(ComputerNameDnsDomain, szDomainName, & nDomainNameSize);
	m_strDomainName = szDomainName;

	TCHAR szFullUserName[UNLEN + 1];
	ZeroMemory(szFullUserName, sizeof(szFullUserName));
	GetFullName(szUserName, szDomainName, szFullUserName);
	m_strFullUserName = szFullUserName;

	m_bAdminUser = IsUserAnAdmin();

	TCHAR szGroupName[(GNLEN + 1) * 5];
	ZeroMemory(szGroupName, sizeof(szGroupName));
	GetGroupName(szUserName, szGroupName);
	m_strGroupName = szGroupName;	
	m_strGroupName.TrimLeft(_T(','));

	UpdateData(FALSE);
}
Exemplo n.º 4
0
MetroWindow::MetroWindow() :m_pDirect2dFactory(NULL),
m_pRenderTarget(NULL),
m_pMinButtonActiveBrush(NULL),
m_pMetroButtonNsBrush(NULL),
m_pMetroButtonLsBrush(NULL),
m_EdgeViewBrush(NULL),
m_pLightWhiteBrush(NULL),
m_pControlTextBrush(NULL),
m_pDWriteTypography(NULL),
m_pCloseButtonClickBrush(NULL),
m_pWICFactory(NULL),
m_pBitmap(NULL),
m_pBitmapBkg(NULL),
m_pITextFormatTitle(NULL),
m_pITextFormatContent(NULL),
m_pIDWriteFactory(NULL),
IsInvalid(false),
_bMouseTrack(TRUE),
iseThreadID(0),
dwExit(0)
{
	if (IsUserAnAdmin())
	{
		windowTitle = L"Metro USB Drives Boot Manager [";
		windowTitle += MUI::muiController.atString(L"Adm", L"Administrator") + L"]";
	}
	else{
		windowTitle = L"Metro USB Drives Boot Manager";
	}
	Notes =MUI::muiController.atString(L"NoticeInfo", DEFAULT_NOTES);
	if (localeinfo.lcid == 2052)
	{
		FontTabel = 1;
	}
	else{
		FontTabel = 0;
	}
	MTNotices = L"Notices Center:";
	JobStatusRate = L"Task not start";
	ProcessInfo = L"Manager Task Rate:";
	copyright = L"Copyright \xA9 2015 Force Charlie.";
	m_mbFind.bStatus = false;
	m_mbFind.caption =MUI::muiController.atString(L"Discover",L"Discover...");
	m_FixBoot.bStatus = false;
	m_FixBoot.caption = MUI::muiController.atString(L"Fixboot", L"Fix Boot");
	m_Operate.bStatus = false;
	//m_Operate.caption =muiController->m_langmap[L"BMake"];
	m_Operate.caption = MUI::muiController.atString(L"BMake",L"Expand Image");
	USBdrive = MUI::muiController.atString(L"USBdrive", L"USB Drives:");
	ImageFile = MUI::muiController.atString(L"ImageFile", L"Image File:");
	ImageSize = MUI::muiController.atString(L"ImageSize", L"Image Size:");
	Description = MUI::muiController.atString(L"Description", L"Description:");

	normalFont = MUI::muiController.atString(L"NormalFont", L"Segoe UI");
	
}
Exemplo n.º 5
0
UINT CFileAssoc::RunCheckIconsAssocThread(LPVOID pParam)
{
    const CMediaFormats& mf = *(const CMediaFormats*)pParam;

    UINT nLastVersion = AfxGetApp()->GetProfileInt(IDS_R_SETTINGS, IDS_RS_ICON_LIB_VERSION, 0);

    if (LoadIconLib()) {
        UINT nCurrentVersion = GetIconLibVersion();
        SaveIconLibVersion(); // Ensure we don't try to fix the icons more than once

        CAtlList<CString> registeredExts;

        if (nCurrentVersion != nLastVersion && GetAssociatedExtensions(mf, registeredExts)) {
            if (SysVersion::IsVistaOrLater() && !IsUserAnAdmin()) {
                TASKDIALOGCONFIG config = {0};
                config.cbSize = sizeof(config);
                config.hInstance = AfxGetInstanceHandle();
                config.hwndParent = AfxGetApp()->GetMainWnd()->GetSafeHwnd();
                config.dwCommonButtons = TDCBF_YES_BUTTON | TDCBF_NO_BUTTON;
                config.pszMainIcon = TD_SHIELD_ICON;
                config.pszWindowTitle = MAKEINTRESOURCE(IDS_ICONS_REASSOC_DLG_TITLE);
                config.pszMainInstruction = MAKEINTRESOURCE(IDS_ICONS_REASSOC_DLG_INSTR);
                config.pszContent = MAKEINTRESOURCE(IDS_ICONS_REASSOC_DLG_CONTENT);
                config.pfCallback = TaskDialogCallbackProc;

                typedef HRESULT(_stdcall * pfTaskDialogIndirect)(const TASKDIALOGCONFIG*, int*, int*, BOOL*);

                HMODULE hModule = ::LoadLibrary(_T("comctl32.dll"));
                if (hModule) {
                    pfTaskDialogIndirect TaskDialogIndirect = (pfTaskDialogIndirect)(::GetProcAddress(hModule, "TaskDialogIndirect"));

                    if (TaskDialogIndirect) {
                        int nButtonPressed = 0;
                        TaskDialogIndirect(&config, &nButtonPressed, NULL, NULL);

                        if (IDYES == nButtonPressed) {
                            AfxGetMyApp()->RunAsAdministrator(GetProgramPath(true), _T("/iconsassoc"), true);
                        }
                    }

                    ::FreeLibrary(hModule);
                }
            } else {
                ReAssocIcons(registeredExts);

                SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
            }
        }

        FreeIconLib();
    }

    return 0;
}
Exemplo n.º 6
0
static VOID
OnInitDialog(HWND hwndDlg)
{
    /* Initialize the list view control */
    SetListViewColumns(GetDlgItem(hwndDlg, IDC_USERPROFILE_LIST));

    AddUserProfiles(GetDlgItem(hwndDlg, IDC_USERPROFILE_LIST));

    /* Disable the "Delete" and "Copy To" buttons if the user is not an admin */
    if (!IsUserAnAdmin())
    {
         EnableWindow(GetDlgItem(hwndDlg, IDC_USERPROFILE_DELETE), FALSE);
         EnableWindow(GetDlgItem(hwndDlg, IDC_USERPROFILE_COPY), FALSE);
    }
}
int ControlApplication::runConfigurator(bool configService, bool isRunAsRequested)
{
  // If not enough rights to configurate service, then restart application requesting
  // admin access rights.
  if (configService && (IsUserAnAdmin() == FALSE)) {
    // If admin rights already requested and application still don't have them,
    // then show error message and exit.
    if (isRunAsRequested) {
      MessageBox(0,
        StringTable::getString(IDS_ADMIN_RIGHTS_NEEDED),
        StringTable::getString(IDS_MBC_TVNCONTROL),
        MB_OK | MB_ICONERROR);
      return 0;
    }
    // Path to tvnserver binary.
    StringStorage pathToBinary;
    // Command line for child process.
    StringStorage childCommandLine;

    // Get path to tvnserver binary.
    Environment::getCurrentModulePath(&pathToBinary);
    // Set -dontelevate flag to tvncontrol know that admin rights already requested.
    childCommandLine.format(_T("%s -dontelevate"), m_commandLine.getString());

    // Start child.
    try {
      Shell::runAsAdmin(pathToBinary.getString(), childCommandLine.getString());
    } catch (SystemException &sysEx) {
      if (sysEx.getErrorCode() != ERROR_CANCELLED) {
        MessageBox(0,
          sysEx.getMessage(),
          StringTable::getString(IDS_MBC_TVNCONTROL),
          MB_OK | MB_ICONERROR);
      }
      return 1;
    } // try / catch.
    return 0;
  }

  Configurator *configurator = Configurator::getInstance();

  configurator->setServiceFlag(configService);
  configurator->load();

  ConfigDialog confDialog(configService, 0);

  return confDialog.showModal();
}
Exemplo n.º 8
0
BOOL GetProcessElevation(TOKEN_ELEVATION_TYPE* pElevationType, BOOL* pIsAdmin) {

   HANDLE hToken = NULL;
   DWORD dwSize; 

   // Get current process token
   if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
      return(FALSE);

   BOOL bResult = FALSE;

   // Retrieve elevation type information 
   if (GetTokenInformation(hToken, TokenElevationType, 
      pElevationType, sizeof(TOKEN_ELEVATION_TYPE), &dwSize)) {
      // Create the SID corresponding to the Administrators group
      byte adminSID[SECURITY_MAX_SID_SIZE];
      dwSize = sizeof(adminSID);
      CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, &adminSID, 
         &dwSize);

      if (*pElevationType == TokenElevationTypeLimited) {
         // Get handle to linked token (will have one if we are lua)
         HANDLE hUnfilteredToken = NULL;
         GetTokenInformation(hToken, TokenLinkedToken, (VOID*) 
            &hUnfilteredToken, sizeof(HANDLE), &dwSize);

         // Check if this original token contains admin SID
         if (CheckTokenMembership(hUnfilteredToken, &adminSID, pIsAdmin)) {
            bResult = TRUE;
         }

         // Don't forget to close the unfiltered token
         CloseHandle(hUnfilteredToken);
      } else {
         *pIsAdmin = IsUserAnAdmin();
         bResult = TRUE;
      }
   }

   // Don't forget to close the process token
   CloseHandle(hToken);

   return(bResult);
}
Exemplo n.º 9
0
static BOOL
InitMainWnd(PMAIN_WND_INFO Info)
{
    if (!pCreateToolbar(Info))
    {
        DisplayString(_T("error creating toolbar"));
        return FALSE;
    }

    if (!CreateListView(Info))
    {
        DisplayString(_T("error creating list view"));
        return FALSE;
    }

    if (!CreateStatusBar(Info))
        DisplayString(_T("error creating status bar"));

    /* Create Popup Menu */
    Info->hShortcutMenu = LoadMenu(hInstance,
                                   MAKEINTRESOURCE(IDR_POPUP));

    Info->bIsUserAnAdmin = IsUserAnAdmin();
    if (Info->bIsUserAnAdmin)
    {
        HMENU hMainMenu = GetMenu(Info->hMainWnd);

        SendMessage(Info->hTool,
                    TB_SETSTATE,
                    ID_CREATE,
                    (LPARAM)MAKELONG(TBSTATE_ENABLED, 0));
        if (hMainMenu)
        {
            EnableMenuItem(hMainMenu,
                           ID_CREATE,
                           MF_ENABLED);
        }
        EnableMenuItem(GetSubMenu(Info->hShortcutMenu, 0),
                       ID_CREATE,
                       MF_ENABLED);
    }

    return TRUE;
}
Exemplo n.º 10
0
bool IsAdmin()
{
	typedef BOOL (WINAPI *_IsUserAnAdmin)(void);

	_IsUserAnAdmin IsUserAnAdmin = NULL;
	
	HINSTANCE hDll = LoadLibrary(_T("shell32.dll"));
				  
	if (hDll != NULL)
	{
		IsUserAnAdmin = (_IsUserAnAdmin)GetProcAddress(hDll, "IsUserAnAdmin");

		if (IsUserAnAdmin == NULL)
			IsUserAnAdmin = (_IsUserAnAdmin)GetProcAddress(hDll, (LPCSTR)0x02A8);

		if (IsUserAnAdmin != NULL)
			return IsUserAnAdmin() ? true : false;
	}
	return true;
}
Exemplo n.º 11
0
int ControlApplication::checkServicePasswords(bool isRunAsRequested)
{
  // FIXME: code duplication.
  if (IsUserAnAdmin() == FALSE) {
    // If admin rights already requested and application still don't have them,
    // then show error message and exit.
    if (isRunAsRequested) {
      MessageBox(0,
        StringTable::getString(IDS_ADMIN_RIGHTS_NEEDED),
        StringTable::getString(IDS_MBC_TVNCONTROL),
        MB_OK | MB_ICONERROR);
      return 1;
    }
    // Path to tvnserver binary.
    StringStorage pathToBinary;
    // Command line for child process.
    StringStorage childCommandLine;

    // Get path to tvnserver binary.
    Environment::getCurrentModulePath(&pathToBinary);
    // Set -dontelevate flag to tvncontrol know that admin rights already requested.
    childCommandLine.format(_T("%s -dontelevate"), m_commandLine.getString());

    // Start child.
    try {
      Shell::runAsAdmin(pathToBinary.getString(), childCommandLine.getString());
      return 0;
    } catch (SystemException &sysEx) {
      if (sysEx.getErrorCode() != ERROR_CANCELLED) {
        MessageBox(0,
          sysEx.getMessage(),
          StringTable::getString(IDS_MBC_TVNCONTROL),
          MB_OK | MB_ICONERROR);
      }
      return 1;
    } // try / catch.
    return 0;
  }
  checkServicePasswords();
  return 0;
}
Exemplo n.º 12
0
CPPageFormats::CPPageFormats()
:	m_exts(_T(""))
	, m_iRtspHandler(0)
	, m_fRtspFileExtFirst(FALSE)
	, m_bInsufficientPrivileges(FALSE)
{
	if (AfxGetMyApp()->IsVista() && !IsUserAnAdmin())
	{
		
		m_bInsufficientPrivileges = true;
	}

	//TODO: detetc language setting and change  g_strRegisteredAppName  g_strRegisteredKey
	AppSettings& s = AfxGetAppSettings();
	if(!s.bIsChineseUIUser()){
		g_strRegisteredAppName = _T("SPlayer") ;
		g_strRegisteredKey	= _T("Software\\Clients\\Media\\SPlayer\\Capabilities");
	
	}
	
}
Exemplo n.º 13
0
    void App::_StartUi()
    {
        // start ui
        eggs(_ui.Start());

        // add menu
        _ui.AddMenu();

        // add menu break
        _ui.AddMenuBreak();

        // add run-as-administrator option if not already admin
        if( !IsUserAnAdmin() )
            _ui.AddMenuOption(MENU_OPTION_RUNASADMIN, APP_MENU_STRINGS[MENU_OPTION_RUNASADMIN], false);
        // add start-with-windows option
        _ui.AddMenuOption(MENU_OPTION_AUTOSTART, APP_MENU_STRINGS[MENU_OPTION_AUTOSTART], _settings.GetBoolean(SETTING_AUTOSTART));
        // add about dialog
        _ui.AddMenuOption(MENU_OPTION_ABOUT, APP_MENU_STRINGS[MENU_OPTION_ABOUT], false);

        // register events
        _ui.AddListener(*this);
    }
Exemplo n.º 14
0
/*--------------------------------------------------------------------------------*/
BOOL	CStorageSerial::QuerySystemStorage(LPTSTR Volume,PULONG DeviceNumber)
{
	BOOL	Result = FALSE;
	HANDLE	FileHandle = INVALID_HANDLE_VALUE;
	ULONG	NumberOfReturnBytes = 0;
	TCHAR	DeviceName[64] = {0};
	STORAGE_DEVICE_NUMBER	StorageDeviceNumber = {0};

	if(IsUserAnAdmin())
	{
		_stprintf_s(DeviceName,sizeof(DeviceName)/sizeof(TCHAR),_T("\\\\.\\%s"),Volume);
		FileHandle = CreateFile(DeviceName,
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ | FILE_SHARE_WRITE,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,NULL);
		if(FileHandle != INVALID_HANDLE_VALUE)
		{
			Result = DeviceIoControl(FileHandle,
				IOCTL_STORAGE_GET_DEVICE_NUMBER,
				NULL,
				0,
				&StorageDeviceNumber,
				sizeof(StorageDeviceNumber),
				&NumberOfReturnBytes,
				NULL);
			if(Result)
			{
				*DeviceNumber = StorageDeviceNumber.DeviceNumber;
			}
			CloseHandle(FileHandle);
		}
	}
	return	(Result);
}
Exemplo n.º 15
0
int main(int argc, char**argv)
#endif
{
#if defined WIN32
#ifndef _DEBUG
    CreateMutexA(0, FALSE, "Local\\Domoticz");
    if(GetLastError() == ERROR_ALREADY_EXISTS) {
        MessageBox(HWND_DESKTOP,"Another instance of Domoticz is already running!","Domoticz",MB_OK);
        return 1;
    }
#endif //_DEBUG
    bool bStartWebBrowser = true;
    RedirectIOToConsole();
#endif //WIN32

    szStartupFolder = "";
    szWWWFolder = "";
    szWebRoot = "";

    CCmdLine cmdLine;

    // parse argc,argv
#if defined WIN32
    cmdLine.SplitLine(__argc, __argv);
#else
    cmdLine.SplitLine(argc, argv);
    //ignore pipe errors
    signal(SIGPIPE, SIG_IGN);
#endif

    if (cmdLine.HasSwitch("-log"))
    {
        if (cmdLine.GetArgumentCount("-log") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify an output log file");
            return 1;
        }
        logfile = cmdLine.GetSafeArgument("-log", 0, "domoticz.log");
        _log.SetOutputFile(logfile.c_str());
    }
    if (cmdLine.HasSwitch("-loglevel"))
    {
        if (cmdLine.GetArgumentCount("-loglevel") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify logfile output level (0=All, 1=Status+Error, 2=Error)");
            return 1;
        }
        int Level = atoi(cmdLine.GetSafeArgument("-loglevel", 0, "").c_str());
        _log.SetVerboseLevel((_eLogFileVerboseLevel)Level);
    }
    if (cmdLine.HasSwitch("-notimestamps"))
    {
        _log.EnableLogTimestamps(false);
    }

    if (cmdLine.HasSwitch("-approot"))
    {
        if (cmdLine.GetArgumentCount("-approot") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a APP root path");
            return 1;
        }
        std::string szroot = cmdLine.GetSafeArgument("-approot", 0, "");
        if (szroot.size() != 0)
            szStartupFolder = szroot;
    }

    if (szStartupFolder == "")
    {
#if !defined WIN32
        char szStartupPath[255];
        getExecutablePathName((char*)&szStartupPath,255);
        szStartupFolder=szStartupPath;
        if (szStartupFolder.find_last_of('/')!=std::string::npos)
            szStartupFolder=szStartupFolder.substr(0,szStartupFolder.find_last_of('/')+1);
#else
#ifndef _DEBUG
        char szStartupPath[255];
        char * p;
        GetModuleFileName(NULL, szStartupPath, sizeof(szStartupPath));
        p = szStartupPath + strlen(szStartupPath);

        while (p >= szStartupPath && *p != '\\')
            p--;

        if (++p >= szStartupPath)
            *p = 0;
        szStartupFolder=szStartupPath;
        size_t start_pos = szStartupFolder.find("\\Release\\");
        if(start_pos != std::string::npos) {
            szStartupFolder.replace(start_pos, 9, "\\domoticz\\");
            _log.Log(LOG_STATUS,"%s",szStartupFolder.c_str());
        }
#endif
#endif
    }
    GetAppVersion();
    _log.Log(LOG_STATUS, "Domoticz V%s (c)2012-%d GizMoCuz", szAppVersion.c_str(), ActYear);
    _log.Log(LOG_STATUS, "Build Hash: %s, Date: %s", szAppHash.c_str(), szAppDate.c_str());

#if !defined WIN32
    //Check if we are running on a RaspberryPi
    std::string sLine = "";
    std::ifstream infile;

    infile.open("/proc/cpuinfo");
    if (infile.is_open())
    {
        while (!infile.eof())
        {
            getline(infile, sLine);
            if (
                (sLine.find("BCM2708")!=std::string::npos)||
                (sLine.find("BCM2709")!=std::string::npos)
            )
            {
                //Core temperature of BCM2835 SoC
                _log.Log(LOG_STATUS,"System: Raspberry Pi");
                szInternalTemperatureCommand="/opt/vc/bin/vcgencmd measure_temp";
                bHasInternalTemperature=true;
                break;
            }
        }
        infile.close();
    }
    if (!bHasInternalTemperature)
    {
        if (file_exist("/sys/devices/platform/sunxi-i2c.0/i2c-0/0-0034/temp1_input"))
        {
            _log.Log(LOG_STATUS,"System: Cubieboard/Cubietruck");
            szInternalTemperatureCommand="cat /sys/devices/platform/sunxi-i2c.0/i2c-0/0-0034/temp1_input | awk '{ printf (\"temp=%0.2f\\n\",$1/1000); }'";
            bHasInternalTemperature = true;
        }
        else if (file_exist("/sys/devices/virtual/thermal/thermal_zone0/temp"))
        {
            //_log.Log(LOG_STATUS,"System: ODroid");
            szInternalTemperatureCommand="cat /sys/devices/virtual/thermal/thermal_zone0/temp | awk '{ printf (\"temp=%0.2f\\n\",$1/1000); }'";
            bHasInternalTemperature = true;
        }
    }
    if (file_exist("/sys/class/power_supply/ac/voltage_now"))
    {
        szInternalVoltageCommand = "cat /sys/class/power_supply/ac/voltage_now | awk '{ printf (\"volt=%0.2f\\n\",$1/1000000); }'";
        bHasInternalVoltage = true;
    }
    if (file_exist("/sys/class/power_supply/ac/current_now"))
    {
        szInternalCurrentCommand = "cat /sys/class/power_supply/ac/current_now | awk '{ printf (\"curr=%0.2f\\n\",$1/1000000); }'";
        bHasInternalCurrent = true;
    }
    _log.Log(LOG_STATUS,"Startup Path: %s", szStartupFolder.c_str());
#endif

    szWWWFolder = szStartupFolder + "www";

    if ((cmdLine.HasSwitch("-h")) || (cmdLine.HasSwitch("--help")) || (cmdLine.HasSwitch("/?")))
    {
        _log.Log(LOG_NORM, szHelp);
        return 0;
    }

    szUserDataFolder=szStartupFolder;
    if (cmdLine.HasSwitch("-userdata"))
    {
        if (cmdLine.GetArgumentCount("-userdata") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a path for user data to be stored");
            return 1;
        }
        std::string szroot = cmdLine.GetSafeArgument("-userdata", 0, "");
        if (szroot.size() != 0)
            szUserDataFolder = szroot;
    }

    if (cmdLine.HasSwitch("-startupdelay"))
    {
        if (cmdLine.GetArgumentCount("-startupdelay") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a startupdelay");
            return 1;
        }
        int DelaySeconds = atoi(cmdLine.GetSafeArgument("-startupdelay", 0, "").c_str());
        _log.Log(LOG_STATUS, "Startup delay... waiting %d seconds...", DelaySeconds);
        sleep_seconds(DelaySeconds);
    }

    if (cmdLine.HasSwitch("-wwwbind"))
    {
        if (cmdLine.GetArgumentCount("-wwwbind") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify an address");
            return 1;
        }
        std::string wwwbind = cmdLine.GetSafeArgument("-wwwbind", 0, "0.0.0.0");
        m_mainworker.SetWebserverAddress(wwwbind);
    }

    if (cmdLine.HasSwitch("-www"))
    {
        if (cmdLine.GetArgumentCount("-www") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a port");
            return 1;
        }
        std::string wwwport = cmdLine.GetSafeArgument("-www", 0, "8080");
        if (wwwport == "0")
            wwwport.clear();//HTTP server disabled
        m_mainworker.SetWebserverPort(wwwport);
    }
#ifdef NS_ENABLE_SSL
    if (cmdLine.HasSwitch("-sslwww"))
    {
        if (cmdLine.GetArgumentCount("-sslwww") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a port");
            return 1;
        }
        std::string wwwport = cmdLine.GetSafeArgument("-sslwww", 0, "443");
        if (wwwport == "0")
            wwwport.clear();//HTTPS server disabled
        m_mainworker.SetSecureWebserverPort(wwwport);
    }
    if (cmdLine.HasSwitch("-sslcert"))
    {
        if (cmdLine.GetArgumentCount("-sslcert") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify the file path");
            return 1;
        }
        std::string ca_cert = cmdLine.GetSafeArgument("-sslcert", 0, "./server_cert.pem");
        m_mainworker.SetSecureWebserverCert(ca_cert);
    }
    if (cmdLine.HasSwitch("-sslpass"))
    {
        if (cmdLine.GetArgumentCount("-sslpass") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a passphrase for your certificate file");
            return 1;
        }
        std::string ca_passphrase = cmdLine.GetSafeArgument("-sslpass", 0, "");
        m_mainworker.SetSecureWebserverPass(ca_passphrase);
    }
#endif
    if (cmdLine.HasSwitch("-nowwwpwd"))
    {
        m_mainworker.m_bIgnoreUsernamePassword = true;
    }
    if (cmdLine.HasSwitch("-nocache"))
    {
        g_bDontCacheWWW = true;
    }
    std::string dbasefile = szUserDataFolder + "domoticz.db";
#ifdef WIN32
#ifndef _DEBUG
    if (!IsUserAnAdmin())
    {
        char szPath[MAX_PATH];
        HRESULT hr = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
        if (SUCCEEDED(hr))
        {
            std::string sPath = szPath;
            sPath += "\\Domoticz";

            DWORD dwAttr = GetFileAttributes(sPath.c_str());
            BOOL bDirExists = (dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY));
            if (!bDirExists)
            {
                BOOL bRet = CreateDirectory(sPath.c_str(), NULL);
                if (bRet == FALSE) {
                    MessageBox(0, "Error creating Domoticz directory in program data folder (%ProgramData%)!!", "Error:", MB_OK);
                }
            }
            sPath += "\\domoticz.db";
            dbasefile = sPath;
        }
    }
#endif
#endif

    if (cmdLine.HasSwitch("-dbase"))
    {
        if (cmdLine.GetArgumentCount("-dbase") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a Database Name");
            return 1;
        }
        dbasefile = cmdLine.GetSafeArgument("-dbase", 0, "domoticz.db");
    }
    m_sql.SetDatabaseName(dbasefile);

    if (cmdLine.HasSwitch("-wwwroot"))
    {
        if (cmdLine.GetArgumentCount("-wwwroot") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a WWW root path");
            return 1;
        }
        std::string szroot = cmdLine.GetSafeArgument("-wwwroot", 0, "");
        if (szroot.size() != 0)
            szWWWFolder = szroot;
    }

    if (cmdLine.HasSwitch("-webroot"))
    {
        if (cmdLine.GetArgumentCount("-webroot") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a web root path");
            return 1;
        }
        std::string szroot = cmdLine.GetSafeArgument("-webroot", 0, "");
        if (szroot.size() != 0)
            szWebRoot = szroot;
    }

    if (cmdLine.HasSwitch("-verbose"))
    {
        if (cmdLine.GetArgumentCount("-verbose") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a verbose level");
            return 1;
        }
        int Level = atoi(cmdLine.GetSafeArgument("-verbose", 0, "").c_str());
        m_mainworker.SetVerboseLevel((eVerboseLevel)Level);
    }
#if defined WIN32
    if (cmdLine.HasSwitch("-nobrowser"))
    {
        bStartWebBrowser = false;
    }
    //Init WinSock
    WSADATA data;
    WORD version;

    version = (MAKEWORD(2, 2));
    int ret = WSAStartup(version, &data);
    if (ret != 0)
    {
        ret = WSAGetLastError();

        if (ret == WSANOTINITIALISED)
        {
            _log.Log(LOG_ERROR, "Error: Winsock could not be initialized!");
        }
    }
    CoInitializeEx(0, COINIT_MULTITHREADED);
    CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
#endif
#ifndef WIN32
    if (cmdLine.HasSwitch("-daemon"))
    {
        g_bRunAsDaemon = true;
    }

    std::string daemonname = DAEMON_NAME;
    if (cmdLine.HasSwitch("-daemonname"))
    {
        daemonname = cmdLine.GetSafeArgument("-daemonname", 0, DAEMON_NAME);
    }

    std::string pidfile = PID_FILE;
    if (cmdLine.HasSwitch("-pidfile"))
    {
        pidfile = cmdLine.GetSafeArgument("-pidfile", 0, PID_FILE);
    }

    if ((g_bRunAsDaemon)||(g_bUseSyslog))
    {
        setlogmask(LOG_UPTO(LOG_INFO));
        openlog(daemonname.c_str(), LOG_CONS | LOG_PERROR, LOG_USER);

        syslog(LOG_INFO, "Domoticz is starting up....");
    }

    if (g_bRunAsDaemon)
    {
        /* Deamonize */
        daemonize(szStartupFolder.c_str(), pidfile.c_str());
    }
    if ((g_bRunAsDaemon) || (g_bUseSyslog))
    {
        syslog(LOG_INFO, "Domoticz running...");
    }
#endif

    if (!g_bRunAsDaemon)
    {
        signal(SIGINT, signal_handler);
        signal(SIGTERM, signal_handler);
    }

    if (!m_mainworker.Start())
    {
        return 1;
    }
    m_StartTime = time(NULL);

    /* now, lets get into an infinite loop of doing nothing. */
#if defined WIN32
#ifndef _DEBUG
    RedirectIOToConsole();	//hide console
#endif
    InitWindowsHelper(hInstance, hPrevInstance, nShowCmd, m_mainworker.GetWebserverAddress(), atoi(m_mainworker.GetWebserverPort().c_str()), bStartWebBrowser);
    MSG Msg;
    while (!g_bStopApplication)
    {
        if (PeekMessage(&Msg, NULL, 0, 0, PM_NOREMOVE))
        {
            if (GetMessage(&Msg, NULL, 0, 0) > 0)
            {
                TranslateMessage(&Msg);
                DispatchMessage(&Msg);
            }
        }
        else
            sleep_milliseconds(100);
    }
    TrayMessage(NIM_DELETE, NULL);
#else
    while ( !g_bStopApplication )
    {
        sleep_seconds(1);
    }
#endif
    _log.Log(LOG_STATUS, "Closing application!...");
    fflush(stdout);
    _log.Log(LOG_STATUS, "Stopping worker...");
    try
    {
        m_mainworker.Stop();
    }
    catch (...)
    {

    }
#ifndef WIN32
    if (g_bRunAsDaemon)
    {
        syslog(LOG_INFO, "Domoticz stopped...");
        daemonShutdown();

        // Delete PID file
        remove(pidfile.c_str());
    }
#else
    // Release WinSock
    WSACleanup();
    CoUninitialize();
#endif
    return 0;
}
Exemplo n.º 16
0
int main(int argc, char**argv)
#endif
{
#if defined WIN32
	CreateMutexA(0, FALSE, "Local\\Domoticz"); 
    if(GetLastError() == ERROR_ALREADY_EXISTS) { 
		MessageBox(HWND_DESKTOP,"Another instance of Domoticz is already running!","Domoticz",MB_OK);
        return -1; 
	}
	bool bStartWebBrowser=true;
	RedirectIOToConsole();
#endif

	szStartupFolder="";
	szWWWFolder="";
#if !defined WIN32
	char szStartupPath[255];
	getExecutablePathName((char*)&szStartupPath,255);
	szStartupFolder=szStartupPath;
	if (szStartupFolder.find_last_of('/')!=std::string::npos)
		szStartupFolder=szStartupFolder.substr(0,szStartupFolder.find_last_of('/')+1);
#else
	#ifndef _DEBUG
		char szStartupPath[255];
		char * p;
		GetModuleFileName(NULL, szStartupPath, sizeof(szStartupPath));
		p = szStartupPath + strlen(szStartupPath);

		while(p >= szStartupPath && *p != '\\')
			p--;

		if(++p >= szStartupPath)
			*p = 0;
		szStartupFolder=szStartupPath;
		size_t start_pos = szStartupFolder.find("\\Release\\");
		if(start_pos != std::string::npos) {
			szStartupFolder.replace(start_pos, 9, "\\domoticz\\");
			_log.Log(LOG_NORM,"%s",szStartupFolder.c_str());
		}
	#endif
#endif
	GetAppVersion();
	_log.Log(LOG_NORM,"Domoticz V%s (c)2012-2014 GizMoCuz",szAppVersion.c_str());

#if !defined WIN32
	//Check if we are running on a RaspberryPi
	std::string sLine = "";
	std::ifstream infile;

	infile.open("/proc/cpuinfo");
	if (infile.is_open())
	{
		while (!infile.eof())
		{
			getline(infile, sLine);
			if (sLine.find("BCM2708")!=std::string::npos)
			{
				_log.Log(LOG_NORM,"System: Raspberry Pi");
				bIsRaspberryPi=true;
				break;
			}
		}
		infile.close();
	}
	_log.Log(LOG_NORM,"Startup Path: %s", szStartupFolder.c_str());
#endif

	szWWWFolder=szStartupFolder+"www";

	CCmdLine cmdLine;

	// parse argc,argv 
#if defined WIN32
	cmdLine.SplitLine(__argc, __argv);
#else
	cmdLine.SplitLine(argc, argv);
#endif

	if ((cmdLine.HasSwitch("-h"))||(cmdLine.HasSwitch("--help"))||(cmdLine.HasSwitch("/?")))
	{
		_log.Log(LOG_NORM,szHelp);
		return 0;
	}

	if (cmdLine.HasSwitch("-startupdelay"))
	{
		if (cmdLine.GetArgumentCount("-startupdelay")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a startupdelay");
			return 0;
		}
		int DelaySeconds=atoi(cmdLine.GetSafeArgument("-startupdelay",0,"").c_str());
		_log.Log(LOG_NORM,"Startup delay... waiting %d seconds...",DelaySeconds);
		sleep_seconds(DelaySeconds);
	}

	if (cmdLine.HasSwitch("-www"))
	{
		if (cmdLine.GetArgumentCount("-www")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a port");
			return 0;
		}
		std::string wwwport=cmdLine.GetSafeArgument("-www",0,"8080");
		_mainworker.SetWebserverPort(wwwport);
	}
	if (cmdLine.HasSwitch("-nowwwpwd"))
	{
		_mainworker.m_bIgnoreUsernamePassword=true;
	}

	std::string dbasefile=szStartupFolder + "domoticz.db";
#ifdef WIN32
	if (!IsUserAnAdmin())
	{
		char szPath[MAX_PATH];
		HRESULT hr = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
		if (SUCCEEDED(hr))
		{
			std::string sPath=szPath;
			sPath+="\\Domoticz";

			DWORD dwAttr = GetFileAttributes(sPath.c_str());
			BOOL bDirExists=(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY));
			if (!bDirExists)
			{
				BOOL bRet=CreateDirectory(sPath.c_str(),NULL);
				if (bRet==FALSE) {
					MessageBox(0,"Error creating Domoticz directory in program data folder (%ProgramData%)!!","Error:",MB_OK);
				}
			}
			sPath+="\\domoticz.db";
			dbasefile=sPath;
		}
	}
#endif

	if (cmdLine.HasSwitch("-dbase"))
	{
		if (cmdLine.GetArgumentCount("-dbase")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a Database Name");
			return 0;
		}
		dbasefile=cmdLine.GetSafeArgument("-dbase",0,"domoticz.db");
	}
	_mainworker.m_sql.SetDatabaseName(dbasefile);

	if (cmdLine.HasSwitch("-wwwroot"))
	{
		if (cmdLine.GetArgumentCount("-wwwroot")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a WWW root path");
			return 0;
		}
		std::string szroot=cmdLine.GetSafeArgument("-wwwroot",0,"");
		if (szroot.size()!=0)
			szWWWFolder=szroot;
	}

	if (cmdLine.HasSwitch("-verbose"))
	{
		if (cmdLine.GetArgumentCount("-verbose")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a verbose level");
			return 0;
		}
		int Level=atoi(cmdLine.GetSafeArgument("-verbose",0,"").c_str());
		_mainworker.SetVerboseLevel((eVerboseLevel)Level);
	}
#if defined WIN32
	if (cmdLine.HasSwitch("-nobrowser"))
	{
		bStartWebBrowser=false;
	}
#endif
	if (cmdLine.HasSwitch("-log"))
	{
		if (cmdLine.GetArgumentCount("-log")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify an output log file");
			return 0;
		}
		std::string logfile=cmdLine.GetSafeArgument("-log",0,"domoticz.log");
		_log.SetOutputFile(logfile.c_str());
	}

	if (!_mainworker.Start())
	{
		return 0;
	}

	signal(SIGINT, catch_intterm); 
	signal(SIGTERM,catch_intterm);
	
	/* now, lets get into an infinite loop of doing nothing. */

#if defined WIN32
#ifndef _DEBUG
	RedirectIOToConsole();	//hide console
#endif
	InitWindowsHelper(hInstance,hPrevInstance,nShowCmd,DQuitFunction,atoi(_mainworker.GetWebserverPort().c_str()),bStartWebBrowser);
	MSG Msg;
	while(GetMessage(&Msg, NULL, 0, 0) > 0)
	{
		TranslateMessage(&Msg);
		DispatchMessage(&Msg);
	}
#else
	for ( ;; )
		sleep_seconds(1);
#endif
	return 0;
}
Exemplo n.º 17
0
/**************************************************************************
 * IsUserAdmin [SETUPAPI.@]
 *
 * Checks whether the current user is a member of the Administrators group.
 *
 * PARAMS
 *     None
 *
 * RETURNS
 *     Success: TRUE
 *     Failure: FALSE
 */
BOOL WINAPI IsUserAdmin(VOID)
{
    TRACE("\n");
    return IsUserAnAdmin();
}
Exemplo n.º 18
0
int __cdecl wmain(int argc, PWCHAR argv[]) {
  size_t i;
  WCHAR fileName[MAX_PATH];
  WCHAR driverFullPath[MAX_PATH] = {0};
  PVOID wow64OldValue;
  BOOL isAdmin;

  isAdmin = IsUserAnAdmin();

  DokanUseStdErr(TRUE); // Set dokan library debug output

  Wow64DisableWow64FsRedirection(&wow64OldValue); // Disable system32 direct
  // setlocale(LC_ALL, "");

  GetModuleFileName(NULL, fileName, MAX_PATH);

  // search the last "\"
  for (i = wcslen(fileName) - 1; i > 0 && fileName[i] != L'\\'; --i) {
    ;
  }
  fileName[i] = L'\0';

  ExpandEnvironmentStringsW(DOKAN_DRIVER_FULL_PATH, driverFullPath, MAX_PATH);

  fwprintf(stdout, L"Driver path: '%s'\n", driverFullPath);

  WCHAR option = GetOption(argc, argv, 1);
  if (option == L'\0' || option == L'?') {
    return ShowUsage();
  }

  if (!isAdmin &&
      (option == L'i' || option == L'r' || option == L'd' || option == L'u')) {
    fprintf(stderr, "Admin rights required to process this operation\n");
    return EXIT_FAILURE;
  }

  switch (option) {
  // Admin rights required
  case L'i': {
    WCHAR type = towlower(argv[2][0]);
    if (type == L'd') {
      return InstallDriver(driverFullPath);
    } else if (type == L'n') {
      if (DokanNetworkProviderInstall())
        fprintf(stdout, "network provider install ok\n");
      else
        fprintf(stderr, "network provider install failed\n");
    } else {
      goto DEFAULT;
    }
  } break;

  case L'r': {
    WCHAR type = towlower(argv[2][0]);
    if (type == L'd') {
      return DeleteDokanService(DOKAN_DRIVER_SERVICE);
    } else if (type == L'n') {
      if (DokanNetworkProviderUninstall())
        fprintf(stdout, "network provider remove ok\n");
      else
        fprintf(stderr, "network provider remove failed\n");
    } else {
      goto DEFAULT;
    }
  } break;

  case L'd': {
    WCHAR type = towlower(argv[2][0]);
    if (L'0' > type || type > L'9')
      goto DEFAULT;

    ULONG mode = type - L'0';
    if (DokanSetDebugMode(mode)) {
      fprintf(stdout, "set debug mode ok\n");
    } else {
      fprintf(stderr, "set debug mode failed\n");
    }
  } break;

  case L'u': {
    if (argc < 3) {
      goto DEFAULT;
    }
    return Unmount(argv[2]);
  } break;

  // No admin rights required
  case L'l': {
    ULONG nbRead = 0;
    PDOKAN_CONTROL dokanControl =
        malloc(DOKAN_MAX_INSTANCES * sizeof(*dokanControl));
    if (dokanControl == NULL) {
      fprintf(stderr, "Failed to allocate dokanControl\n");
      return EXIT_FAILURE;
    }

    ZeroMemory(dokanControl, DOKAN_MAX_INSTANCES * sizeof(*dokanControl));
    if (DokanGetMountPointList(dokanControl, DOKAN_MAX_INSTANCES, FALSE,
                               &nbRead)) {
      fwprintf(stdout, L"  Mount points: %d\n", nbRead);
      for (unsigned int p = 0; p < nbRead; ++p) {
        fwprintf(stdout, L"  %u# MountPoint: %s - UNC: %s - DeviceName: %s\n",
                 p, dokanControl[p].MountPoint, dokanControl[p].UNCName,
                 dokanControl[p].DeviceName);
      }
    } else {
      fwprintf(stderr, L"  Cannot retrieve mount point list.\n");
    }
    free(dokanControl);
  } break;

  case L'v': {
    fprintf(stdout, "dokanctl : %s %s\n", __DATE__, __TIME__);
    fprintf(stdout, "Dokan version : %d\n", DokanVersion());
    fprintf(stdout, "Dokan driver version : 0x%lx\n", DokanDriverVersion());
  } break;

  DEFAULT:
  default:
    fprintf(stderr, "Unknown option - Use /? to show usage\n");
  }

  return EXIT_SUCCESS;
}
Exemplo n.º 19
0
BOOL Dlg_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) 
{   
   chSETDLGICONS(hwnd, IDI_PROCESSINFO);

   /* Is set to TRUE if the Administrator privileges 
    * are available; either because running elevated
    * or simply because UAC has been disabled.
	*/
   BOOL bCanReadSystemProcesses = FALSE;

   /* Show if we are running with filtered token or not */
   if (GetProcessElevation(&s_elevationType, &s_bIsAdmin)) 
   {
      /* prefix title with elevation */
      TCHAR szTitle[64];

      switch(s_elevationType) 
	  {
         /* Default user or UAC is disabled */
         case TokenElevationTypeDefault:  
            if (IsUserAnAdmin()) 
			{
               _tcscpy_s(
				   szTitle, 
				   _countof(szTitle), 
                   TEXT("Default Administrator: ")); 
               bCanReadSystemProcesses = true;
            } 
			else 
			{
               _tcscpy_s(
				   szTitle, 
				   _countof(szTitle), 
                   TEXT("Default: ")); 
            }
         break;
         /* Process has been successfully elevated */
         case TokenElevationTypeFull:
            if (IsUserAnAdmin()) 
			{
               _tcscpy_s(
				   szTitle, 
				   _countof(szTitle), 
                   TEXT("Elevated Administrator: ")); 
               bCanReadSystemProcesses = true;
            } 
			else 
			{
               _tcscpy_s(
				   szTitle, 
				   _countof(szTitle), 
                   TEXT("Elevated: ")); 
            }
         break;
         /* Process is running with limited privileges */
         case TokenElevationTypeLimited:
            if (s_bIsAdmin) 
			{
               _tcscpy_s(
				   szTitle, 
				   _countof(szTitle), 
                   TEXT("Filtered Administrator: ")); 
            } 
			else 
			{
               _tcscpy_s(
				   szTitle, 
				   _countof(szTitle), 
                   TEXT("Filtered: ")); 
            }
         break;
      }

      /* Update the dialog title based on the elevation level */
      GetWindowText(
		  hwnd, 
		  _tcschr(szTitle, TEXT('\0')), 
         _countof(szTitle) - _tcslen(szTitle));
      SetWindowText(hwnd, szTitle);

      /* Add the "shield" icon if needed to allow the user
       * to restart the application with elevated privileges
	   */
      if (!bCanReadSystemProcesses) 
	  {
         Button_SetElevationRequiredState(
            GetDlgItem(hwnd, IDC_BTN_SYSTEM_PROCESSES), 
               !bCanReadSystemProcesses);
      } 
	  else 
	  {
         /* No need to show the button... */
         ShowWindow(GetDlgItem(hwnd, IDC_BTN_SYSTEM_PROCESSES), SW_HIDE);
         
         /* ... and the combo-box can take the whole width of the dialog box */
         MoveWindow(GetDlgItem(hwnd, IDC_BTN_SYSTEM_PROCESSES), 
            0, 0, 0, 0, FALSE);
      }
   }
   
   /* Hide the module-helper listbox. */
   ShowWindow(GetDlgItem(hwnd, IDC_MODULEHELP), SW_HIDE);

   /* Have the results window use a fixed-pitch font */
   SetWindowFont(
	   GetDlgItem(hwnd, IDC_RESULTS), 
       GetStockFont(ANSI_FIXED_FONT), 
	   FALSE);

   /* By default, show the running processes */
   Dlg_PopulateProcessList(hwnd);

   return(TRUE);
}
Exemplo n.º 20
0
void add_self_to_firewall(void)
{
	if(!IsUserAnAdmin())
	{
		log_printf(LOG_ERROR, "Cannot add firewall exception, not running as an administrator");
		return;
	}
	
	CoInitialize(NULL);
	
	/* We need to go deeper. */
	
	INetFwMgr *fw_mgr;
	HRESULT err = CoCreateInstance(&CLSID_NetFwMgr_s, NULL, CLSCTX_INPROC_SERVER, &IID_INetFwMgr_s, (void**)(&fw_mgr));
	if(err == S_OK)
	{
		INetFwPolicy *fw_policy;
		if((err = INetFwMgr_get_LocalPolicy(fw_mgr, &fw_policy)) == S_OK)
		{
			INetFwProfile *fw_profile;
			if((err = INetFwPolicy_get_CurrentProfile(fw_policy, &fw_profile)) == S_OK)
			{
				INetFwAuthorizedApplications *fw_apps;
				if((err = INetFwProfile_get_AuthorizedApplications(fw_profile, &fw_apps)) == S_OK)
				{
					/* Create an instance of INetFwAuthorizedApplication and
					 * put the current executable in it.
					*/
					
					INetFwAuthorizedApplication *this_exe;
					if((err = CoCreateInstance(&CLSID_NetFwAuthorizedApplication_s, NULL, CLSCTX_INPROC_SERVER, &IID_INetFwAuthorizedApplication_s, (void**)(&this_exe))) == S_OK)
					{
						if(_fill_this_exe(this_exe))
						{
							/* Add the new INetFwAuthorizedApplication
							 * to the active profile.
							*/
							
							if((err = INetFwAuthorizedApplications_Add(fw_apps, this_exe)) != S_OK)
							{
								log_printf(LOG_ERROR, "Could not add firewall exception (error %u)", (unsigned int)(err));
							}
						}
						
						INetFwAuthorizedApplication_Release(this_exe);
					}
					else{
						log_printf(LOG_ERROR, "Could not create INetFwAuthorizedApplication (error %u)", (unsigned int)(err));
					}
					
					INetFwAuthorizedApplications_Release(fw_apps);
				}
				else{
					log_printf(LOG_ERROR, "Could not get INetFwAuthorizedApplications object (error %u)", (unsigned int)(err));
				}
				
				INetFwProfile_Release(fw_profile);
			}
			else{
				log_printf(LOG_ERROR, "Could not get INetFwProfile object (error %u)", (unsigned int)(err));
			}
			
			INetFwPolicy_Release(fw_policy);
		}
		else{
			log_printf(LOG_ERROR, "Could not get INetFwPolicy object (error %u)", (unsigned int)(err));
		}
		
		INetFwMgr_Release(fw_mgr);
	}
	else{
		log_printf(LOG_ERROR, "Could not create INetFwMgr object (error %u)", (unsigned int)(err));
	}
	
	CoUninitialize();
}
Exemplo n.º 21
0
int __cdecl _tmain(int argc, _TCHAR *argv[])
{
	HDEVINFO h = NULL;
	SP_DEVINFO_DATA dev_info_data;
	ULONG status = 0, problem = 0;
	BOOL bDevice = FALSE;

	if (IsWow64()) {
		logPrint("Your are runing 32bit VirtualMonitor on 64bit windows\n");
		logPrint("Please Download 64bit version of VirtualMonitor\n");
		return -1;
	}
	if (argc < 2 || !strcmp(argv[1], "-h")) {
		usage(argv);
		goto out;
	}

	GetWinVersion();
	if (!isSupport) {
		logPrint("Unsupported Windows system\n");
		goto out;
	}
	if (isVista || isWin7) {
		if (!IsUserAnAdmin()) {
			logPrint("Access Denied. Administrator permissions are needed to use the selected options.");
			logPrint("Use an administrator command prompt to complete these tasks.");
			goto out;
		}
	}

	if (!strcmp(argv[1], "-i")) {
		FixInfFile(INF);
	}
	h = GetDevInfoFromDeviceId(&dev_info_data, DRIVER_NAME);
	if (!strcmp(argv[1], "-i")) {
		if (h) {
			logPrint("Driver already installed\n");
			goto out;
		}
		if (!logInit()) {
			goto out;
		}
		logPrint("Installing driver, It may take few minutes. please wait\n");
		RegClean();
		InstallInf(INF);
		if (isVista || isWin7) {
			DisableMirror();
		}
		h = GetDevInfoFromDeviceId(&dev_info_data, DRIVER_NAME);
		if (!h) {
			logError("GetDevInfo Failed After Driver Installed\n");
		}
		GetDevStatus(h, &dev_info_data, &status, &problem);
		bDevice = DetectVirtualMonitor(FALSE);
		logInfo("Driver Status: %x, problem: %x\n", status, problem);
		if (!bDevice) {
			DetectVirtualMonitor(TRUE);
			logPrint("Driver installed Status: %x, problem: %x\n", status, problem);
			logPrint("Please reboot your system\n");
		} else {
			logPrint("Driver installed successful\n");
		}
		if (isVista || isWin7) {
			logPrint("Please reboot your system\n");
		}
	} else if (!strcmp(argv[1], "-u")) {
		if (!h) {
			logPrint("Driver not found\n");
		} else {
			if (!logInit()) {
				goto out;
			}
			UnInstallDriver(h, &dev_info_data);
			if (isVista || isWin7) {
				CleanOemInf();
			}
			RegClean();
			logPrint("Driver Uninstalled sucessful, Please Reboot System\n");
		}
	} else {
		usage(argv);
		goto out;
	}
out:
	if (g_logf)
		fclose(g_logf);
	if (h) {
			DestroyDevInfo(h);
	}
	exit(0);
}
Exemplo n.º 22
0
BOOL CPPageFormats::OnInitDialog()
{
    __super::OnInitDialog();

    m_list.SetExtendedStyle(m_list.GetExtendedStyle() | LVS_EX_FULLROWSELECT);

    m_list.InsertColumn(COL_CATEGORY, _T("Category"), LVCFMT_LEFT, 290);
    m_list.InsertColumn(COL_ENGINE, _T("Engine"), LVCFMT_RIGHT, 50);

    // We don't use m_onoff.Create(IDB_CHECKBOX, 12, 3, 0xffffff) since
    // we want to load the bitmap directly from the main executable.
    CImage onoff;
    onoff.LoadFromResource(AfxGetInstanceHandle(), IDB_CHECKBOX);
    m_onoff.Create(12, 12, ILC_COLOR4 | ILC_MASK, 0, 3);
    m_onoff.Add(CBitmap::FromHandle(onoff), 0xffffff);
    m_list.SetImageList(&m_onoff, LVSIL_SMALL);

    LoadSettings();
    CreateToolTip();

    SetButtonIcon(IDC_ASSOCIATE_ALL_FORMATS,   IDB_CHECK_ALL);
    SetButtonIcon(IDC_ASSOCIATE_AUDIO_FORMATS, IDB_CHECK_AUDIO);
    SetButtonIcon(IDC_ASSOCIATE_VIDEO_FORMATS, IDB_CHECK_VIDEO);
    SetButtonIcon(IDC_CLEAR_ALL_ASSOCIATIONS,  IDB_UNCHECK_ALL);

    if (SysVersion::IsVistaOrLater() && !IsUserAnAdmin()) {
        GetDlgItem(IDC_EDIT1)->EnableWindow(FALSE);
        GetDlgItem(IDC_ASSOCIATE_ALL_FORMATS)->EnableWindow(FALSE);
        GetDlgItem(IDC_ASSOCIATE_AUDIO_FORMATS)->EnableWindow(FALSE);
        GetDlgItem(IDC_ASSOCIATE_VIDEO_FORMATS)->EnableWindow(FALSE);
        GetDlgItem(IDC_CLEAR_ALL_ASSOCIATIONS)->EnableWindow(FALSE);

        GetDlgItem(IDC_CHECK1)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK2)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK3)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK4)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK5)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK6)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK7)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK8)->ShowWindow(SW_HIDE);

        GetDlgItem(IDC_RADIO1)->EnableWindow(FALSE);
        GetDlgItem(IDC_RADIO2)->EnableWindow(FALSE);
        GetDlgItem(IDC_RADIO3)->EnableWindow(FALSE);

        GetDlgItem(IDC_BUTTON1)->SendMessage(BCM_SETSHIELD, 0, TRUE);
        GetDlgItem(IDC_BUTTON1)->ShowWindow(SW_SHOW);

        m_bInsufficientPrivileges = true;
    } else {
        GetDlgItem(IDC_BUTTON1)->ShowWindow(SW_HIDE);
    }

    if (SysVersion::Is8OrLater()) {
        GetDlgItem(IDC_BUTTON7)->ShowWindow(SW_SHOW);

        auto offsetControlBottomRight = [this](int nID, int dx, int dy) {
            CRect r;
            GetDlgItem(nID)->GetWindowRect(r);
            ScreenToClient(r);
            r.BottomRight().Offset(dx, dy);
            GetDlgItem(nID)->MoveWindow(r);
        };

        auto moveControl = [this](int nID, int dx, int dy) {
            CRect r;
            GetDlgItem(nID)->GetWindowRect(r);
            ScreenToClient(r);
            r.OffsetRect(dx, dy);
            GetDlgItem(nID)->MoveWindow(r);
        };

        const int dy = DpiHelper().ScaleY(-5); // TODO: use the helper from parent dialog

        offsetControlBottomRight(IDC_STATIC2, 0, dy);
        offsetControlBottomRight(IDC_LIST1, 0, dy);

        moveControl(IDC_EDIT1, 0, dy);
        moveControl(IDC_BUTTON2, 0, dy);
        moveControl(IDC_BUTTON_EXT_SET, 0, dy);

        CRect r;
        GetDlgItem(IDC_STATIC3)->GetWindowRect(r);
        ScreenToClient(r);
        r.TopLeft().Offset(0, dy);
        GetDlgItem(IDC_STATIC3)->MoveWindow(r);

        moveControl(IDC_CHECK8, 0, dy);
        moveControl(IDC_BUTTON1, 0, dy);
    } else {
        GetDlgItem(IDC_BUTTON7)->ShowWindow(SW_HIDE);
    }

    UpdateData(FALSE);

    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}
Exemplo n.º 23
0
BOOL MainWindow::IsAdmin() const
{
    return IsUserAnAdmin();
}
Exemplo n.º 24
0
BOOL CPPageFormats::OnInitDialog()
{
	__super::OnInitDialog();

	m_list.SetExtendedStyle(m_list.GetExtendedStyle()|LVS_EX_FULLROWSELECT);

	m_list.InsertColumn(COL_CATEGORY, _T("Category"), LVCFMT_LEFT, 300);
	m_list.InsertColumn(COL_ENGINE, _T("Engine"), LVCFMT_RIGHT, 60);

	m_onoff.Create(IDB_ONOFF, 12, 3, 0xffffff);
	m_list.SetImageList(&m_onoff, LVSIL_SMALL);

	CMediaFormats& mf = AfxGetAppSettings().Formats;
	mf.UpdateData(FALSE);
	for(int i = 0; i < (int)mf.GetCount(); i++)
	{
		CString label;
		label.Format (_T("%s (%s)"), mf[i].GetLabel(), mf[i].GetExts());

		int iItem = m_list.InsertItem(i, label);
		m_list.SetItemData(iItem, i);
		engine_t e = mf[i].GetEngineType();
		m_list.SetItemText(iItem, COL_ENGINE,
						   e == DirectShow ? _T("DirectShow") :
						   e == RealMedia ? _T("RealMedia") :
						   e == QuickTime ? _T("QuickTime") :
						   e == ShockWave ? _T("ShockWave") : _T("-"));
	}

//	m_list.SetColumnWidth(COL_CATEGORY, LVSCW_AUTOSIZE);
	m_list.SetColumnWidth(COL_ENGINE, LVSCW_AUTOSIZE_USEHEADER);

	m_list.SetSelectionMark(0);
	m_list.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);
	m_exts = mf[(int)m_list.GetItemData(0)].GetExtsWithPeriod();

	AppSettings& s = AfxGetAppSettings();
	bool fRtspFileExtFirst;
	engine_t e = s.Formats.GetRtspHandler(fRtspFileExtFirst);
	m_iRtspHandler = (e==RealMedia?0:e==QuickTime?1:2);
	m_fRtspFileExtFirst = fRtspFileExtFirst;

	UpdateData(FALSE);

	f_setContextFiles = 0;

	for(int i = 0; i < m_list.GetItemCount(); i++)
	{
		SetListItemState(i);
	}
	m_fContextFiles.SetCheck(f_setContextFiles);

	if(AfxGetAppSettings().fXpOrBetter)
	{
		m_apvideo.SetCheck(IsAutoPlayRegistered(AP_VIDEO));
		m_apmusic.SetCheck(IsAutoPlayRegistered(AP_MUSIC));
		m_apaudiocd.SetCheck(IsAutoPlayRegistered(AP_AUDIOCD));
		m_apdvd.SetCheck(IsAutoPlayRegistered(AP_DVDMOVIE));
	}
	else
	{
		m_autoplay.ShowWindow(SW_HIDE);
		m_apvideo.ShowWindow(SW_HIDE);
		m_apmusic.ShowWindow(SW_HIDE);
		m_apaudiocd.ShowWindow(SW_HIDE);
		m_apdvd.ShowWindow(SW_HIDE);
	}

	CreateToolTip();


	if (IsVistaOrAbove() && !IsUserAnAdmin())
	{
		GetDlgItem(IDC_BUTTON1)->ShowWindow (SW_HIDE);
		GetDlgItem(IDC_BUTTON3)->ShowWindow (SW_HIDE);
		GetDlgItem(IDC_BUTTON4)->ShowWindow (SW_HIDE);
		GetDlgItem(IDC_CHECK1)->EnableWindow (FALSE);
		GetDlgItem(IDC_CHECK2)->EnableWindow (FALSE);
		GetDlgItem(IDC_CHECK3)->EnableWindow (FALSE);
		GetDlgItem(IDC_CHECK4)->EnableWindow (FALSE);
		GetDlgItem(IDC_CHECK5)->EnableWindow (FALSE);

		GetDlgItem(IDC_RADIO1)->EnableWindow (FALSE);
		GetDlgItem(IDC_RADIO2)->EnableWindow (FALSE);
		GetDlgItem(IDC_RADIO3)->EnableWindow (FALSE);

		GetDlgItem(IDC_BUTTON5)->ShowWindow (SW_SHOW);
		GetDlgItem(IDC_BUTTON5)->SendMessage (BCM_SETSHIELD, 0, 1);

		m_bInsufficientPrivileges = true;
	}
	else
		GetDlgItem(IDC_BUTTON5)->ShowWindow (SW_HIDE);


	CRegKey		key;
	TCHAR		buff[_MAX_PATH];
	ULONG		len = sizeof(buff);

	int fContextDir = 0;
	if(ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Directory\\shell\\mplayerc.play\\command"), KEY_READ))
	{
		CString		strCommand = GetOpenCommand();
		if (ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len))
			fContextDir = (strCommand.CompareNoCase(CString(buff)) == 0);
	}
	m_fContextDir.SetCheck(fContextDir);
	m_fAssociatedWithIcons.SetCheck(s.fAssociatedWithIcons);

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}
Exemplo n.º 25
0
INT_PTR CALLBACK ConnDlgProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	switch( Msg ) {
	case WM_INITDIALOG:
		{
			HWND hList = GetDlgItem(hWnd, IDC_CONNLIST);

			ListView_SetExtendedListViewStyle(hList, LVS_EX_FULLROWSELECT);
			LV_COLUMN lvc = { 0 };
			lvc.mask = LVCF_TEXT|LVCF_FMT|LVCF_WIDTH;
			lvc.fmt = LVCFMT_LEFT;
			lvc.cx = 40;
			lvc.pszText = _T("ID");
			ListView_InsertColumn(hList, 0, &lvc);
			lvc.cx = 50;
			lvc.pszText = TranslateT("User");
			ListView_InsertColumn(hList, 1, &lvc);
			lvc.cx = 250;
			lvc.pszText = TranslateT("File");
			ListView_InsertColumn(hList, 2, &lvc);
			lvc.cx = 50;
			lvc.pszText = TranslateT("Access");
			ListView_InsertColumn(hList, 3, &lvc);
			KillTimer(NULL, 777);
			lst = cpy_list(&list);
			if (IsUserAnAdmin())
				SetTimer(NULL, 777, TIME, TimerProc);
			else
				MessageBox(NULL, TranslateT("Plugin WhoUsesMyFiles requires admin privileges in order to work."), _T("Miranda NG"), MB_OK);
			ShowList(lst, hList);
		}
		Utils_RestoreWindowPosition(hWnd, NULL, MODULENAME,"conn");
		return TRUE;

	case WM_CLOSE:
		PostMessage( hWnd, WM_COMMAND, IDCANCEL, 0l );
		break;

	case WM_COMMAND:
		switch( LOWORD(wParam)) {
		case IDOK:
		case IDCANCEL:
			PostMessage(hWnd, WM_DESTROY, 0, 0);
			break;
		}
		break;

	case WM_SIZE:
		{
			UTILRESIZEDIALOG urd = { sizeof(urd) };
			urd.hwndDlg = hWnd;
			urd.hInstance = hInst;
			urd.lpTemplate = MAKEINTRESOURCEA(IDD_CONNLIST);
			urd.lParam = (LPARAM)NULL;
			urd.pfnResizer = DlgResizer;
			CallService(MS_UTILS_RESIZEDIALOG, 0, (LPARAM)&urd);
		}
		Utils_SaveWindowPosition(hWnd, NULL, MODULENAME,"conn");
		return TRUE;

	case WM_MOVE:
		Utils_SaveWindowPosition(hWnd, NULL, MODULENAME,"conn");
		break;

	case WM_NOTIFY:
		switch (((LPNMHDR) lParam)->code) { 
		case LVN_GETDISPINFO: 
			OnGetDispInfo((NMLVDISPINFO*)lParam); 
			break; 
		}
		break;

	case WM_DESTROY:
		del_all(&lst);
		PostQuitMessage(0);
		break;
	}
	return FALSE;
}
Exemplo n.º 26
0
BOOL CPPageFormats::OnInitDialog()
{
    __super::OnInitDialog();

    m_bFileExtChanged = false;
    m_bHaveRegisteredCategory = false;

    m_list.SetExtendedStyle(m_list.GetExtendedStyle() | LVS_EX_FULLROWSELECT);

    m_list.InsertColumn(COL_CATEGORY, _T("Category"), LVCFMT_LEFT, 300);
    m_list.InsertColumn(COL_ENGINE, _T("Engine"), LVCFMT_RIGHT, 60);

    // We don't use m_onoff.Create(IDB_CHECKBOX, 12, 3, 0xffffff) since
    // we want to load the bitmap directly from the main executable.
    CImage onoff;
    onoff.LoadFromResource(AfxGetInstanceHandle(), IDB_CHECKBOX);
    m_onoff.Create(12, 12, ILC_COLOR4 | ILC_MASK, 0, 3);
    m_onoff.Add(CBitmap::FromHandle(onoff), 0xffffff);
    m_list.SetImageList(&m_onoff, LVSIL_SMALL);

    int fSetContextFiles = FALSE;

    const CAppSettings& s = AfxGetAppSettings();
    m_mf = s.m_Formats;

    for (int i = 0, cnt = (int)m_mf.GetCount(); i < cnt; i++) {
        if (!m_mf[i].IsAssociable()) {
            continue;
        }

        CString label;
        label.Format(_T("%s (%s)"), m_mf[i].GetDescription(), m_mf[i].GetExts());

        int iItem = m_list.InsertItem(i, label);
        m_list.SetItemData(iItem, i);
        engine_t e = m_mf[i].GetEngineType();
        m_list.SetItemText(iItem, COL_ENGINE,
                           e == DirectShow ? _T("DirectShow") :
                           e == RealMedia ? _T("RealMedia") :
                           e == QuickTime ? _T("QuickTime") :
                           e == ShockWave ? _T("ShockWave") : _T("-"));

        CFileAssoc::reg_state_t state = CFileAssoc::IsRegistered(m_mf[i]);
        if (!m_bHaveRegisteredCategory && state != CFileAssoc::NOT_REGISTERED) {
            m_bHaveRegisteredCategory = true;
        }
        SetCheckedMediaCategory(iItem, (state == CFileAssoc::SOME_REGISTERED) ? 2 : (state == CFileAssoc::ALL_REGISTERED));

        if (!fSetContextFiles && CFileAssoc::AreRegisteredFileContextMenuEntries(m_mf[i]) != CFileAssoc::NOT_REGISTERED) {
            fSetContextFiles = TRUE;
        }
    }

    m_list.SetColumnWidth(COL_ENGINE, LVSCW_AUTOSIZE_USEHEADER);

    m_list.SetSelectionMark(0);
    m_list.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);
    m_exts = m_mf[m_list.GetItemData(0)].GetExtsWithPeriod();

    bool fRtspFileExtFirst;
    engine_t e = m_mf.GetRtspHandler(fRtspFileExtFirst);
    m_iRtspHandler = (e == RealMedia ? 0 : e == QuickTime ? 1 : 2);
    m_fRtspFileExtFirst = fRtspFileExtFirst;

    m_fContextFiles.SetCheck(fSetContextFiles);

    m_apvideo.SetCheck(CFileAssoc::IsAutoPlayRegistered(CFileAssoc::AP_VIDEO));
    m_apmusic.SetCheck(CFileAssoc::IsAutoPlayRegistered(CFileAssoc::AP_MUSIC));
    m_apaudiocd.SetCheck(CFileAssoc::IsAutoPlayRegistered(CFileAssoc::AP_AUDIOCD));
    m_apdvd.SetCheck(CFileAssoc::IsAutoPlayRegistered(CFileAssoc::AP_DVDMOVIE));

    CreateToolTip();

    if (SysVersion::IsVistaOrLater() && !IsUserAnAdmin()) {
        GetDlgItem(IDC_BUTTON1)->ShowWindow(SW_HIDE);
        GetDlgItem(IDC_BUTTON3)->ShowWindow(SW_HIDE);
        GetDlgItem(IDC_BUTTON4)->ShowWindow(SW_HIDE);

        GetDlgItem(IDC_EDIT1)->EnableWindow(FALSE);

        GetDlgItem(IDC_CHECK1)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK2)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK3)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK4)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK5)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK6)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK7)->EnableWindow(FALSE);
        GetDlgItem(IDC_CHECK8)->EnableWindow(FALSE);

        GetDlgItem(IDC_RADIO1)->EnableWindow(FALSE);
        GetDlgItem(IDC_RADIO2)->EnableWindow(FALSE);
        GetDlgItem(IDC_RADIO3)->EnableWindow(FALSE);

        GetDlgItem(IDC_BUTTON5)->ShowWindow(SW_SHOW);
        GetDlgItem(IDC_BUTTON5)->SendMessage(BCM_SETSHIELD, 0, 1);

        m_bInsufficientPrivileges = true;
    } else {
        GetDlgItem(IDC_BUTTON5)->ShowWindow(SW_HIDE);
    }

    if (SysVersion::Is8()) {
        CRect r;
        GetDlgItem(IDC_STATIC2)->GetWindowRect(r);
        ScreenToClient(r);
        r.BottomRight().Offset(0, -50);
        GetDlgItem(IDC_STATIC2)->MoveWindow(r);
        GetDlgItem(IDC_LIST1)->GetWindowRect(r);
        ScreenToClient(r);
        r.BottomRight().Offset(0, -50);
        GetDlgItem(IDC_LIST1)->MoveWindow(r);
        GetDlgItem(IDC_EDIT1)->GetWindowRect(r);
        ScreenToClient(r);
        r.OffsetRect(0, -50);
        GetDlgItem(IDC_EDIT1)->MoveWindow(r);
        GetDlgItem(IDC_BUTTON2)->GetWindowRect(r);
        ScreenToClient(r);
        r.OffsetRect(0, -50);
        GetDlgItem(IDC_BUTTON2)->MoveWindow(r);
        GetDlgItem(IDC_BUTTON_EXT_SET)->GetWindowRect(r);
        ScreenToClient(r);
        r.OffsetRect(0, -50);
        GetDlgItem(IDC_BUTTON_EXT_SET)->MoveWindow(r);
    } else {
        GetDlgItem(IDC_STATIC3)->ShowWindow(SW_HIDE);
        GetDlgItem(IDC_BUTTON6)->ShowWindow(SW_HIDE);
    }

    m_fContextDir.SetCheck(CFileAssoc::AreRegisteredFolderContextMenuEntries());
    m_fAssociatedWithIcons.SetCheck(s.fAssociatedWithIcons);

    UpdateData(FALSE);

    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}
Exemplo n.º 27
0
int disk_dump_hex_data(int drive_number, long total_sectors_to_read, LP_PROGRAM_DATA PData)
{
	unsigned int buffer[512];
	char letra;
	DWORD bytes_por_setor;
    char const *unidade = "";
	long long tam_disco;
	int falhas = 0, sector_index;
	FILE *inputFile;
	FILE *outputFile;
	struct conversion_data a1;
	struct conversion_mode a2;
	CONVERSION_DATA StructConv = &a1;
	CONVERSION_MODE StructMode = &a2;
	short res;
	HANDLE DiscoRigido;
    CHAR nome_hd[16], cmdLine[MAX_PATH], localAtual[MAX_PATH], currentFile[MAX_PATH], HexFile2[MAX_PATH], HexFile[MAX_PATH];
	DWORD ptr;
	NTFS_VOLUME_DATA_BUFFER disk_data_buffer;
	DWORD bytesLidos, totalBytesLidos = 0;
	
	letra = convert_disk_number_to_letter(drive_number);
	if(letra == 0) return 0x83;
	
	if(!IsUserAnAdmin()) 
	{	
		msgaviso("You are not admin ... Changing privileges ...\n");
        if(GetCurrentDirectoryA(MAX_PATH, (LPSTR)localAtual))
		{
            sprintf(cmdLine, "%s %s %s %s", PData->command_line[1], PData->command_line[2], PData->command_line[3], PData->command_line[4]);
            sprintf(currentFile, "%s\\hexdumper.exe", localAtual);
            ShellExecuteA(0, "runas", currentFile, cmdLine, (char const *)localAtual, SW_SHOW);
		}
		exit(GetLastError());
	}
	
	sprintf(nome_hd, "\\\\.\\%c:", letra);
	DiscoRigido = CreateFileA( nome_hd, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	
	if(DiscoRigido == INVALID_HANDLE_VALUE) 
		return 0x81;
	
	if(!DeviceIoControl(DiscoRigido, FSCTL_GET_NTFS_VOLUME_DATA, 0, 0, &disk_data_buffer, sizeof(disk_data_buffer), &ptr, NULL))
	{
		if(DiscoRigido) CloseHandle(DiscoRigido);
		return 0x80;
	}
	
	bytes_por_setor = disk_data_buffer.BytesPerSector;
	tam_disco = disk_data_buffer.NumberSectors.QuadPart * disk_data_buffer.BytesPerSector;
	
    unidade = "";

	assert(tam_disco > 0);
	
	if(tam_disco <= _1KB)
		unidade = "Bytes";
	else if(tam_disco <= _1MB) {
		tam_disco /= _1KB;
		unidade = "KB";
	}
	else if(tam_disco <= _1GB) {
		tam_disco /= _1MB;
		unidade = "MB";
	}
	else {
		tam_disco /= _1GB;
		unidade = "GB";
	}
	
	long long conversion_size = total_sectors_to_read * bytes_por_setor;

	if((conversion_size / _1GB) > (0xffffffff / _1GB)) {
		msgerro( "Data bigger than %.2lf GB aren´t supported yet\n", (double)(0xffffffff / _1GB));
		msgerro("Your conversion size is: %.2lf KB\n", (double)conversion_size / _1KB);
		return 0x86;
	}
	
	sprintf(HexFile, "hd%d.txt", drive_number);
	outputFile = fopen(HexFile, "wb");
	assert(outputFile != NULL);
	
	if(PData->verbose) 
	{
		fprintf(stdout, "\n");
		fprintf(stdout, "\t-> Disk size: %.2lf %s\n\t-> Bytes per sector %ld\n", (double)tam_disco, unidade, bytes_por_setor);
		fprintf(stdout, "\t-> Serial number: 0x%.8x\n\t-> MFT start address: 0x%.8x\n", disk_data_buffer.VolumeSerialNumber,
						disk_data_buffer.MftStartLcn);
		fprintf(stdout, "\t-> Number of sectors to read: %ld\n", total_sectors_to_read);
		fprintf(stdout, "\t-> Data length to read: %.2lf KB\n", (double)conversion_size / _1KB);
		fprintf(stdout, "\n");
	}

	if (!DeviceIoControl(DiscoRigido, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &ptr, NULL))
		if(PData->verbose)
			msgaviso( "failed to block volume ...\n");
		
	for(sector_index = 0; sector_index < total_sectors_to_read; sector_index++)
	{
		if(!DiscoRigido || DiscoRigido == INVALID_HANDLE_VALUE) break;
		
		bytesLidos = read_disk_sector(sector_index, bytes_por_setor, buffer, DiscoRigido);
		if(bytesLidos) 
		{
			fwrite(buffer, 1, bytesLidos, outputFile);
			totalBytesLidos += bytesLidos;
		} else {
			falhas++;
			if(falhas > 100)
				break;
		}
	}
	
	if(!DeviceIoControl(DiscoRigido, FSCTL_UNLOCK_VOLUME, 0, 0, NULL, 0, &ptr, NULL)) {
		if(PData->verbose)
			msgaviso( "Failed to unblock volume. Maybe it is already unblocked\n");
	}
	
	if(DiscoRigido) CloseHandle(DiscoRigido);
	if(outputFile) fclose(outputFile); 
	
	if (PData->verbose) {
		msginfo("Converting data to HEX format ...\n");
		msginfo("Opening %s ...\n", HexFile);
	}

	inputFile = fopen(HexFile, "rb");
	sprintf(HexFile2, "dump_of_%s", HexFile);
	
	outputFile = fopen(HexFile2, "wb");
	
	assert(inputFile != NULL);
	assert(outputFile != NULL);
	
	// agora descarregar o arquivo no formato hexadecimal ...
	
	StructConv->bytes_to_read = totalBytesLidos;
	StructMode->s_mode = DEFAULT_MODE;
	
	res = hex_file_write_data_in_specified_mode(StructConv, StructMode, inputFile, outputFile, DEFAULT_MODE);
	if(PData->verbose && res == 0xFF) {
		msgerro( "Cannot make HEX dump ...\n");
	}
	else if(PData->verbose && res == 0) 
		msgsucesso( "Hex dump completed ...\nOutput: %s\n", HexFile2);
	
	if(inputFile) fclose(inputFile);
	if(outputFile) fclose(outputFile);

	return 0;
}
Exemplo n.º 28
0
int WINAPI
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
    WNDCLASSEXW WndClass = {0};
    WCHAR szWindowClass[] = L"ROSAPPMGR";
    WCHAR szWindowName[MAX_STR_LEN];
    WCHAR szErrorText[MAX_STR_LEN];
    HANDLE hMutex = NULL;
    MSG Msg;

    switch (GetUserDefaultUILanguage())
  {
    case MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT):
      SetProcessDefaultLayout(LAYOUT_RTL);
      break;

    default:
      break;
  }

    hInst = hInstance;

    if (!IsUserAnAdmin())
    {
        LoadStringW(hInst, IDS_USER_NOT_ADMIN, szErrorText, sizeof(szErrorText) / sizeof(WCHAR));
        MessageBox(0, szErrorText, NULL, MB_OK | MB_ICONWARNING);
        return 1;
    }

    hMutex = CreateMutexW(NULL, FALSE, szWindowClass);
    if ((!hMutex) || (GetLastError() == ERROR_ALREADY_EXISTS))
    {
        /* If already started, it is found its window */
        HWND hWindow = FindWindowW(szWindowClass, NULL);

        /* Activate window */
        ShowWindow(hWindow, SW_SHOWNORMAL);
        SetForegroundWindow(hWindow);
        return 1;
    }

    if (!LoadSettings())
    {
        FillDefaultSettings(&SettingsInfo);
    }

    InitLogs();

    InitCommonControls();

    /* Create the window */
    WndClass.cbSize        = sizeof(WNDCLASSEXW);
    WndClass.lpszClassName = szWindowClass;
    WndClass.lpfnWndProc   = MainWindowProc;
    WndClass.hInstance     = hInstance;
    WndClass.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MAIN));
    WndClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
    WndClass.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
    WndClass.lpszMenuName  = MAKEINTRESOURCEW(IDR_MAINMENU);

    if (RegisterClassExW(&WndClass) == (ATOM)0) goto Exit;

    LoadStringW(hInst, IDS_APPTITLE, szWindowName, sizeof(szWindowName) / sizeof(WCHAR));

    hMainWnd = CreateWindowExW(WS_EX_WINDOWEDGE,
                               szWindowClass,
                               szWindowName,
                               WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
                               CW_USEDEFAULT,
                               CW_USEDEFAULT,
                               680,
                               450,
                               NULL,
                               NULL,
                               hInstance,
                               NULL);

    if (!hMainWnd) goto Exit;

    /* Show it */
    ShowWindow(hMainWnd, SW_SHOW);
    UpdateWindow(hMainWnd);

    /* Message Loop */
    while (GetMessage(&Msg, NULL, 0, 0))
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

Exit:
    if (hMutex) CloseHandle(hMutex);

    return 0;
}
Exemplo n.º 29
0
static void CheckUpdates(void *)
{
	TCHAR tszBuff[2048] = { 0 }, tszFileInfo[30] = { 0 }, tszTmpIni[MAX_PATH] = { 0 };
	char szKey[64] = { 0 };
	vector<FILEINFO> UpdateFiles;

	if (!Exists(tszRoot))
		CreateDirectory(tszRoot, NULL);
	Files.clear();
	Reminder = db_get_b(NULL, MODNAME, "Reminder", DEFAULT_REMINDER);
	FileCount = db_get_dw(NULL, MODNAME, "FileCount", DEFAULT_FILECOUNT);

	// Load files info
	ptrT tszDownloadURL(db_get_tsa(NULL, MODNAME, "File_VersionURL"));
	if (!tszDownloadURL) { // URL is not set
		Title = TranslateT("Pack Updater");
		Text = TranslateT("URL for checking updates not found.");
		if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups1", DEFAULT_POPUP_ENABLED)) {
			Number = 1;
			show_popup(0, Title, Text, Number, 0);
		}
		else if (db_get_b(NULL, MODNAME, "Popups1M", DEFAULT_MESSAGE_ENABLED))
			MessageBox(NULL, Text, Title, MB_ICONSTOP);
		hCheckThread = NULL;
		return;
	}
	// Download version info
	pFileUrl = (FILEURL *)mir_alloc(sizeof(*pFileUrl));
	mir_tstrncpy(pFileUrl->tszDownloadURL, tszDownloadURL, _countof(pFileUrl->tszDownloadURL));
	mir_sntprintf(tszBuff, _countof(tszBuff), _T("%s\\tmp.ini"), tszRoot);
	mir_tstrncpy(pFileUrl->tszDiskPath, tszBuff, _countof(pFileUrl->tszDiskPath));
	mir_tstrncpy(tszTmpIni, tszBuff, _countof(tszTmpIni));
	Title = TranslateT("Pack Updater");
	Text = TranslateT("Downloading version info...");
	DlgDownloadProc();
	mir_free(pFileUrl);
	if (!DlgDld) {
		hCheckThread = NULL;
		return;
	}

	for (CurrentFile = 0; CurrentFile < FileCount; CurrentFile++) {
		FILEINFO FileInfo = { _T(""), _T(""), _T(""), _T(""), _T(""), _T(""), _T(""), { _T(""), _T("") } };

		mir_snprintf(szKey, _countof(szKey), "File_%d_CurrentVersion", CurrentFile + 1);
		ptrT tszCurVer(db_get_tsa(NULL, MODNAME, szKey));
		if (tszCurVer)
			mir_tstrncpy(FileInfo.tszCurVer, tszCurVer, _countof(FileInfo.tszCurVer));
		else 
			mir_tstrncpy(FileInfo.tszCurVer, _T(""), _countof(FileInfo.tszCurVer));

		mir_snprintf(szKey, _countof(szKey), "File_%d_LastVersion", CurrentFile + 1);
		ptrT tszLastVer(db_get_tsa(NULL, MODNAME, szKey));
		if (tszLastVer)
			mir_tstrncpy(FileInfo.tszLastVer, tszLastVer, _countof(FileInfo.tszLastVer));
		else
			mir_tstrncpy(FileInfo.tszLastVer, _T(""), _countof(FileInfo.tszLastVer));

		Files.push_back(FileInfo);

		// Read version info
		mir_sntprintf(tszFileInfo, _countof(tszFileInfo), _T("FileInfo_%d"), CurrentFile + 1);
		GetPrivateProfileString(tszFileInfo, _T("FileVersion"), _T(""), Files[CurrentFile].tszNewVer, _countof(Files[CurrentFile].tszNewVer), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("Message"), _T(""), Files[CurrentFile].tszMessage, _countof(Files[CurrentFile].tszMessage), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("DownloadURL"), _T(""), Files[CurrentFile].File.tszDownloadURL, _countof(Files[CurrentFile].File.tszDownloadURL), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("AdvFolder"), _T(""), Files[CurrentFile].tszAdvFolder, _countof(Files[CurrentFile].tszAdvFolder), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("Descr"), _T(""), Files[CurrentFile].tszDescr, _countof(Files[CurrentFile].tszDescr), tszTmpIni);
		GetPrivateProfileString(tszFileInfo, _T("DiskFileName"), _T(""), tszBuff, MAX_PATH, tszTmpIni);

		if (_tcsstr(tszBuff, _T("\\"))) { //check update name
			Title = TranslateT("Pack Updater");
			Text = TranslateT("Name of Update's file is not supported.");
			if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups1", DEFAULT_POPUP_ENABLED)) {
				Number = 1;
				show_popup(0, Title, Text, Number, 0);
			}
			else if (db_get_b(NULL, MODNAME, "Popups1M", DEFAULT_MESSAGE_ENABLED))
				MessageBox(NULL, Text, Title, MB_ICONINFORMATION);
			continue;
		} // end check update name
		mir_tstrncpy(Files[CurrentFile].File.tszDiskPath, tszBuff, _countof(Files[CurrentFile].File.tszDiskPath));
		GetPrivateProfileString(tszFileInfo, _T("InfoURL"), _T(""), Files[CurrentFile].tszInfoURL, _countof(Files[CurrentFile].tszInfoURL), tszTmpIni);
		Files[CurrentFile].FileType = GetPrivateProfileInt(tszFileInfo, _T("FileType"), 0, tszTmpIni);
		Files[CurrentFile].Force = GetPrivateProfileInt(tszFileInfo, _T("Force"), 0, tszTmpIni);
		Files[CurrentFile].FileNum = CurrentFile + 1;

		if (Files[CurrentFile].FileType == 2) {
			if (mir_tstrcmp(Files[CurrentFile].tszAdvFolder, _T("")) == 0)
				mir_sntprintf(tszBuff, _countof(tszBuff), _T("Plugins\\%s"), Files[CurrentFile].File.tszDiskPath);
			else
				mir_sntprintf(tszBuff, _countof(tszBuff), _T("Plugins\\%s\\%s"), Files[CurrentFile].tszAdvFolder, Files[CurrentFile].File.tszDiskPath);
			TCHAR pluginFolderName[MAX_PATH];
			PathToAbsoluteT(tszBuff, pluginFolderName);
			if (!Files[CurrentFile].Force && (IsPluginDisabled(Files[CurrentFile].File.tszDiskPath) || !Exists(pluginFolderName))) //check if plugin disabled or not exists
				continue;
		}
		// Compare versions
		if (getVer(Files[CurrentFile].tszCurVer) < getVer(Files[CurrentFile].tszNewVer)) { // Yeah, we've got new version.
			VARST tszSysRoot(_T("%SystemRoot%"));
			VARST tszProgFiles(_T("%ProgramFiles%"));

			if (Files[CurrentFile].FileType != 1 && !IsUserAnAdmin() && (_tcsstr(tszRoot, tszSysRoot) || _tcsstr(tszRoot, tszProgFiles))) {
				MessageBox(NULL, TranslateT("Update is not possible!\nYou have no Administrator's rights.\nPlease run Miranda NG with Administrator's rights."), Title, MB_ICONINFORMATION);
				DeleteFile(tszTmpIni);
				hCheckThread = NULL;
				return;
			} // user have not admin's rights

			//добавить проверку на существование файла
			TCHAR tszFilePathDest[MAX_PATH] = { 0 };
			switch (Files[CurrentFile].FileType) {
			case 0:
			case 1:
				break;
			case 2: {
				VARST tszUtilRootPlug(_T("%miranda_path%\\Plugins"));
				if (mir_tstrcmp(Files[CurrentFile].tszAdvFolder, _T("")) == 0)
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s"), tszUtilRootPlug, Files[CurrentFile].File.tszDiskPath);
				else
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s\\%s"), tszUtilRootPlug, Files[CurrentFile].tszAdvFolder, Files[CurrentFile].File.tszDiskPath);
				}
				break;
			case 3: {
				VARST tszUtilRootIco(_T("%miranda_path%\\Icons"));
				if (mir_tstrcmp(Files[CurrentFile].tszAdvFolder, _T("")) == 0)
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s"), tszUtilRootIco, Files[CurrentFile].File.tszDiskPath);
				else
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s\\%s"), tszUtilRootIco, Files[CurrentFile].tszAdvFolder, Files[CurrentFile].File.tszDiskPath);
				}
				break;
			case 4:
			case 5: {
				VARST tszUtilRoot = Utils_ReplaceVarsT(_T("%miranda_path%"));
				if (mir_tstrcmp(Files[CurrentFile].tszAdvFolder, _T("")) == 0)
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s"), tszUtilRoot, Files[CurrentFile].File.tszDiskPath);
				else
					mir_sntprintf(tszFilePathDest, _countof(tszFilePathDest), _T("%s\\%s\\%s"), tszUtilRoot, Files[CurrentFile].tszAdvFolder, Files[CurrentFile].File.tszDiskPath);
				}
				break;
			}//end* switch (Files[CurrentFile].FileType)

			if (Files[CurrentFile].Force || Exists(tszFilePathDest))
				UpdateFiles.push_back(Files[CurrentFile]);
			// Save last version
			mir_tstrncpy(Files[CurrentFile].tszLastVer, Files[CurrentFile].tszNewVer, _countof(Files[CurrentFile].tszLastVer));
			mir_snprintf(szKey, _countof(szKey), "File_%d_LastVersion", CurrentFile + 1);
			db_set_ts(NULL, MODNAME, szKey, Files[CurrentFile].tszLastVer);
		} // end compare versions
	} //end checking all files in for ()

	// Show dialog
	INT upd_ret = 0;
	if (UpdateFiles.size() > 0)
		upd_ret = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_UPDATE), GetDesktopWindow(), DlgUpdate, (LPARAM)&UpdateFiles);
	DeleteFile(tszTmpIni);
	if (upd_ret == IDCANCEL) {
		hCheckThread = NULL;
		return;
	}

	if (!UpdatesCount && !Silent) {
		Title = TranslateT("Pack Updater");
		Text = TranslateT("No updates found.");
		if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups2", DEFAULT_POPUP_ENABLED)) {
			Number = 2;
			show_popup(0, Title, Text, Number, 0);
		}
		else if (db_get_b(NULL, MODNAME, "Popups2M", DEFAULT_MESSAGE_ENABLED))
			MessageBox(NULL, Text, Title, MB_ICONINFORMATION);
	}

	if (!FileCount) {
		Title = TranslateT("Pack Updater");
		Text = TranslateT("No files for update.");
		if (ServiceExists(MS_POPUP_ADDPOPUPT) && db_get_b(NULL, "Popup", "ModuleIsEnabled", 1) && db_get_b(NULL, MODNAME, "Popups2", DEFAULT_POPUP_ENABLED)) {
			Number = 2;
			show_popup(0, Title, Text, Number, 0);
		}
		else if (db_get_b(NULL, MODNAME, "Popups2M", DEFAULT_MESSAGE_ENABLED))
			MessageBox(NULL, Text, Title, MB_ICONINFORMATION);
	}
	hCheckThread = NULL;
}