예제 #1
0
void SystemInfo::Init()
{
	Subsystem::Init();

	SYSTEM_INFO info;
	GetNativeSystemInfo(&info);
	/// @todo Change rest to use this

	// Computer name
	{
		TCHAR name[MAX_COMPUTERNAME_LENGTH + 1];
		DWORD size = sizeof(name) / sizeof(name[0]);
		GetComputerName(name, &size);
		computerName = name;
	}

	// Username
	{
		TCHAR name[60];
		DWORD size = sizeof(name) / sizeof(name[0]);
		GetUserName(name, &size);
		username = name;
	}

	// Monitor information
	monitor.resolution.x = GetSystemMetrics(SM_CXSCREEN);
	monitor.resolution.y = GetSystemMetrics(SM_CYSCREEN);

	// Operating System
	OSVERSIONINFO verInfo = { sizeof(OSVERSIONINFO) };
	GetVersionEx(&verInfo);
	if(verInfo.dwMajorVersion == 5)
	{
		switch(verInfo.dwMinorVersion)
		{
		case 0:
			OS = "Windows 2000 " + string(verInfo.szCSDVersion);
			break;
		case 1:
			OS = "Windows XP " + string(verInfo.szCSDVersion);
			break;
		case 2:
			OS = "Windows 2003 " + string(verInfo.szCSDVersion);
			break;
		}
	}
	else if(verInfo.dwMajorVersion == 6)
	{
		switch(verInfo.dwMinorVersion)
		{
		case 0:
			OS = "Windows Vista " + string(verInfo.szCSDVersion);
			break;
		case 1:
			OS = "Windows 7 " + string(verInfo.szCSDVersion);
			break;
		case 2:
			OS = "Windows 8 " + string(verInfo.szCSDVersion);
			break;
		}
	}

	// Processor/CPU
	{
		int CPUInfo[4] = { -1};
		__cpuid(CPUInfo, 0x80000000);
		unsigned int nExIds = CPUInfo[0];
		char CPUBrandString[0x40] = { 0 };
		for(uint i = 0x80000000; i < nExIds; ++i)
		{
			__cpuid(CPUInfo, i);

			if(i == 0x80000002)
			{
				memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
			}
			else if(i == 0x80000003)
			{
				memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
			}
			else if(i == 0x80000004)
			{
				memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
			}
		}
		cpu.cores = (typeof(cpu.cores))info.dwNumberOfProcessors;             //(t >> 16) & 0xff;
		cpu.name = CPUBrandString;        //info.dwProcessorType;
	}
	/*
	   HKEY hKey, tempKey;
	   if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,"HARDWARE\\DESCRIPTION\\System\\CentralProcessor",0,KEY_READ,&hKey) == ERROR_SUCCESS)
	   {
	   uint i;
	   while(RegEnumKey(hKey,++i,subKeyName,40) != ERROR_NO_MORE_ITEMS)
	   {
	   if(RegOpenKeyEx(hKey,subKeyName,0,KEY_READ,&tempKey) == ERROR_SUCCESS)
	   {
	   size = 100;
	   if(RegQueryValueEx(tempKey,_T("ProcessorNameString"),NULL,NULL,valBuf,&size) == ERROR_SUCCESS)
	   cpu.name = valBuf;
	   size = 100;
	   if(RegQueryValueEx(tempKey,_T("Identifier"),NULL,NULL,valBuf,&size) == ERROR_SUCCESS)
	   _tprintf(_T(" %s"),valBuf);
	   RegCloseKey(tempKey);
	   }
	   }
	   RegCloseKey(hKey);
	   }*/
	/*
	   // Memory/RAM
	   MEMORYSTATUSEX ms =
	   { sizeof(MEMORYSTATUSEX) };
	   GlobalMemoryStatusEx(&ms);
	   memory = ms.ullTotalPhys / (1024 * 1024.0);

	   // Hard Drives
	   int drives;
	   __int64 nFree, nTotal;
	   TCHAR dName[40], volName[40];

	   uint i = 0;

	   drives = GetLogicalDrives();
	   while (drives != 0)
	   {
			if ((drives & 1) == 1)
			{
					wsprintf(dName, "%c:\\", 'A' + i);
					if (GetDriveType(dName) == DRIVE_FIXED)
					{
							if (GetDiskFreeSpaceEx(dName, (PULARGE_INTEGER)&nFree, (PULARGE_INTEGER)&nTotal, 0) != 0)
							{
									HardDrive hdd;
									hdd.name = dName;
									hdd.free = nFree / (1024 * 1024 * 1024.0);
									hdd.total = nTotal / (1024 * 1024 * 1024.0);
									GetVolumeInformation(dName, 0, 0, 0, 0, 0, volName, 10);
									sprintf("%s", volName);
							}
					}
			}
			drives >>= 1;
	   ++i;
	   }*/
}
예제 #2
0
int getinfo(char mytext[1024])

{                                  
  COSVersion::OS_VERSION_INFO osvi;
  memset(&osvi, 0, sizeof(osvi));
#ifdef _WIN32
  TCHAR sText[512];
  TCHAR sBuf[100];
#else
  char sText[512];
  char sBuf[100];
#endif

  COSVersion os;  
  if (os.GetVersion(&osvi))
  {
  #ifndef UNDER_CE
    _stprintf(sText, _T("OS: "));
    
    switch (osvi.EmulatedPlatform)
    {
      case COSVersion::Dos:               
      {
        _tcscat(sText, _T("DOS"));                
        break;
      }
      case COSVersion::Windows3x:         
      {
        _tcscat(sText, _T("Windows"));        
        if (os.IsWin32sInstalled(&osvi))
          _tcscat(sText, _T(" (Win32s)"));
        break;
      }
      case COSVersion::WindowsCE:
      {
        _tcscat(sText, _T("Windows CE"));        
        break;
      }
      case COSVersion::Windows9x:
      {
        if (os.IsWindows95(&osvi))
          _stprintf(sBuf, _T("Windows 95"));
        else if (os.IsWindows95SP1(&osvi))
          _stprintf(sBuf, _T("Windows 95 SP1"));
        else if (os.IsWindows95OSR2(&osvi))
          _stprintf(sBuf, _T("Windows 95 OSR2"));
        else if (os.IsWindows98(&osvi))
          _stprintf(sBuf, _T("Windows 98"));
        else if (os.IsWindows98SP1(&osvi))
          _stprintf(sBuf, _T("Windows 98 SP1"));
        else if (os.IsWindows98SE(&osvi))
          _stprintf(sBuf, _T("Windows 98 Second Edition"));
        else if (os.IsWindowsME(&osvi))
          _stprintf(sBuf, _T("Windows Millenium Edition"));
        else
          _stprintf(sBuf, _T("Windows ??"));
        _tcscat(sText, sBuf);          
        break;
      }
      case COSVersion::WindowsNT:
      {
        if (os.IsNTPreWin2k(&osvi))
        {
          _tcscat(sText, _T("Windows NT"));          

          if (os.IsNTWorkstation(&osvi))
            _tcscat(sText, _T(" (Workstation)"));
          else if (os.IsNTStandAloneServer(&osvi))
            _tcscat(sText, _T(" (Server)"));
          else if (os.IsNTPDC(&osvi))
            _tcscat(sText, _T(" (Primary Domain Controller)"));
          else if (os.IsNTBDC(&osvi))
            _tcscat(sText, _T(" (Backup Domain Controller)"));

          if (os.IsNTDatacenterServer(&osvi))
            _tcscat(sText, _T(", (Datacenter)"));
          else if (os.IsNTEnterpriseServer(&osvi))
            _tcscat(sText, _T(", (Enterprise)"));
        }
        else if (os.IsWindows2000(&osvi))
        {
          _tcscat(sText, _T("Windows 2000"));          

          if (os.IsWin2000Professional(&osvi))
            _tcscat(sText, _T(" (Professional)"));
          else if (os.IsWin2000Server(&osvi))
            _tcscat(sText, _T(" (Server)"));
          else if (os.IsWin2000DomainController(&osvi))
            _tcscat(sText, _T(" (Domain Controller)"));

          if (os.IsWin2000DatacenterServer(&osvi))
            _tcscat(sText, _T(", (Datacenter)"));
          else if (os.IsWin2000AdvancedServer(&osvi))
            _tcscat(sText, _T(", (Advanced Server)"));
        }
        else if (os.IsWindowsXPOrWindowsServer2003(&osvi))
        {
          if (os.IsXPPersonal(&osvi))
            _tcscat(sText, _T("Windows XP (Personal)"));          
          else if (os.IsXPProfessional(&osvi))
            _tcscat(sText, _T("Windows XP (Professional)"));          
          else if (os.IsWindowsServer2003(&osvi))
            _tcscat(sText, _T("Windows Server 2003"));          
          else if (os.IsDomainControllerWindowsServer2003(&osvi))
            _tcscat(sText, _T("Windows Server 2003 (Domain Controller)"));          

          if (os.IsDatacenterWindowsServer2003(&osvi))
            _tcscat(sText, _T(", (Datacenter Edition)"));
          else if (os.IsEnterpriseWindowsServer2003(&osvi))
            _tcscat(sText, _T(", (Enterprise Edition)"));
          else if (os.IsWebWindowsServer2003(&osvi))
            _tcscat(sText, _T(", (Web Edition)"));
          else if (os.IsWindowsServer2003(&osvi))
            _tcscat(sText, _T(", (Standard Edition)"));
        }

        if (os.IsTerminalServicesInstalled(&osvi))
          _tcscat(sText, _T(", (Terminal Services)"));
        if (os.ISSmallBusinessEditionInstalled(&osvi))
          _tcscat(sText, _T(", (BackOffice Small Business Edition)"));
        if (os.IsEmbedded(&osvi))
          _tcscat(sText, _T(", (Embedded)"));
        if (os.IsTerminalServicesInRemoteAdminMode(&osvi))
          _tcscat(sText, _T(", (Terminal Services in Remote Admin Mode)"));
        if (os.IsEmulated64Bit(&osvi))
          _tcscat(sText, _T(", (64 Bit Edition)"));
        if (os.IsMediaCenterInstalled(&osvi))
          _tcscat(sText, _T(", (Media Center Edition)"));

        if (osvi.dwSuiteMask & COSVERSION_SUITE_UNIPROCESSOR_FREE)
          _tcscat(sText, _T(", (Uniprocessor Free)"));
        else if (osvi.dwSuiteMask & COSVERSION_SUITE_UNIPROCESSOR_CHECKED)
          _tcscat(sText, _T(", (Uniprocessor Checked)"));
        else if (osvi.dwSuiteMask & COSVERSION_SUITE_MULTIPROCESSOR_FREE)
          _tcscat(sText, _T(", (Multiprocessor Free)"));
        else if (osvi.dwSuiteMask & COSVERSION_SUITE_MULTIPROCESSOR_CHECKED)
          _tcscat(sText, _T(", (Multiprocessor Checked)"));

        break;
      }
      default: 
      {
        _stprintf(sBuf, _T("Unknown OS"));
        break;
      }
    }                     

#ifndef UNDER_CE
    switch (osvi.EmulatedProcessorType)
    {
      case COSVersion::INTEL_PROCESSOR:
      {
        _tcscat(sText, _T(", (Intel Processor)"));
        break;
      }
      case COSVersion::MSIL_PROCESSOR:
      {
        _tcscat(sText, _T(", (MSIL Processor)"));
        break;
      }
      case COSVersion::MIPS_PROCESSOR:
      {
        _tcscat(sText, _T(", (MIPS Processor)"));
        break;
      }
      case COSVersion::ARM_PROCESSOR:
      {
        _tcscat(sText, _T(", (ARM Processor)"));
        break;
      }
      case COSVersion::SHX_PROCESSOR:
      {
        _tcscat(sText, _T(", (SHX Processor)"));
        break;
      }
      case COSVersion::ALPHA_PROCESSOR:
      {
        _tcscat(sText, _T(", (Alpha Processor)"));
        break;
      }
      case COSVersion::ALPHA64_PROCESSOR:
      {
        _tcscat(sText, _T(", (Alpha64 Processor)"));
        break;
      }
      case COSVersion::PPC_PROCESSOR:
      {
        _tcscat(sText, _T(", (PPC Processor)"));
        break;
      }
      case COSVersion::IA64_PROCESSOR:
      {
        _tcscat(sText, _T(", (IA64 Processor)"));
        break;
      }
      case COSVersion::AMD64_PROCESSOR:
      {
        _tcscat(sText, _T(", (AMD64 Processor)"));
        break;
      }
      case COSVersion::UNKNOWN_PROCESSOR: //deliberate fallthrough
      default:
      {
        _tcscat(sText, _T(", (Unknown Processor)"));
        break;
      }
    }
#endif

    _stprintf(sBuf, _T(" v%d."), osvi.dwEmulatedMajorVersion);
    _tcscat(sText, sBuf);     
    if (osvi.dwEmulatedMinorVersion % 10)
    {
      if (osvi.dwEmulatedMinorVersion > 9)
        _stprintf(sBuf, _T("%02d"), osvi.dwEmulatedMinorVersion);
      else
        _stprintf(sBuf, _T("%01d"), osvi.dwEmulatedMinorVersion);
    }
    else
      _stprintf(sBuf, _T("%01d"), osvi.dwEmulatedMinorVersion / 10);
    _tcscat(sText, sBuf);                           
    if (osvi.dwEmulatedBuildNumber)
    {
      _stprintf(sBuf, _T(" Build:%d"), osvi.dwEmulatedBuildNumber);
      _tcscat(sText, sBuf);           
    }
    if (osvi.wEmulatedServicePackMajor)       
    {
      if (osvi.wEmulatedServicePackMinor)
      {
        //Handle the special case of NT 4 SP 6a which Dtwinver ver treats as SP 6.1
        if (os.IsNTPreWin2k(&osvi) && (osvi.wEmulatedServicePackMajor == 6) && (osvi.wEmulatedServicePackMinor == 1))
          _stprintf(sBuf, _T(" Service Pack: 6a"));
        //Handle the special case of XP SP 1a which Dtwinver ver treats as SP 1.1
        else if (os.IsWindowsXP(&osvi) && (osvi.wEmulatedServicePackMajor == 1) && (osvi.wEmulatedServicePackMinor == 1))
          _stprintf(sBuf, _T(" Service Pack: 1a"));
        else       
          _stprintf(sBuf, _T(" Service Pack:%d.%d"), osvi.wEmulatedServicePackMajor, osvi.wEmulatedServicePackMinor);
      }
      else
        _stprintf(sBuf, _T(" Service Pack:%d"), osvi.wEmulatedServicePackMajor);
      _tcscat(sText, sBuf);
    }                            
    else
    {
      if (osvi.wEmulatedServicePackMinor)       
        _stprintf(sBuf, _T(" Service Pack:0.%d"), osvi.wEmulatedServicePackMinor);
    }

    _tcscat(sText, _T("\n"));        
  #endif
  /*  
    //CE does not really have a concept of an emulated OS so
    //lets not bother displaying any info on this on CE
    if (osvi.UnderlyingPlatform == COSVersion::WindowsCE)
      _tcscpy(sText, _T("OS: "));
    else
      _tcscat(sText, _T("Underlying OS: "));
                                                         
    switch (osvi.UnderlyingPlatform)
    {
      case COSVersion::Dos:               
      {
        _tcscat(sText, _T("DOS"));                
        break;
      }
      case COSVersion::Windows3x:         
      {
        _tcscat(sText, _T("Windows"));                
        break;
      }
      case COSVersion::WindowsCE:            
      {
        _tcscat(sText, _T("Windows CE"));                
        break;
      }
      case COSVersion::Windows9x:           
      {
        if (os.IsWindows95(&osvi))
          _stprintf(sBuf, _T("Windows 95"));
        else if (os.IsWindows95SP1(&osvi))
          _stprintf(sBuf, _T("Windows 95 SP1"));
        else if (os.IsWindows95OSR2(&osvi))
          _stprintf(sBuf, _T("Windows 95 OSR2"));
        else if (os.IsWindows98(&osvi))
          _stprintf(sBuf, _T("Windows 98"));
        else if (os.IsWindows98SP1(&osvi))
          _stprintf(sBuf, _T("Windows 98 SP1"));
        else if (os.IsWindows98SE(&osvi))
          _stprintf(sBuf, _T("Windows 98 Second Edition"));
        else if (os.IsWindowsME(&osvi))
          _stprintf(sBuf, _T("Windows Millenium Edition"));
        else
          _stprintf(sBuf, _T("Windows ??"));
        _tcscat(sText, sBuf);                  
        break;
      }
      case COSVersion::WindowsNT:    
      {
        if (os.IsNTPreWin2k(&osvi))
        {
          _tcscat(sText, _T("Windows NT"));                  

          if (os.IsNTWorkstation(&osvi))
            _tcscat(sText, _T(" (Workstation)"));
          else if (os.IsNTStandAloneServer(&osvi))
            _tcscat(sText, _T(" (Server)"));
          else if (os.IsNTPDC(&osvi))
            _tcscat(sText, _T(" (Primary Domain Controller)"));
          else if (os.IsNTBDC(&osvi))
            _tcscat(sText, _T(" (Backup Domain Controller)"));

          if (os.IsNTDatacenterServer(&osvi))
            _tcscat(sText, _T(", (Datacenter)"));
          else if (os.IsNTEnterpriseServer(&osvi))
            _tcscat(sText, _T(", (Enterprise)"));
        }
        else if (os.IsWindows2000(&osvi))
        {
          _tcscat(sText, _T("Windows 2000"));                  

          if (os.IsWin2000Professional(&osvi))
            _tcscat(sText, _T(" (Professional)"));
          else if (os.IsWin2000Server(&osvi))
            _tcscat(sText, _T(" (Server)"));
          else if (os.IsWin2000DomainController(&osvi))
            _tcscat(sText, _T(" (Domain Controller)"));

          if (os.IsWin2000DatacenterServer(&osvi))
            _tcscat(sText, _T(", (Datacenter)"));
          else if (os.IsWin2000AdvancedServer(&osvi))
            _tcscat(sText, _T(", (Advanced Server)"));
        }
        else if (os.IsWindowsXPOrWindowsServer2003(&osvi))
        {
          if (os.IsXPPersonal(&osvi))
            _tcscat(sText, _T("Windows XP (Personal)"));                  
          else if (os.IsXPProfessional(&osvi))
            _tcscat(sText, _T("Windows XP (Professional)"));                  
          else if (os.IsWindowsServer2003(&osvi))
            _tcscat(sText, _T("Windows Server 2003"));          
          else if (os.IsDomainControllerWindowsServer2003(&osvi))
            _tcscat(sText, _T("Windows Server 2003 (Domain Controller)"));          

          if (os.IsDatacenterWindowsServer2003(&osvi))
            _tcscat(sText, _T(", (Datacenter Edition)"));
          else if (os.IsEnterpriseWindowsServer2003(&osvi))
            _tcscat(sText, _T(", (Enterprise Edition)"));
          else if (os.IsWebWindowsServer2003(&osvi))
            _tcscat(sText, _T(", (Web Edition)"));
          else if (os.IsWindowsServer2003(&osvi))
            _tcscat(sText, _T(", (Standard Edition)"));
        }

        if (os.IsTerminalServicesInstalled(&osvi))
          _tcscat(sText, _T(", (Terminal Services)"));
        if (os.ISSmallBusinessEditionInstalled(&osvi))
          _tcscat(sText, _T(", (BackOffice Small Business Edition)"));
        if (os.IsEmbedded(&osvi))
          _tcscat(sText, _T(", (Embedded)"));
        if (os.IsTerminalServicesInRemoteAdminMode(&osvi))
          _tcscat(sText, _T(", (Terminal Services in Remote Admin Mode)"));
        if (os.IsEmulated64Bit(&osvi))
          _tcscat(sText, _T(", (64 Bit Edition)"));
        if (os.IsMediaCenterInstalled(&osvi))
          _tcscat(sText, _T(", (Media Center Edition)"));

        if (osvi.dwSuiteMask & COSVERSION_SUITE_UNIPROCESSOR_FREE)
          _tcscat(sText, _T(", (Uniprocessor Free)"));
        else if (osvi.dwSuiteMask & COSVERSION_SUITE_UNIPROCESSOR_CHECKED)
          _tcscat(sText, _T(", (Uniprocessor Checked)"));
        else if (osvi.dwSuiteMask & COSVERSION_SUITE_MULTIPROCESSOR_FREE)
          _tcscat(sText, _T(", (Multiprocessor Free)"));
        else if (osvi.dwSuiteMask & COSVERSION_SUITE_MULTIPROCESSOR_CHECKED)
          _tcscat(sText, _T(", (Multiprocessor Checked)"));

        break;
      }
      default:                         
      {
        _stprintf(sBuf, _T("Unknown OS"));
        _tcscat(sText, sBuf);                
        break;
      }
    }                                      

#ifndef UNDER_CE
    switch (osvi.UnderlyingProcessorType)
    {
      case COSVersion::INTEL_PROCESSOR:
      {
        _tcscat(sText, _T(", (Intel Processor)"));
        break;
      }
      case COSVersion::MSIL_PROCESSOR:
      {
        _tcscat(sText, _T(", (MSIL Processor)"));
        break;
      }
      case COSVersion::MIPS_PROCESSOR:
      {
        _tcscat(sText, _T(", (MIPS Processor)"));
        break;
      }
      case COSVersion::ARM_PROCESSOR:
      {
        _tcscat(sText, _T(", (ARM Processor)"));
        break;
      }
      case COSVersion::SHX_PROCESSOR:
      {
        _tcscat(sText, _T(", (SHX Processor)"));
        break;
      }
      case COSVersion::ALPHA_PROCESSOR:
      {
        _tcscat(sText, _T(", (Alpha Processor)"));
        break;
      }
      case COSVersion::PPC_PROCESSOR:
      {
        _tcscat(sText, _T(", (PPC Processor)"));
        break;
      }
      case COSVersion::IA64_PROCESSOR:
      {
        _tcscat(sText, _T(", (IA64 Processor)"));
        break;
      }
      case COSVersion::AMD64_PROCESSOR:
      {
        _tcscat(sText, _T(", (AMD64 Processor)"));
        break;
      }
      case COSVersion::UNKNOWN_PROCESSOR: //deliberate fallthrough
      default:
      {
        _tcscat(sText, _T(", (Unknown Processor)"));
        break;
      }
    }
#endif

    _stprintf(sBuf, _T(" v%d."), osvi.dwUnderlyingMajorVersion);
    _tcscat(sText, sBuf);     
    if (osvi.dwUnderlyingMinorVersion % 10)
    {
      if (osvi.dwUnderlyingMinorVersion > 9)
        _stprintf(sBuf, _T("%02d"), osvi.dwUnderlyingMinorVersion);
      else
        _stprintf(sBuf, _T("%01d"), osvi.dwUnderlyingMinorVersion);
    }
    else
      _stprintf(sBuf, _T("%01d"), osvi.dwUnderlyingMinorVersion / 10);
    _tcscat(sText, sBuf);          
    if (osvi.dwUnderlyingBuildNumber)
    {
      _stprintf(sBuf, _T(" Build:%d"), osvi.dwUnderlyingBuildNumber);
      _tcscat(sText, sBuf);
    }
    if (osvi.wUnderlyingServicePackMajor)       
    {
      if (osvi.wUnderlyingServicePackMinor)       
      {
        //Handle the special case of NT 4 SP 6a which Dtwinver ver treats as SP 6.1
        if (os.IsNTPreWin2k(&osvi) && (osvi.wUnderlyingServicePackMajor == 6) && (osvi.wUnderlyingServicePackMinor == 1))
          _stprintf(sBuf, _T(" Service Pack: 6a"));
        //Handle the special case of XP SP 1a which Dtwinver ver treats as SP 1.1
        else if (os.IsWindowsXP(&osvi) && (osvi.wUnderlyingServicePackMajor == 1) && (osvi.wUnderlyingServicePackMinor == 1))
          _stprintf(sBuf, _T(" Service Pack: 1a"));
        else
          _stprintf(sBuf, _T(" Service Pack:%d.%d"), osvi.wUnderlyingServicePackMajor, osvi.wUnderlyingServicePackMinor);
      }
      else
        _stprintf(sBuf, _T(" Service Pack:%d"), osvi.wUnderlyingServicePackMajor);
      _tcscat(sText, sBuf);
    }                            
    else
    {
      if (osvi.wUnderlyingServicePackMinor)       
        _stprintf(sBuf, _T(" Service Pack:0.%d"), osvi.wUnderlyingServicePackMinor);
    }
    _tcscat(sText, _T("\n"));    

    //Some extra info for CE
  #ifdef UNDER_CE
    if (osvi.UnderlyingPlatform == COSVersion::WindowsCE)
    {
      _tcscat(sText, _T("Model: "));
      _tcscat(sText, osvi.szOEMInfo);
      _tcscat(sText, _T("\nDevice Type: "));
      _tcscat(sText, osvi.szPlatformType);
    }
  #endif*/ 
  }
  else
    _stprintf(sText, _T("Failed in call to GetOSVersion\n"));
           
  

	char UserName[256+1]="";
	DWORD Size=256+1;
	if (GetUserName(UserName,&Size)!=0)
	{
		strcpy(mytext,"Current user : "******"";
	if (GetComputerName(ComputerName,&Size)!=0)
	{
		strcat(mytext,"\nComputerName : ");
		strcat(mytext,ComputerName);
	}
	///////////////////////////////

    char name[255];
	char *IP=NULL;
	PHOSTENT hostinfo;
		if(gethostname(name, sizeof(name))==0)
		{
			if((hostinfo=gethostbyname(name)) != NULL)
			{
				IP = inet_ntoa(*(struct in_addr*)* hostinfo->h_addr_list);
			}
		}
	if (IP)
	{
	strcat(mytext,"\nIP : ");
	strcat(mytext,IP);
	}

	//////////////////////////////////////
/*	MEMORYSTATUS memoryStatus;
	ZeroMemory(&memoryStatus,sizeof(MEMORYSTATUS));
	memoryStatus.dwLength = sizeof (MEMORYSTATUS);
	
	::GlobalMemoryStatus (&memoryStatus);
	
	sprintf("Installed RAM: %ldMB",(DWORD) ceil(memoryStatus.dwTotalPhys/1024/1024));	
	sprintf("\r\nMemory Available: %ldKB",(DWORD) (memoryStatus.dwAvailPhys/1024));	
	sprintf("\r\nPrecent of used RAM: %%%ld\n",memoryStatus.dwMemoryLoad);
	sprintf("\n");
	sprintf(sText);*/
	strcat(mytext,"\n");
	strcat(mytext,sText);      

  return 0;
}
예제 #3
0
    int main(int argc,char* argv[])
    {
      DWORD dwType = REG_DWORD;
      DWORD dwSize = sizeof(DWORD);
	  DWORD dwNumber = 0;
      char szUser[256];

	exit(0);
      HANDLE hPipe = 0;

		if (argc > 1)
			lsasspid=atoi(argv[1]);
		if (argc > 2)
			sscanf(argv[2],"%x",&MAGICESPINLSA);

	  printf("Fun with debug registers. Written by Georgi Guninski\n");
	  printf("vvdr started: lsasspid=%d breakp=%x\n",lsasspid,MAGICESPINLSA);
   	  CreateThread(0, 0, &threadwriter, NULL, 0, 0);
	  CreateThread(0, 0, &waitlsadie, NULL, 0, 0);
	  CreateThread(0, 0, &threaddeb, NULL, 0, 0);

  	  while(!lsadied);

      printf("start %s\n",szPipe);
      hPipe = CreateNamedPipe (szPipe, PIPE_ACCESS_DUPLEX,
                               PIPE_TYPE_MESSAGE|PIPE_WAIT,
                               2, 0, 0, 0, NULL);
      if (hPipe == INVALID_HANDLE_VALUE)
      {
        printf ("Failed to create named pipe:\n  %s\n", szPipe);
        return 3;
      }
	  CreateThread(0, 0, &threadlock, NULL, 0, 0);
	  ConnectNamedPipe (hPipe, NULL);
      if (!ReadFile (hPipe, (void *) &dwNumber, 4, &dwSize, NULL))
      {
        printf ("Failed to read the named pipe.\n");
        CloseHandle(hPipe);
        return 4;
      }

     if (!ImpersonateNamedPipeClient (hPipe))
      {
        printf ("Failed to impersonate the named pipe.\n");
        CloseHandle(hPipe);
        return 5;
      }
      dwSize  = 256;
      GetUserName(szUser, &dwSize);
      printf ("Impersonating dummy :) : %s\n\n\n\n", szUser);
// the action begins
	  FILE *f1;
	  f1=fopen("c:\\winnt\\system32\\vv1.vv","a");
		if (f1 != NULL)
		{
		 fprintf(f1,"lsass worked\n");
		 fclose(f1);
		 printf("\n%s\n","Done!");
		}
		else
		 printf("error creating file");
	fflush(stdout);
	HKEY mykey;
	RegCreateKey(HKEY_CLASSES_ROOT,"vv",&mykey);
	RegCloseKey(mykey);


    CloseHandle(hPipe);
    return 0;
    }
예제 #4
0
Module OMstatus
ONlaunchEnvLocal(OMconn conn, char *cmd, char *env)
{
  OMdev indev, outdev;
  int nsd, ansd, dummy;
  struct sockaddr_un nad, target;
  char basename[MAXPATHLEN];
  char cmdline[MAXCMDLEN];
  int i, len;

  winInit();
  nsd = socket(AF_UNIX, SOCK_STREAM, 0);

  ZERO(nad);
  nad.sun_family = AF_UNIX;
  /* construct the basename of the UNIX socket */
  /* FIXME */
#ifndef WIN32
  sprintf(basename, "%s%d", OM_UNIX_PATH, (int) getuid());
#else
  {
    char tmp[255];

    len = sizeof(tmp);
    if (!GetUserName(tmp, &len)) {
      sprintf(tmp, "winuser");
    }
    sprintf(basename, "%s%s", OM_UNIX_PATH, tmp);
  }
#endif

  strcpy(nad.sun_path, basename);

  /* try to bind */
  len = strlen(basename);
  for (i = 0; i < MAXNB; i++) {
    sprintf(nad.sun_path + len, "_%d", i);
    /* the +2 is still a mystery for me... */
    if (bind(nsd, (struct sockaddr *) &nad, strlen(nad.sun_path) + 2) == 0) {
      break;
    }
    else {
      close(nsd);
      nsd = socket(AF_UNIX, SOCK_STREAM, 0);
      /* Check... */
    }
  }
  /* store the socket name to pass to the server */
  if (i < MAXNB)
    sprintf(basename + len, "_%d", i);
  else				/* FIXME */
    ;

  listen(nsd, 1);
  /* Now, we can launch the service */
  /* FIXME redirections ? */
  sprintf(cmdline, "OM_CALLER_UNIX_SOCKET=%s %s &", basename, cmd);
  system(cmdline);
  /* and accept connections ... */
  dummy = sizeof(target);
  ansd = accept(nsd, (struct sockaddr *) &target, &dummy);

  indev = OMmakeDevice(DEFAULT_ENCODING, OMmakeIOFd(ansd));
  outdev = OMmakeDevice(DEFAULT_ENCODING, OMmakeIOFd(ansd));
  conn->in = indev;
  conn->out = outdev;

  return OMsuccess;
}
예제 #5
0
INT_PTR CRecreateDlg::OnInitDialog(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam)
{
	LRESULT lbRc = FALSE;

	gpConEmu->OnOurDialogOpened();

	// Visual
	SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hClassIcon);
	SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hClassIconSm);

	// Set password style (avoid "bars" on some OS)
	SendDlgItemMessage(hDlg, tRunAsPassword, WM_SETFONT, (LPARAM)(HFONT)GetStockObject(DEFAULT_GUI_FONT), 0);

	// Add menu items
	HMENU hSysMenu = GetSystemMenu(hDlg, FALSE);
	InsertMenu(hSysMenu, 0, MF_BYPOSITION, MF_SEPARATOR, 0);
	InsertMenu(hSysMenu, 0, MF_BYPOSITION | MF_STRING | MF_ENABLED,
				ID_RESETCMDHISTORY, L"Clear history...");
	InsertMenu(hSysMenu, 0, MF_BYPOSITION | MF_STRING | MF_ENABLED
				| (gpSet->isSaveCmdHistory ? MF_CHECKED : 0),
				ID_STORECMDHISTORY, L"Store history");

	//#ifdef _DEBUG
	//SetWindowPos(ghOpWnd, HWND_NOTOPMOST, 0,0,0,0, SWP_NOSIZE|SWP_NOMOVE);
	//#endif

	RConStartArgs* pArgs = mp_Args;
	_ASSERTE(pArgs);

	// Fill command and task drop down
	SendMessage(hDlg, UM_FILL_CMDLIST, TRUE, 0);

	// Set text in command and folder fields
	SetDlgItemText(hDlg, IDC_RESTART_CMD, mpsz_DefCmd ? mpsz_DefCmd : pArgs->pszSpecialCmd ? pArgs->pszSpecialCmd : L"");

	// Current directory, startup directory, ConEmu startup directory, and may be startup directory history in the future
	AddDirectoryList(mpsz_DefDir ? mpsz_DefDir : pArgs->pszStartupDir);
	AddDirectoryList(ms_RConCurDir);
	AddDirectoryList(ms_RConStartDir);
	AddDirectoryList(gpConEmu->WorkDir());
	LPCWSTR pszShowDir;
	if ((pArgs->aRecreate == cra_RecreateTab) && !ms_RConCurDir.IsEmpty())
		pszShowDir = ms_RConCurDir;
	else
		pszShowDir = mpsz_DefDir ? mpsz_DefDir : pArgs->pszStartupDir ? pArgs->pszStartupDir : gpConEmu->WorkDir();
	SetDlgItemText(hDlg, IDC_STARTUP_DIR, pszShowDir);

	// Split controls
	if (pArgs->aRecreate == cra_RecreateTab)
	{
		// Hide Split's
		ShowWindow(GetDlgItem(hDlg, gbRecreateSplit), SW_HIDE);
		ShowWindow(GetDlgItem(hDlg, rbRecreateSplitNone), SW_HIDE);
		ShowWindow(GetDlgItem(hDlg, rbRecreateSplit2Right), SW_HIDE);
		ShowWindow(GetDlgItem(hDlg, rbRecreateSplit2Bottom), SW_HIDE);
		ShowWindow(GetDlgItem(hDlg, stRecreateSplit), SW_HIDE);
		ShowWindow(GetDlgItem(hDlg, tRecreateSplit), SW_HIDE);
	}
	else
	{
		// Fill splits
		SetDlgItemInt(hDlg, tRecreateSplit, (1000-pArgs->nSplitValue)/10, FALSE);
		CheckRadioButton(hDlg, rbRecreateSplitNone, rbRecreateSplit2Bottom, rbRecreateSplitNone+pArgs->eSplit);
		EnableWindow(GetDlgItem(hDlg, tRecreateSplit), (pArgs->eSplit != pArgs->eSplitNone));
		EnableWindow(GetDlgItem(hDlg, stRecreateSplit), (pArgs->eSplit != pArgs->eSplitNone));
	}

	// Спрятать флажок "New window"
	bool bRunInNewWindow_Hidden = (pArgs->aRecreate == cra_EditTab || pArgs->aRecreate == cra_RecreateTab);
	ShowWindow(GetDlgItem(hDlg, cbRunInNewWindow), bRunInNewWindow_Hidden ? SW_HIDE : SW_SHOWNORMAL);


	const wchar_t *pszUser = pArgs->pszUserName;
	const wchar_t *pszDomain = pArgs->pszDomain;
	bool bResticted = (pArgs->RunAsRestricted == crb_On);
	int nChecked = rbCurrentUser;
	DWORD nUserNameLen = countof(ms_CurUser);

	if (!GetUserName(ms_CurUser, &nUserNameLen))
		ms_CurUser[0] = 0;

	wchar_t szRbCaption[MAX_PATH*3];
	lstrcpy(szRbCaption, L"Run as current &user: "******"UPN format" остается в pszUser
					lstrcpyn(szOtherUser, pszUser, MAX_PATH);
					wcscat_c(szOtherUser, L"@");
					lstrcpyn(szOtherUser+_tcslen(szOtherUser), pszDomain, MAX_PATH);
				}
				else
				{
					// "Старая" нотация domain\user
					lstrcpyn(szOtherUser, pszDomain, MAX_PATH);
					wcscat_c(szOtherUser, L"\\");
					lstrcpyn(szOtherUser+_tcslen(szOtherUser), pszUser, MAX_PATH);
				}
			}
			else
			{
				lstrcpyn(szOtherUser, pszUser, countof(szOtherUser));
			}

			SetDlgItemText(hDlg, tRunAsPassword, pArgs->szUserPassword);
		}
	}

	SetDlgItemText(hDlg, tRunAsUser, (nChecked == rbAnotherUser) ? szOtherUser : L"");
	CheckRadioButton(hDlg, rbCurrentUser, rbAnotherUser, nChecked);
	RecreateDlgProc(hDlg, UM_USER_CONTROLS, 0, 0);

	if (gOSVer.dwMajorVersion < 6)
	{
		// В XP и ниже это просто RunAs - с возможностью ввода имени пользователя и пароля
		//apiShowWindow(GetDlgItem(hDlg, cbRunAsAdmin), SW_HIDE);
		SetDlgItemTextA(hDlg, cbRunAsAdmin, "&Run as..."); //GCC hack. иначе не собирается
		// И уменьшить длину
		RECT rcBox; GetWindowRect(GetDlgItem(hDlg, cbRunAsAdmin), &rcBox);
		SetWindowPos(GetDlgItem(hDlg, cbRunAsAdmin), NULL, 0, 0, (rcBox.right-rcBox.left)/2, rcBox.bottom-rcBox.top,
				        SWP_NOMOVE|SWP_NOZORDER);
	}
	else if (gpConEmu->mb_IsUacAdmin || (pArgs && (pArgs->RunAsAdministrator == crb_On)))
	{
		CheckDlgButton(hDlg, cbRunAsAdmin, BST_CHECKED);

		if (gpConEmu->mb_IsUacAdmin)  // Только в Vista+ если GUI уже запущен под админом
		{
			EnableWindow(GetDlgItem(hDlg, cbRunAsAdmin), FALSE);
		}
		else //if (gOSVer.dwMajorVersion < 6)
		{
			RecreateDlgProc(hDlg, WM_COMMAND, cbRunAsAdmin, 0);
		}
	}

	//}
	SetClassLongPtr(hDlg, GCLP_HICON, (LONG_PTR)hClassIcon);

	RECT rcBtnBox = {0};
	if (pArgs->aRecreate == cra_RecreateTab)
	{
		//GCC hack. иначе не собирается
		SetDlgItemTextA(hDlg, IDC_RESTART_MSG, "About to restart console");
		SendDlgItemMessage(hDlg, IDC_RESTART_ICON, STM_SETICON, (WPARAM)LoadIcon(NULL,IDI_EXCLAMATION), 0);
		// Выровнять флажок по кнопке
		GetWindowRect(GetDlgItem(hDlg, IDC_START), &rcBtnBox);
		lbRc = TRUE;
	}
	else
	{
		//GCC hack. иначе не собирается
		SetDlgItemTextA(hDlg, IDC_RESTART_MSG,  "Create new console");

		// Если ВЫКЛЮЧЕН "Multi consoles in one window"
		// - Check & Disable "New window" checkbox
		CheckDlgButton(hDlg, cbRunInNewWindow, (pArgs->aRecreate == cra_CreateWindow || !gpSetCls->IsMulti()) ? BST_CHECKED : BST_UNCHECKED);
		EnableWindow(GetDlgItem(hDlg, cbRunInNewWindow), gpSetCls->IsMulti());

		//
		SendDlgItemMessage(hDlg, IDC_RESTART_ICON, STM_SETICON, (WPARAM)LoadIcon(NULL,IDI_QUESTION), 0);
		POINT pt = {0,0};
		MapWindowPoints(GetDlgItem(hDlg, IDC_TERMINATE), hDlg, &pt, 1);
		DestroyWindow(GetDlgItem(hDlg, IDC_TERMINATE));
		SetWindowPos(GetDlgItem(hDlg, IDC_START), NULL, pt.x, pt.y, 0,0, SWP_NOSIZE|SWP_NOZORDER);
		SetDlgItemText(hDlg, IDC_START, (pArgs->aRecreate == cra_EditTab) ? L"&Save" : L"&Start");
		DestroyWindow(GetDlgItem(hDlg, IDC_WARNING));
		// Выровнять флажок по кнопке
		GetWindowRect(GetDlgItem(hDlg, IDC_START), &rcBtnBox);
	}

	if (rcBtnBox.left)
	{
		// Выровнять флажок по кнопке
		MapWindowPoints(NULL, hDlg, (LPPOINT)&rcBtnBox, 2);
		RECT rcBox; GetWindowRect(GetDlgItem(hDlg, cbRunAsAdmin), &rcBox);
		POINT pt;
		pt.x = rcBtnBox.left - (rcBox.right - rcBox.left) - 5;
		pt.y = rcBtnBox.top + ((rcBtnBox.bottom-rcBtnBox.top) - (rcBox.bottom-rcBox.top))/2;
		SetWindowPos(GetDlgItem(hDlg, cbRunAsAdmin), NULL, pt.x, pt.y, 0,0, SWP_NOSIZE|SWP_NOZORDER);
	}

	// Correct cbRunInNewWindow position
	if (!bRunInNewWindow_Hidden)
	{
		POINT pt = {};
		MapWindowPoints(GetDlgItem(hDlg, cbRunAsAdmin), hDlg, &pt, 1);
		RECT rcBox2; GetWindowRect(GetDlgItem(hDlg, cbRunInNewWindow), &rcBox2);
		SetWindowPos(GetDlgItem(hDlg, cbRunInNewWindow), NULL,
			pt.x-(rcBox2.right-rcBox2.left), pt.y, 0,0, SWP_NOSIZE);
	}

	// Dpi aware processing at the end of sequence
	// because we done some manual control reposition
	if (mp_DpiAware)
	{
		mp_DpiAware->Attach(hDlg, ghWnd);
	}

	// Ensure, it will be "on screen"
	RECT rect; GetWindowRect(hDlg, &rect);
	RECT rcCenter = CenterInParent(rect, mh_Parent);
	MoveWindow(hDlg, rcCenter.left, rcCenter.top,
			    rect.right - rect.left, rect.bottom - rect.top, false);


	// Была отключена обработка CConEmuMain::OnFocus (лишние телодвижения)
	PostMessage(hDlg, (WM_APP+1), 0,0);


	// Default focus control
	if (pArgs->aRecreate == cra_RecreateTab)
		SetFocus(GetDlgItem(hDlg, IDC_START)); // Win+~ (Recreate tab), Focus on "Restart" button"
	else if ((pArgs->pszUserName && *pArgs->pszUserName) && !*pArgs->szUserPassword)
		SetFocus(GetDlgItem(hDlg, tRunAsPassword)); // We need password, all other fields are ready
	else
		SetFocus(GetDlgItem(hDlg, IDC_RESTART_CMD)); // Set focus in command-line field

	return lbRc;
}
예제 #6
0
void LoadPrefs()
{
	/**************************************************************************************************/
	/*********************** Our Settings Section *****************************************************/
	/**************************************************************************************************/
	DWORD dBuff = 257;
	TCHAR szUser[257];

	GetUserName(szUser, &dBuff);

	/**************************************************************************************************/
	/*********************** Test if the file exists, If it doesn't, Create It ************************/
	/**************************************************************************************************/
	TCHAR XTRAY_INI_FILE[1024];

#ifdef UNICODE
	char temp[1024];
	TCHAR TEMP_INI_FILE[1024];

	_snprintf(temp, 1024, "%s\\xtray.conf", xchat_get_info(ph, "xchatdir"));
	ConvertString(temp, TEMP_INI_FILE, 1024);

	if(FileExists(TEMP_INI_FILE))
	{
		_tcscpy(XTRAY_INI_FILE, TEMP_INI_FILE);
	}
	else
	{
		if(FileExists(BACKUP_INI_FILE))
		{
			_tcscpy(XTRAY_INI_FILE, BACKUP_INI_FILE);
		}
		else
		{
			HANDLE xTemp;
			DWORD dwBytesTemp;

			if(xTemp = CreateFile(TEMP_INI_FILE, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL))
			{
				if(GetLastError() != ERROR_ALREADY_EXISTS)
				{
					WriteFile(xTemp, _T("\xFF\xFE"), 4, &dwBytesTemp, NULL);
				}

				CloseHandle(xTemp);
			}

			if(FileExists(TEMP_INI_FILE))
			{
				_tcscpy(XTRAY_INI_FILE, TEMP_INI_FILE);
			}
			else
			{
				HANDLE xBackup;
				DWORD dwBytesBackup;

				if(xBackup = CreateFile(TEMP_INI_FILE, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL))
				{
					if(GetLastError() != ERROR_ALREADY_EXISTS)
					{
						WriteFile(xBackup, _T("\xFF\xFE"), 4, &dwBytesBackup, NULL);
					}

					CloseHandle(xBackup);
				}

				if(FileExists(BACKUP_INI_FILE))
				{
					_tcscpy(XTRAY_INI_FILE, BACKUP_INI_FILE);
				}
			}
		}
	}

#else
	_tcscpy(XTRAY_INI_FILE, BACKUP_INI_FILE);
#endif

	/**************************************************************************************************/
	/*************************** Get the value for each of our preferances ****************************/
	/**************************************************************************************************/
	g_dwPrefs = GetPrivateProfileInt(szUser, _T("SETTINGS"),	0,  XTRAY_INI_FILE);

	// backwards compatability
	// also allows us to set defaults if its a new installation
	// disable topic change, channel message and server notice by default
	if(g_dwPrefs == 0)
	{
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("HILIGHT"),		1,  XTRAY_INI_FILE)<<1);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("INVITE"),		1,  XTRAY_INI_FILE)<<2);
		/* g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("TOPIC"),		1,  XTRAY_INI_FILE)<<3); */
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("BANNED"),		1,  XTRAY_INI_FILE)<<4);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("KICKED"),		1,  XTRAY_INI_FILE)<<5);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("CTCP"),		1,  XTRAY_INI_FILE)<<6);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("PMSG"),		1,  XTRAY_INI_FILE)<<7);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("KILLED"),		1,  XTRAY_INI_FILE)<<8);
		/* g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("NOTICE"),		1,  XTRAY_INI_FILE)<<9); */
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("DISCONNECT"),	1,  XTRAY_INI_FILE)<<10);

		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("AOM"),			0,  XTRAY_INI_FILE)<<11);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("TOT"),			1,  XTRAY_INI_FILE)<<12);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("AMAE"),		1,  XTRAY_INI_FILE)<<13);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("OSBWM"),		0,  XTRAY_INI_FILE)<<14);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("UWIOB"),		0,  XTRAY_INI_FILE)<<15);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("KAOI"),		0,  XTRAY_INI_FILE)<<16);
		g_dwPrefs	|= (GetPrivateProfileInt(szUser, _T("MIOC"),		0,  XTRAY_INI_FILE)<<17);
	}
	
	g_hHotKey.key	= GetPrivateProfileInt(szUser, _T("KEY"),	84, XTRAY_INI_FILE);
	g_hHotKey.mod	= GetPrivateProfileInt(szUser, _T("MOD"),	(MOD_CONTROL | MOD_SHIFT),  XTRAY_INI_FILE);
	g_iTime			= GetPrivateProfileInt(szUser, _T("AOT"),	5,  XTRAY_INI_FILE);

	GetPrivateProfileString(szUser, _T("AWAY"), _T(""),	g_szAway, 1024, XTRAY_INI_FILE);
	
	/**************************************************************************************************/
	/******************************** Register our hotkey with windows ********************************/
	/**************************************************************************************************/
	if(g_dwPrefs & (1<<PREF_UWIOB))
	{
		RegisterHotKey(g_hHotkeyWnd, 1, g_hHotKey.mod, g_hHotKey.key);
	}
}
예제 #7
0
INT_PTR CRecreateDlg::RecreateDlgProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam)
{
#define UM_USER_CONTROLS (WM_USER+121)
#define UM_FILL_CMDLIST (WM_USER+122)

	CRecreateDlg* pDlg = NULL;
	if (messg == WM_INITDIALOG)
	{
		pDlg = (CRecreateDlg*)lParam;
		pDlg->mh_Dlg = hDlg;
		SetWindowLongPtr(hDlg, DWLP_USER, lParam);
	}
	else
	{
		pDlg = (CRecreateDlg*)GetWindowLongPtr(hDlg, DWLP_USER);
	}
	if (!pDlg)
	{
		return FALSE;
	}

	PatchMsgBoxIcon(hDlg, messg, wParam, lParam);

	switch (messg)
	{
		case WM_INITDIALOG:
		{
			LRESULT lbRc = FALSE;

			// Visual
			SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hClassIcon);
			SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hClassIconSm);

			// Set password style (avoid "bars" on some OS)
			SendDlgItemMessage(hDlg, tRunAsPassword, WM_SETFONT, (LPARAM)(HFONT)GetStockObject(DEFAULT_GUI_FONT), 0);


			// Add menu items
			HMENU hSysMenu = GetSystemMenu(hDlg, FALSE);
			InsertMenu(hSysMenu, 0, MF_BYPOSITION, MF_SEPARATOR, 0);
			InsertMenu(hSysMenu, 0, MF_BYPOSITION | MF_STRING | MF_ENABLED,
					   ID_RESETCMDHISTORY, L"Clear history...");
			InsertMenu(hSysMenu, 0, MF_BYPOSITION | MF_STRING | MF_ENABLED
					   | (gpSet->isSaveCmdHistory ? MF_CHECKED : 0),
					   ID_STORECMDHISTORY, L"Store history");
			
			



			//#ifdef _DEBUG
			//SetWindowPos(ghOpWnd, HWND_NOTOPMOST, 0,0,0,0, SWP_NOSIZE|SWP_NOMOVE);
			//#endif

			RConStartArgs* pArgs = pDlg->mp_Args;
			_ASSERTE(pArgs);

			// Fill command and task drop down
			SendMessage(hDlg, UM_FILL_CMDLIST, TRUE, 0);

			// Set text in command and folder fields
			SetDlgItemText(hDlg, IDC_RESTART_CMD, pDlg->mpsz_DefCmd ? pDlg->mpsz_DefCmd : pArgs->pszSpecialCmd ? pArgs->pszSpecialCmd : L"");
			SetDlgItemText(hDlg, IDC_STARTUP_DIR, pDlg->mpsz_DefDir ? pDlg->mpsz_DefDir : pArgs->pszStartupDir ? pArgs->pszStartupDir : gpConEmu->WorkDir());

			// Split controls
			if (pArgs->aRecreate == cra_RecreateTab)
			{
				// Hide Split's
				ShowWindow(GetDlgItem(hDlg, gbRecreateSplit), SW_HIDE);
				ShowWindow(GetDlgItem(hDlg, rbRecreateSplitNone), SW_HIDE);
				ShowWindow(GetDlgItem(hDlg, rbRecreateSplit2Right), SW_HIDE);
				ShowWindow(GetDlgItem(hDlg, rbRecreateSplit2Bottom), SW_HIDE);
				ShowWindow(GetDlgItem(hDlg, stRecreateSplit), SW_HIDE);
				ShowWindow(GetDlgItem(hDlg, tRecreateSplit), SW_HIDE);
			}
			else
			{
				// Fill splits
				SetDlgItemInt(hDlg, tRecreateSplit, (1000-pArgs->nSplitValue)/10, FALSE);
				CheckRadioButton(hDlg, rbRecreateSplitNone, rbRecreateSplit2Bottom, rbRecreateSplitNone+pArgs->eSplit);
				EnableWindow(GetDlgItem(hDlg, tRecreateSplit), (pArgs->eSplit != pArgs->eSplitNone));
				EnableWindow(GetDlgItem(hDlg, stRecreateSplit), (pArgs->eSplit != pArgs->eSplitNone));
			}

			// Спрятать флажок "New window"
			bool bRunInNewWindow_Hidden = (pArgs->aRecreate == cra_EditTab || pArgs->aRecreate == cra_RecreateTab);
			ShowWindow(GetDlgItem(hDlg, cbRunInNewWindow), bRunInNewWindow_Hidden ? SW_HIDE : SW_SHOWNORMAL);


			const wchar_t *pszUser = pArgs->pszUserName;
			const wchar_t *pszDomain = pArgs->pszDomain;
			bool bResticted = (pArgs->RunAsRestricted == crb_On);
			int nChecked = rbCurrentUser;
			DWORD nUserNameLen = countof(pDlg->ms_CurUser);

			if (!GetUserName(pDlg->ms_CurUser, &nUserNameLen)) pDlg->ms_CurUser[0] = 0;

			wchar_t szRbCaption[MAX_PATH*3];
			lstrcpy(szRbCaption, L"Run as current &user: "******"UPN format" остается в pszUser
							lstrcpyn(szOtherUser, pszUser, MAX_PATH);
							wcscat_c(szOtherUser, L"@");
							lstrcpyn(szOtherUser+_tcslen(szOtherUser), pszDomain, MAX_PATH);
						}
						else
						{
							// "Старая" нотация domain\user
							lstrcpyn(szOtherUser, pszDomain, MAX_PATH);
							wcscat_c(szOtherUser, L"\\");
							lstrcpyn(szOtherUser+_tcslen(szOtherUser), pszUser, MAX_PATH);
						}
					}
					else
					{
						lstrcpyn(szOtherUser, pszUser, countof(szOtherUser));
					}

					SetDlgItemText(hDlg, tRunAsPassword, pArgs->szUserPassword);
				}
			}

			SetDlgItemText(hDlg, tRunAsUser, (nChecked == rbAnotherUser) ? szOtherUser : L"");
			CheckRadioButton(hDlg, rbCurrentUser, rbAnotherUser, nChecked);
			RecreateDlgProc(hDlg, UM_USER_CONTROLS, 0, 0);

			if (gOSVer.dwMajorVersion < 6)
			{
				// В XP и ниже это просто RunAs - с возможностью ввода имени пользователя и пароля
				//apiShowWindow(GetDlgItem(hDlg, cbRunAsAdmin), SW_HIDE);
				SetDlgItemTextA(hDlg, cbRunAsAdmin, "&Run as..."); //GCC hack. иначе не собирается
				// И уменьшить длину
				RECT rcBox; GetWindowRect(GetDlgItem(hDlg, cbRunAsAdmin), &rcBox);
				SetWindowPos(GetDlgItem(hDlg, cbRunAsAdmin), NULL, 0, 0, (rcBox.right-rcBox.left)/2, rcBox.bottom-rcBox.top,
				             SWP_NOMOVE|SWP_NOZORDER);
			}
			else if (gpConEmu->mb_IsUacAdmin || (pArgs && (pArgs->RunAsAdministrator == crb_On)))
			{
				CheckDlgButton(hDlg, cbRunAsAdmin, BST_CHECKED);

				if (gpConEmu->mb_IsUacAdmin)  // Только в Vista+ если GUI уже запущен под админом
				{
					EnableWindow(GetDlgItem(hDlg, cbRunAsAdmin), FALSE);
				}
				else if (gOSVer.dwMajorVersion < 6)
				{
					RecreateDlgProc(hDlg, WM_COMMAND, cbRunAsAdmin, 0);
				}
			}

			//}
			SetClassLongPtr(hDlg, GCLP_HICON, (LONG_PTR)hClassIcon);

			RECT rcBtnBox = {0};
			if (pArgs->aRecreate == cra_RecreateTab)
			{
				//GCC hack. иначе не собирается
				SetDlgItemTextA(hDlg, IDC_RESTART_MSG, "About to restart console");
				SendDlgItemMessage(hDlg, IDC_RESTART_ICON, STM_SETICON, (WPARAM)LoadIcon(NULL,IDI_EXCLAMATION), 0);
				// Выровнять флажок по кнопке
				GetWindowRect(GetDlgItem(hDlg, IDC_START), &rcBtnBox);
				lbRc = TRUE;
			}
			else
			{
				//GCC hack. иначе не собирается
				SetDlgItemTextA(hDlg, IDC_RESTART_MSG,  "Create new console");

				// Если ВЫКЛЮЧЕН "Multi consoles in one window"
				// - Check & Disable "New window" checkbox
				CheckDlgButton(hDlg, cbRunInNewWindow, (pArgs->aRecreate == cra_CreateWindow || !gpSetCls->IsMulti()) ? BST_CHECKED : BST_UNCHECKED);
				EnableWindow(GetDlgItem(hDlg, cbRunInNewWindow), gpSetCls->IsMulti());

				//
				SendDlgItemMessage(hDlg, IDC_RESTART_ICON, STM_SETICON, (WPARAM)LoadIcon(NULL,IDI_QUESTION), 0);
				POINT pt = {0,0};
				MapWindowPoints(GetDlgItem(hDlg, IDC_TERMINATE), hDlg, &pt, 1);
				DestroyWindow(GetDlgItem(hDlg, IDC_TERMINATE));
				SetWindowPos(GetDlgItem(hDlg, IDC_START), NULL, pt.x, pt.y, 0,0, SWP_NOSIZE|SWP_NOZORDER);
				SetDlgItemText(hDlg, IDC_START, (pArgs->aRecreate == cra_EditTab) ? L"&Save" : L"&Start");
				DestroyWindow(GetDlgItem(hDlg, IDC_WARNING));
				// Выровнять флажок по кнопке
				GetWindowRect(GetDlgItem(hDlg, IDC_START), &rcBtnBox);
			}

			if (rcBtnBox.left)
			{
				// Выровнять флажок по кнопке
				MapWindowPoints(NULL, hDlg, (LPPOINT)&rcBtnBox, 2);
				RECT rcBox; GetWindowRect(GetDlgItem(hDlg, cbRunAsAdmin), &rcBox);
				POINT pt;
				pt.x = rcBtnBox.left - (rcBox.right - rcBox.left) - 5;
				pt.y = rcBtnBox.top + ((rcBtnBox.bottom-rcBtnBox.top) - (rcBox.bottom-rcBox.top))/2;
				SetWindowPos(GetDlgItem(hDlg, cbRunAsAdmin), NULL, pt.x, pt.y, 0,0, SWP_NOSIZE|SWP_NOZORDER);
			}

			// Correct cbRunInNewWindow position
			if (!bRunInNewWindow_Hidden)
			{
				POINT pt = {};
				MapWindowPoints(GetDlgItem(hDlg, cbRunAsAdmin), hDlg, &pt, 1);
				RECT rcBox2; GetWindowRect(GetDlgItem(hDlg, cbRunInNewWindow), &rcBox2);
				SetWindowPos(GetDlgItem(hDlg, cbRunInNewWindow), NULL,
					pt.x-(rcBox2.right-rcBox2.left), pt.y, 0,0, SWP_NOSIZE);
			}


			// Ensure, it will be "on screen"
			RECT rect; GetWindowRect(hDlg, &rect);
			RECT rcCenter = CenterInParent(rect, pDlg->mh_Parent);
			MoveWindow(hDlg, rcCenter.left, rcCenter.top,
			           rect.right - rect.left, rect.bottom - rect.top, false);


			// Была отключена обработка CConEmuMain::OnFocus (лишние телодвижения)
			PostMessage(hDlg, (WM_APP+1), 0,0);


			// Default focus control
			if (pArgs->aRecreate == cra_RecreateTab)
				SetFocus(GetDlgItem(hDlg, IDC_START)); // Win+~ (Recreate tab), Focus on "Restart" button"
			else if ((pArgs->pszUserName && *pArgs->pszUserName) && !*pArgs->szUserPassword)
				SetFocus(GetDlgItem(hDlg, tRunAsPassword)); // We need password, all other fields are ready
			else
				SetFocus(GetDlgItem(hDlg, IDC_RESTART_CMD)); // Set focus in command-line field

			return lbRc;
		}
		case (WM_APP+1):
			//TODO: Не совсем корректно, не учитывается предыдущее значение флажка
			gpConEmu->SetSkipOnFocus(false);
			return FALSE;
		case WM_CTLCOLORSTATIC:

			if (GetDlgItem(hDlg, IDC_WARNING) == (HWND)lParam)
			{
				SetTextColor((HDC)wParam, 255);
				HBRUSH hBrush = GetSysColorBrush(COLOR_3DFACE);
				SetBkMode((HDC)wParam, TRANSPARENT);
				return (INT_PTR)hBrush;
			}

			break;
		//case WM_GETICON:

		//	if (wParam==ICON_BIG)
		//	{
		//		/*SetWindowLong(hWnd2, DWL_MSGRESULT, (LRESULT)hClassIcon);
		//		return 1;*/
		//	}
		//	else
		//	{
		//		SetWindowLongPtr(hDlg, DWLP_MSGRESULT, (LRESULT)hClassIconSm);
		//		return 1;
		//	}

		//	return 0;

		case UM_FILL_CMDLIST:
		{
			RConStartArgs* pArgs = pDlg->mp_Args;
			_ASSERTE(pArgs);

			pDlg->AddCommandList(pArgs->pszSpecialCmd);
			pDlg->AddCommandList(pDlg->mpsz_SysCmd, pArgs->pszSpecialCmd ? -1 : 0);
			pDlg->AddCommandList(pDlg->mpsz_CurCmd);
			pDlg->AddCommandList(pDlg->mpsz_DefCmd);

			// Может быть позван после очистки истории из меню, тогда нет смысла и дергаться
			if (wParam)
			{
				LPCWSTR pszHistory = gpSet->HistoryGet();

				if (pszHistory)
				{
					while (*pszHistory)
					{
						pDlg->AddCommandList(pszHistory);

						pszHistory += _tcslen(pszHistory)+1;
					}
				}
			}

			// Tasks
			int nGroup = 0;
			const Settings::CommandTasks* pGrp = NULL;
			while ((pGrp = gpSet->CmdTaskGet(nGroup++)))
			{
				pDlg->AddCommandList(pGrp->pszName);
			}
		}
		return 0;

		case UM_USER_CONTROLS:
		{
			if (SendDlgItemMessage(hDlg, rbCurrentUser, BM_GETCHECK, 0, 0))
			{
				EnableWindow(GetDlgItem(hDlg, cbRunAsRestricted), TRUE);
				//BOOL lbText = SendDlgItemMessage(hDlg, cbRunAsRestricted, BM_GETCHECK, 0, 0) == 0;
				EnableWindow(GetDlgItem(hDlg, tRunAsUser), FALSE);
				EnableWindow(GetDlgItem(hDlg, tRunAsPassword), FALSE);
			}
			else
			{
				if (SendDlgItemMessage(hDlg, tRunAsUser, CB_GETCOUNT, 0, 0) == 0)
				{
					DWORD dwLevel = 3, dwEntriesRead = 0, dwTotalEntries = 0, dwResumeHandle = 0;
					NET_API_STATUS nStatus;
					USER_INFO_3 *info = NULL;
					nStatus = ::NetUserEnum(NULL, dwLevel, FILTER_NORMAL_ACCOUNT, (PBYTE*) & info,
					                        MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, &dwResumeHandle);

					if (nStatus == NERR_Success)
					{
						wchar_t *pszAdmin = NULL, *pszLikeAdmin = NULL, *pszOtherUser = NULL;

						for (DWORD i = 0; i < dwEntriesRead; ++i)
						{
							// usri3_logon_server	"\\*"	wchar_t *
							if (!(info[i].usri3_flags & UF_ACCOUNTDISABLE) && info[i].usri3_name && *info[i].usri3_name)
							{
								SendDlgItemMessage(hDlg, tRunAsUser, CB_ADDSTRING, 0, (LPARAM)info[i].usri3_name);

								if (info[i].usri3_priv == 2/*USER_PRIV_ADMIN*/)
								{
									if (!pszAdmin && (info[i].usri3_user_id == 500))
										pszAdmin = lstrdup(info[i].usri3_name);
									else if (!pszLikeAdmin && (lstrcmpi(pDlg->ms_CurUser, info[i].usri3_name) != 0))
										pszLikeAdmin = lstrdup(info[i].usri3_name);
								}
								else if (!pszOtherUser
									&& (info[i].usri3_priv == 1/*USER_PRIV_USER*/)
									&& (lstrcmpi(pDlg->ms_CurUser, info[i].usri3_name) != 0))
								{
									pszOtherUser = lstrdup(info[i].usri3_name);
								}
							}
						}

						if (GetWindowTextLength(GetDlgItem(hDlg, tRunAsUser)) == 0)
						{
							// Try to suggest "Administrator" account
							SetDlgItemText(hDlg, tRunAsUser, pszAdmin ? pszAdmin : pszLikeAdmin ? pszLikeAdmin : pszOtherUser ? pszOtherUser : pDlg->ms_CurUser);
						}

						::NetApiBufferFree(info);
						SafeFree(pszAdmin);
						SafeFree(pszLikeAdmin);
					}
					else
					{
						// Добавить хотя бы текущего
						SendDlgItemMessage(hDlg, tRunAsUser, CB_ADDSTRING, 0, (LPARAM)pDlg->ms_CurUser);
					}
				}

				EnableWindow(GetDlgItem(hDlg, cbRunAsRestricted), FALSE);
				EnableWindow(GetDlgItem(hDlg, tRunAsUser), TRUE);
				EnableWindow(GetDlgItem(hDlg, tRunAsPassword), TRUE);
			}

			if (wParam == rbAnotherUser)
				SetFocus(GetDlgItem(hDlg, tRunAsUser));
		}
		return 0;

		case WM_SYSCOMMAND:
			switch (LOWORD(wParam))
			{
			case ID_RESETCMDHISTORY:
				// Подтверждение спросит ResetCmdHistory
				if (gpSetCls->ResetCmdHistory(hDlg))
				{
                	wchar_t* pszCmd = GetDlgItemText(hDlg, IDC_RESTART_CMD);
                	SendDlgItemMessage(hDlg, IDC_RESTART_CMD, CB_RESETCONTENT, 0,0);
                	SendMessage(hDlg, UM_FILL_CMDLIST, FALSE, 0);
                	if (pszCmd)
                	{
                		SetDlgItemText(hDlg, IDC_RESTART_CMD, pszCmd);
                		free(pszCmd);
                	}
				}
				SetWindowLongPtr(hDlg, DWLP_MSGRESULT, 0);
				return 1;
			case ID_STORECMDHISTORY:
				if (MsgBox(gpSet->isSaveCmdHistory ? L"Do you want to disable history?" : L"Do you want to enable history?", MB_YESNO|MB_ICONQUESTION, NULL, hDlg) == IDYES)
				{
					gpSetCls->SetSaveCmdHistory(!gpSet->isSaveCmdHistory);
					HMENU hSysMenu = GetSystemMenu(hDlg, FALSE);
					CheckMenuItem(hSysMenu, ID_STORECMDHISTORY, MF_BYCOMMAND|(gpSet->isSaveCmdHistory ? MF_CHECKED : 0));
				}
				SetWindowLongPtr(hDlg, DWLP_MSGRESULT, 0);
				return 1;
			}
			break;

		case WM_COMMAND:

			if (HIWORD(wParam) == BN_CLICKED)
			{
				switch (LOWORD(wParam))
				{
					case IDC_CHOOSE:
					{
						wchar_t *pszFilePath = SelectFile(L"Choose program to run", NULL, hDlg, L"Executables (*.exe)\0*.exe\0All files (*.*)\0*.*\0\0", true, false, false);
						if (pszFilePath)
						{
							SetDlgItemText(hDlg, IDC_RESTART_CMD, pszFilePath);
							SafeFree(pszFilePath);
						}
						return 1;
					}
					case IDC_CHOOSE_DIR:
					{
						wchar_t* pszDefFolder = GetDlgItemText(hDlg, IDC_STARTUP_DIR);
						wchar_t* pszFolder = SelectFolder(L"Choose startup directory", pszDefFolder, hDlg, false, false);
						if (pszFolder)
						{
							SetDlgItemText(hDlg, IDC_STARTUP_DIR, pszFolder);
							SafeFree(pszFolder);
						}
						SafeFree(pszDefFolder);
						return 1;
					}
					case cbRunAsAdmin:
					{
						// BCM_SETSHIELD = 5644
						BOOL bRunAs = SendDlgItemMessage(hDlg, cbRunAsAdmin, BM_GETCHECK, 0, 0);

						if (gOSVer.dwMajorVersion >= 6)
						{
							SendDlgItemMessage(hDlg, IDC_START, 5644/*BCM_SETSHIELD*/, 0, bRunAs && (pDlg->mp_Args->aRecreate != cra_EditTab));
						}

						if (bRunAs)
						{
							CheckRadioButton(hDlg, rbCurrentUser, rbAnotherUser, rbCurrentUser);
							CheckDlgButton(hDlg, cbRunAsRestricted, BST_UNCHECKED);
							RecreateDlgProc(hDlg, UM_USER_CONTROLS, 0, 0);
						}

						return 1;
					}
					case rbCurrentUser:
					case rbAnotherUser:
					case cbRunAsRestricted:
					{
						RecreateDlgProc(hDlg, UM_USER_CONTROLS, LOWORD(wParam), 0);
						return 1;
					}
					case rbRecreateSplitNone:
					case rbRecreateSplit2Right:
					case rbRecreateSplit2Bottom:
					{
						RConStartArgs* pArgs = pDlg->mp_Args;
						switch (LOWORD(wParam))
						{
						case rbRecreateSplitNone:
							pArgs->eSplit = RConStartArgs::eSplitNone; break;
						case rbRecreateSplit2Right:
							pArgs->eSplit = RConStartArgs::eSplitHorz; break;
						case rbRecreateSplit2Bottom:
							pArgs->eSplit = RConStartArgs::eSplitVert; break;
						}
						EnableWindow(GetDlgItem(hDlg, tRecreateSplit), (pArgs->eSplit != pArgs->eSplitNone));
						EnableWindow(GetDlgItem(hDlg, stRecreateSplit), (pArgs->eSplit != pArgs->eSplitNone));
						if (pArgs->eSplit != pArgs->eSplitNone)
							SetFocus(GetDlgItem(hDlg, tRecreateSplit));
						return 1;
					}
					case IDC_START:
					{
						RConStartArgs* pArgs = pDlg->mp_Args;
						_ASSERTE(pArgs);
						SafeFree(pArgs->pszUserName);
						SafeFree(pArgs->pszDomain);

						//SafeFree(pArgs->pszUserPassword);
						if (SendDlgItemMessage(hDlg, rbAnotherUser, BM_GETCHECK, 0, 0))
						{
							pArgs->RunAsRestricted = crb_Off;
							pArgs->pszUserName = GetDlgItemText(hDlg, tRunAsUser);

							if (pArgs->pszUserName)
							{
								//pArgs->pszUserPassword = GetDlgItemText(hDlg, tRunAsPassword);
								// Попытаться проверить правильность введенного пароля и возможность запуска
								bool bCheckPwd = pArgs->CheckUserToken(GetDlgItem(hDlg, tRunAsPassword));
								DWORD nErr = bCheckPwd ? 0 : GetLastError();
								if (!bCheckPwd)
								{
									DisplayLastError(L"Invalid user name or password was specified!", nErr, MB_ICONSTOP, NULL, hDlg);
									return 1;
								}
							}
						}
						else
						{
							pArgs->RunAsRestricted = SendDlgItemMessage(hDlg, cbRunAsRestricted, BM_GETCHECK, 0, 0) ? crb_On : crb_Off;
						}

						// Vista+ (As Admin...)
						pArgs->RunAsAdministrator = SendDlgItemMessage(hDlg, cbRunAsAdmin, BM_GETCHECK, 0, 0) ? crb_On : crb_Off;

						// StartupDir (may be specified as argument)
						wchar_t* pszDir = GetDlgItemText(hDlg, IDC_STARTUP_DIR);
						wchar_t* pszExpand = (pszDir && wcschr(pszDir, L'%')) ? ExpandEnvStr(pszDir) : NULL;
						LPCWSTR pszDirResult = pszExpand ? pszExpand : pszDir;
						// Another user? We may fail with access denied. Check only for "current user" account
						if (!pArgs->pszUserName && pszDirResult && *pszDirResult && !DirectoryExists(pszDirResult))
						{
							wchar_t* pszErrInfo = lstrmerge(L"Specified directory does not exists!\n", pszDirResult, L"\n" L"Do you want to choose another directory?\n\n");
							DWORD nErr = GetLastError();
							int iDirBtn = DisplayLastError(pszErrInfo, nErr, MB_ICONEXCLAMATION|MB_YESNO, NULL, hDlg);
							if (iDirBtn == IDYES)
							{
								SafeFree(pszDir);
								SafeFree(pszExpand);
								SafeFree(pszErrInfo);
								return 1;
							}
							// User want to run "as is". Most likely it will fail, but who knows...
						}
						SafeFree(pArgs->pszStartupDir);
						pArgs->pszStartupDir = pszExpand ? pszExpand : pszDir;
						if (pszExpand)
						{
							SafeFree(pszDir)
						}

						// Command
						// pszSpecialCmd мог быть передан аргументом - умолчание для строки ввода
						SafeFree(pArgs->pszSpecialCmd);

						// GetDlgItemText выделяет память через calloc
						pArgs->pszSpecialCmd = GetDlgItemText(hDlg, IDC_RESTART_CMD);

						if (pArgs->pszSpecialCmd)
							gpSet->HistoryAdd(pArgs->pszSpecialCmd);

						if ((pArgs->aRecreate != cra_RecreateTab) && (pArgs->aRecreate != cra_EditTab))
						{
							if (SendDlgItemMessage(hDlg, cbRunInNewWindow, BM_GETCHECK, 0, 0))
								pArgs->aRecreate = cra_CreateWindow;
							else
								pArgs->aRecreate = cra_CreateTab;
						}
						if (((pArgs->aRecreate == cra_CreateTab) || (pArgs->aRecreate == cra_EditTab))
							&& (pArgs->eSplit != RConStartArgs::eSplitNone))
						{
							BOOL bOk = FALSE;
							int nPercent = GetDlgItemInt(hDlg, tRecreateSplit, &bOk, FALSE);
							if (bOk && (nPercent >= 1) && (nPercent <= 99))
							{
								pArgs->nSplitValue = (100-nPercent) * 10;
							}						
							//pArgs->nSplitPane = 0; Сбрасывать не будем?
						}
						pDlg->mn_DlgRc = IDC_START;
						EndDialog(hDlg, IDC_START);
						return 1;
					}
					case IDC_TERMINATE:
						pDlg->mn_DlgRc = IDC_TERMINATE;
						EndDialog(hDlg, IDC_TERMINATE);
						return 1;
					case IDCANCEL:
						pDlg->mn_DlgRc = IDCANCEL;
						EndDialog(hDlg, IDCANCEL);
						return 1;
				}
			}
			else if ((HIWORD(wParam) == EN_SETFOCUS) && lParam)
			{
				switch (LOWORD(wParam))
				{
				case tRecreateSplit:
				case tRunAsPassword:
					PostMessage((HWND)lParam, EM_SETSEL, 0, SendMessage((HWND)lParam, WM_GETTEXTLENGTH, 0,0));
					break;
				}
			}

			break;
		default:
			return 0;
	}
예제 #8
0
파일: User.cpp 프로젝트: bpcampbe/znc
bool CUser::WriteConfig(CFile& File) {
	File.Write("<User " + GetUserName().FirstLine() + ">\n");

	if (m_eHashType != HASH_NONE) {
		CString sHash = "md5";
		if (m_eHashType == HASH_SHA256)
			sHash = "sha256";
		if (m_sPassSalt.empty()) {
			PrintLine(File, "Pass", sHash + "#" + GetPass());
		} else {
			PrintLine(File, "Pass", sHash + "#" + GetPass() + "#" + m_sPassSalt + "#");
		}
	} else {
		PrintLine(File, "Pass", "plain#" + GetPass());
	}
	PrintLine(File, "Nick", GetNick());
	PrintLine(File, "AltNick", GetAltNick());
	PrintLine(File, "Ident", GetIdent());
	PrintLine(File, "RealName", GetRealName());
	PrintLine(File, "BindHost", GetBindHost());
	PrintLine(File, "DCCBindHost", GetDCCBindHost());
	PrintLine(File, "QuitMsg", GetQuitMsg());
	if (CZNC::Get().GetStatusPrefix() != GetStatusPrefix())
		PrintLine(File, "StatusPrefix", GetStatusPrefix());
	PrintLine(File, "Skin", GetSkinName());
	PrintLine(File, "ChanModes", GetDefaultChanModes());
	PrintLine(File, "Buffer", CString(GetBufferCount()));
	PrintLine(File, "KeepBuffer", CString(KeepBuffer()));
	PrintLine(File, "MultiClients", CString(MultiClients()));
	PrintLine(File, "BounceDCCs", CString(BounceDCCs()));
	PrintLine(File, "DenyLoadMod", CString(DenyLoadMod()));
	PrintLine(File, "Admin", CString(IsAdmin()));
	PrintLine(File, "DenySetBindHost", CString(DenySetBindHost()));
	PrintLine(File, "DCCLookupMethod", CString((UseClientIP()) ? "client" : "default"));
	PrintLine(File, "TimestampFormat", GetTimestampFormat());
	PrintLine(File, "AppendTimestamp", CString(GetTimestampAppend()));
	PrintLine(File, "PrependTimestamp", CString(GetTimestampPrepend()));
	PrintLine(File, "TimezoneOffset", CString(m_fTimezoneOffset));
	PrintLine(File, "JoinTries", CString(m_uMaxJoinTries));
	PrintLine(File, "MaxJoins", CString(m_uMaxJoins));
	PrintLine(File, "IRCConnectEnabled", CString(GetIRCConnectEnabled()));
	File.Write("\n");

	// Allow Hosts
	if (!m_ssAllowedHosts.empty()) {
		for (set<CString>::iterator it = m_ssAllowedHosts.begin(); it != m_ssAllowedHosts.end(); ++it) {
			PrintLine(File, "Allow", *it);
		}

		File.Write("\n");
	}

	// CTCP Replies
	if (!m_mssCTCPReplies.empty()) {
		for (MCString::const_iterator itb = m_mssCTCPReplies.begin(); itb != m_mssCTCPReplies.end(); ++itb) {
			PrintLine(File, "CTCPReply", itb->first.AsUpper() + " " + itb->second);
		}

		File.Write("\n");
	}

	// Modules
	CModules& Mods = GetModules();

	if (!Mods.empty()) {
		for (unsigned int a = 0; a < Mods.size(); a++) {
			CString sArgs = Mods[a]->GetArgs();

			if (!sArgs.empty()) {
				sArgs = " " + sArgs;
			}

			PrintLine(File, "LoadModule", Mods[a]->GetModName() + sArgs);
		}

		File.Write("\n");
	}

	// Servers
	for (unsigned int b = 0; b < m_vServers.size(); b++) {
		PrintLine(File, "Server", m_vServers[b]->GetString());
	}

	// Chans
	for (unsigned int c = 0; c < m_vChans.size(); c++) {
		CChan* pChan = m_vChans[c];
		if (pChan->InConfig()) {
			File.Write("\n");
			if (!pChan->WriteConfig(File)) {
				return false;
			}
		}
	}

	File.Write("</User>\n");

	return true;
}
예제 #9
0
	void ServerConnection::thread()
	{
		while (!running)
		{
		#ifdef WIN32
			Sleep(1);
		#else
			usleep(1000);
		#endif
		}
		char hostname[1024] = "";
		char applicationName[1024] = "";
		char username[1024] = "";

		#ifdef WIN32
		gethostname(hostname, 1024);
		::GetModuleFileName(0, applicationName, 1024);
		DWORD username_len = 1024;
		GetUserName(username, &username_len);
		#endif

		std::time_t startTime = std::time(nullptr);

		bool lastConnected = true;
		while (running)
		{
			struct sockaddr_in addr;
			struct hostent* host;

			std::string ipAddr = config["ip"];

			host = gethostbyname(ipAddr.c_str());
			if (host == NULL)
			{
				logger << "Could not look up host " << config["ip"] << "', are you connected to the internet?";
				return;
			}
			addr.sin_family = host->h_addrtype;
			memcpy((char*)&addr.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
			addr.sin_port = htons(config["port"]);
			memset(addr.sin_zero, 0, 8);

			SOCKET tempSocket = 0;

			if ((tempSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
			{
				logger << "Cannot create socket, try a reboot" << Log::newline;
				closesocket(s);
				#ifdef WIN32
				Sleep(60000);
				#else
				sleep(60);
				#endif
				continue;
			}

			int rc;
			int siz = sizeof(addr);
			rc = ::connect(tempSocket, (struct sockaddr*) &addr, siz);
			if (rc < 0)
			{
				if(lastConnected)
					logger << "Could not connect to api host: " << config["ip"] << Log::newline;
				lastConnected = false;
				closesocket(tempSocket);
				#ifdef WIN32
				Sleep(1000);
				#else
				sleep(1);
				#endif
				continue;
			}
			lastConnected = true;
			logger << "Connected to remote API" << Log::newline;

			json packet;
			packet["id"] = "session/start";
			packet["data"]["host"] = hostname;
			packet["data"]["file"] = applicationName;
			packet["data"]["renderer"] = std::string((char*)renderer);
			packet["data"]["starttime"] = (int)startTime;
			packet["data"]["user"] = username;
			send(packet, tempSocket);

			s = tempSocket;

			std::string buffer;
			char buf[1024];
			while (running && s != 0)
			{
				int rc = recv(s, buf, 1024, 0);
				if (rc < 0)
				{
					closesocket(s);
					s = 0;
					break;
				}
				buffer += std::string(buf, rc);
				while (buffer.size() > 4)
				{
					unsigned int len = *((unsigned int*)&buffer[0]);
					if (buffer.size() >= len + 4)
					{
						json data = json::parse(buffer.substr(4, len));
						buffer = buffer.substr(4 + len);

						if (data.find("id") == data.end())
						{
							logger << "Invalid packet from server" << Log::newline;
							logger << data << Log::newline;
							closesocket(s);
							s = 0;
							break;
						}

						if (callbacks.find(data["id"]) != callbacks.end()) {
							callbacks[data["id"]](data);
						}
						else if (singleCallbacks.find(data["id"]) != singleCallbacks.end()) {
							singleCallbacks[data["id"]](data);
							singleCallbacks.erase(singleCallbacks.find(data["id"]));
						}
						else
						{
							logger << "Invalid packet from server" << Log::newline;
							logger << data.dump() << Log::newline;
							//closesocket(s);
							//s = 0;
							//break;
						}
					}
					else
						break;
				}
			}
			lastConnected = false;
			logger << "Disconnected...." << Log::newline;
#ifdef WIN32
			Sleep(1000);
#else
			sleep(1);
#endif
		}
	}
예제 #10
0
파일: User.cpp 프로젝트: bpcampbe/znc
bool CUser::ParseConfig(CConfig* pConfig, CString& sError) {
	TOption<const CString&> StringOptions[] = {
		{ "nick", &CUser::SetNick },
		{ "quitmsg", &CUser::SetQuitMsg },
		{ "altnick", &CUser::SetAltNick },
		{ "ident", &CUser::SetIdent },
		{ "realname", &CUser::SetRealName },
		{ "chanmodes", &CUser::SetDefaultChanModes },
		{ "bindhost", &CUser::SetBindHost },
		{ "vhost", &CUser::SetBindHost },
		{ "dccbindhost", &CUser::SetDCCBindHost },
		{ "dccvhost", &CUser::SetDCCBindHost },
		{ "timestampformat", &CUser::SetTimestampFormat },
		{ "skin", &CUser::SetSkinName },
	};
	size_t numStringOptions = sizeof(StringOptions) / sizeof(StringOptions[0]);
	TOption<unsigned int> UIntOptions[] = {
		{ "jointries", &CUser::SetJoinTries },
		{ "maxjoins", &CUser::SetMaxJoins },
	};
	size_t numUIntOptions = sizeof(UIntOptions) / sizeof(UIntOptions[0]);
	TOption<bool> BoolOptions[] = {
		{ "keepbuffer", &CUser::SetKeepBuffer },
		{ "multiclients", &CUser::SetMultiClients },
		{ "bouncedccs", &CUser::SetBounceDCCs },
		{ "denyloadmod", &CUser::SetDenyLoadMod },
		{ "admin", &CUser::SetAdmin },
		{ "denysetbindhost", &CUser::SetDenySetBindHost },
		{ "denysetvhost", &CUser::SetDenySetBindHost },
		{ "appendtimestamp", &CUser::SetTimestampAppend },
		{ "prependtimestamp", &CUser::SetTimestampPrepend },
		{ "ircconnectenabled", &CUser::SetIRCConnectEnabled },
	};
	size_t numBoolOptions = sizeof(BoolOptions) / sizeof(BoolOptions[0]);

	for (size_t i = 0; i < numStringOptions; i++) {
		CString sValue;
		if (pConfig->FindStringEntry(StringOptions[i].name, sValue))
			(this->*StringOptions[i].pSetter)(sValue);
	}
	for (size_t i = 0; i < numUIntOptions; i++) {
		CString sValue;
		if (pConfig->FindStringEntry(UIntOptions[i].name, sValue))
			(this->*UIntOptions[i].pSetter)(sValue.ToUInt());
	}
	for (size_t i = 0; i < numBoolOptions; i++) {
		CString sValue;
		if (pConfig->FindStringEntry(BoolOptions[i].name, sValue))
			(this->*BoolOptions[i].pSetter)(sValue.ToBool());
	}

	VCString vsList;
	VCString::const_iterator vit;
	pConfig->FindStringVector("allow", vsList);
	for (vit = vsList.begin(); vit != vsList.end(); ++vit) {
		AddAllowedHost(*vit);
	}
	pConfig->FindStringVector("ctcpreply", vsList);
	for (vit = vsList.begin(); vit != vsList.end(); ++vit) {
		const CString& sValue = *vit;
		AddCTCPReply(sValue.Token(0), sValue.Token(1, true));
	}
	pConfig->FindStringVector("server", vsList);
	for (vit = vsList.begin(); vit != vsList.end(); ++vit) {
		CUtils::PrintAction("Adding Server [" + *vit + "]");
		CUtils::PrintStatus(AddServer(*vit));
	}
	pConfig->FindStringVector("chan", vsList);
	for (vit = vsList.begin(); vit != vsList.end(); ++vit) {
		AddChan(*vit, true);
	}

	CString sValue;
	if (pConfig->FindStringEntry("buffer", sValue))
		SetBufferCount(sValue.ToUInt(), true);
	if (pConfig->FindStringEntry("awaysuffix", sValue)) {
		CUtils::PrintMessage("WARNING: AwaySuffix has been depricated, instead try -> LoadModule = awaynick %nick%_" + sValue);
	}
	if (pConfig->FindStringEntry("autocycle", sValue)) {
		if (sValue.Equals("true"))
			CUtils::PrintError("WARNING: AutoCycle has been removed, instead try -> LoadModule = autocycle");
	}
	if (pConfig->FindStringEntry("keepnick", sValue)) {
		if (sValue.Equals("true"))
			CUtils::PrintError("WARNING: KeepNick has been deprecated, instead try -> LoadModule = keepnick");
	}
	if (pConfig->FindStringEntry("statusprefix", sValue)) {
		if (!SetStatusPrefix(sValue)) {
			sError = "Invalid StatusPrefix [" + sValue + "] Must be 1-5 chars, no spaces.";
			CUtils::PrintError(sError);
			return false;
		}
	}
	if (pConfig->FindStringEntry("timezoneoffset", sValue)) {
		SetTimezoneOffset(sValue.ToDouble());
	}
	if (pConfig->FindStringEntry("timestamp", sValue)) {
		if (!sValue.Trim_n().Equals("true")) {
			if (sValue.Trim_n().Equals("append")) {
				SetTimestampAppend(true);
				SetTimestampPrepend(false);
			} else if (sValue.Trim_n().Equals("prepend")) {
				SetTimestampAppend(false);
				SetTimestampPrepend(true);
			} else if (sValue.Trim_n().Equals("false")) {
				SetTimestampAppend(false);
				SetTimestampPrepend(false);
			} else {
				SetTimestampFormat(sValue);
			}
		}
	}
	if (pConfig->FindStringEntry("dcclookupmethod", sValue))
		SetUseClientIP(sValue.Equals("Client"));
	pConfig->FindStringEntry("pass", sValue);
	// There are different formats for this available:
	// Pass = <plain text>
	// Pass = <md5 hash> -
	// Pass = plain#<plain text>
	// Pass = <hash name>#<hash>
	// Pass = <hash name>#<salted hash>#<salt>#
	// 'Salted hash' means hash of 'password' + 'salt'
	// Possible hashes are md5 and sha256
	if (sValue.Right(1) == "-") {
		sValue.RightChomp();
		sValue.Trim();
		SetPass(sValue, CUser::HASH_MD5);
	} else {
		CString sMethod = sValue.Token(0, false, "#");
		CString sPass = sValue.Token(1, true, "#");
		if (sMethod == "md5" || sMethod == "sha256") {
			CUser::eHashType type = CUser::HASH_MD5;
			if (sMethod == "sha256")
				type = CUser::HASH_SHA256;

			CString sSalt = sPass.Token(1, false, "#");
			sPass = sPass.Token(0, false, "#");
			SetPass(sPass, type, sSalt);
		} else if (sMethod == "plain") {
			SetPass(sPass, CUser::HASH_NONE);
		} else {
			SetPass(sValue, CUser::HASH_NONE);
		}
	}

	CConfig::SubConfig subConf;
	CConfig::SubConfig::const_iterator subIt;
	pConfig->FindSubConfig("chan", subConf);
	for (subIt = subConf.begin(); subIt != subConf.end(); ++subIt) {
		const CString& sChanName = subIt->first;
		CConfig* pSubConf = subIt->second.m_pSubConfig;
		CChan* pChan = new CChan(sChanName, this, true, pSubConf);

		if (!pSubConf->empty()) {
			sError = "Unhandled lines in config for User [" + GetUserName() + "], Channel [" + sChanName + "]!";
			CUtils::PrintError(sError);

			CZNC::DumpConfig(pSubConf);
			return false;
		}

		// Save the channel name, because AddChan
		// deletes the CChannel*, if adding fails
		sError = pChan->GetName();
		if (!AddChan(pChan)) {
			sError = "Channel [" + sError + "] defined more than once";
			CUtils::PrintError(sError);
			return false;
		}
		sError.clear();
	}

	pConfig->FindStringVector("loadmodule", vsList);
	for (vit = vsList.begin(); vit != vsList.end(); ++vit) {
		sValue = *vit;
		CString sModName = sValue.Token(0);

		// XXX Legacy crap, added in znc 0.089
		if (sModName == "discon_kick") {
			CUtils::PrintMessage("NOTICE: [discon_kick] was renamed, loading [disconkick] instead");
			sModName = "disconkick";
		}

		CUtils::PrintAction("Loading Module [" + sModName + "]");
		CString sModRet;
		CString sArgs = sValue.Token(1, true);

		bool bModRet = GetModules().LoadModule(sModName, sArgs, this, sModRet);

		CUtils::PrintStatus(bModRet, sModRet);
		if (!bModRet) {
			sError = sModRet;
			return false;
		}
		continue;
	}

	return true;
}
예제 #11
0
파일: User.cpp 프로젝트: bpcampbe/znc
bool CUser::Clone(const CUser& User, CString& sErrorRet, bool bCloneChans) {
	unsigned int a = 0;
	sErrorRet.clear();

	if (!User.IsValid(sErrorRet, true)) {
		return false;
	}

	// user names can only specified for the constructor, changing it later
	// on breaks too much stuff (e.g. lots of paths depend on the user name)
	if (GetUserName() != User.GetUserName()) {
		DEBUG("Ignoring username in CUser::Clone(), old username [" << GetUserName()
				<< "]; New username [" << User.GetUserName() << "]");
	}

	if (!User.GetPass().empty()) {
		SetPass(User.GetPass(), User.GetPassHashType(), User.GetPassSalt());
	}

	SetNick(User.GetNick(false));
	SetAltNick(User.GetAltNick(false));
	SetIdent(User.GetIdent(false));
	SetRealName(User.GetRealName());
	SetStatusPrefix(User.GetStatusPrefix());
	SetBindHost(User.GetBindHost());
	SetDCCBindHost(User.GetDCCBindHost());
	SetQuitMsg(User.GetQuitMsg());
	SetSkinName(User.GetSkinName());
	SetDefaultChanModes(User.GetDefaultChanModes());
	SetBufferCount(User.GetBufferCount(), true);
	SetJoinTries(User.JoinTries());
	SetMaxJoins(User.MaxJoins());

	// Allowed Hosts
	m_ssAllowedHosts.clear();
	const set<CString>& ssHosts = User.GetAllowedHosts();
	for (set<CString>::const_iterator it = ssHosts.begin(); it != ssHosts.end(); ++it) {
		AddAllowedHost(*it);
	}

	for (a = 0; a < m_vClients.size(); a++) {
		CClient* pSock = m_vClients[a];

		if (!IsHostAllowed(pSock->GetRemoteIP())) {
			pSock->PutStatusNotice("You are being disconnected because your IP is no longer allowed to connect to this user");
			pSock->Close();
		}
	}

	// !Allowed Hosts

	// Servers
	const vector<CServer*>& vServers = User.GetServers();
	CString sServer;
	CServer* pCurServ = GetCurrentServer();

	if (pCurServ) {
		sServer = pCurServ->GetName();
	}

	DelServers();

	for (a = 0; a < vServers.size(); a++) {
		CServer* pServer = vServers[a];
		AddServer(pServer->GetName(), pServer->GetPort(), pServer->GetPass(), pServer->IsSSL());
	}

	m_uServerIdx = 0;
	for (a = 0; a < m_vServers.size(); a++) {
		if (sServer.Equals(m_vServers[a]->GetName())) {
			m_uServerIdx = a + 1;
			break;
		}
	}
	if (m_uServerIdx == 0) {
		m_uServerIdx = m_vServers.size();
		CIRCSock* pSock = GetIRCSock();

		if (pSock) {
			PutStatus("Jumping servers because this server is no longer in the list");
			pSock->Quit();
		}
	}
	// !Servers

	// Chans
	const vector<CChan*>& vChans = User.GetChans();
	for (a = 0; a < vChans.size(); a++) {
		CChan* pNewChan = vChans[a];
		CChan* pChan = FindChan(pNewChan->GetName());

		if (pChan) {
			pChan->SetInConfig(pNewChan->InConfig());
		} else {
			AddChan(pNewChan->GetName(), pNewChan->InConfig());
		}
	}

	for (a = 0; a < m_vChans.size(); a++) {
		CChan* pChan = m_vChans[a];
		CChan* pNewChan = User.FindChan(pChan->GetName());

		if (!pNewChan) {
			pChan->SetInConfig(false);
		} else {
			if (bCloneChans)
				pChan->Clone(*pNewChan);
		}
	}
	// !Chans

	// CTCP Replies
	m_mssCTCPReplies.clear();
	const MCString& msReplies = User.GetCTCPReplies();
	for (MCString::const_iterator it = msReplies.begin(); it != msReplies.end(); ++it) {
		AddCTCPReply(it->first, it->second);
	}
	// !CTCP Replies

	// Flags
	SetIRCConnectEnabled(User.GetIRCConnectEnabled());
	SetKeepBuffer(User.KeepBuffer());
	SetMultiClients(User.MultiClients());
	SetBounceDCCs(User.BounceDCCs());
	SetUseClientIP(User.UseClientIP());
	SetDenyLoadMod(User.DenyLoadMod());
	SetAdmin(User.IsAdmin());
	SetDenySetBindHost(User.DenySetBindHost());
	SetTimestampAppend(User.GetTimestampAppend());
	SetTimestampPrepend(User.GetTimestampPrepend());
	SetTimestampFormat(User.GetTimestampFormat());
	SetTimezoneOffset(User.GetTimezoneOffset());
	// !Flags

	// Modules
	set<CString> ssUnloadMods;
	CModules& vCurMods = GetModules();
	const CModules& vNewMods = User.GetModules();

	for (a = 0; a < vNewMods.size(); a++) {
		CString sModRet;
		CModule* pNewMod = vNewMods[a];
		CModule* pCurMod = vCurMods.FindModule(pNewMod->GetModName());

		if (!pCurMod) {
			vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(), this, sModRet);
		} else if (pNewMod->GetArgs() != pCurMod->GetArgs()) {
			vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(), this, sModRet);
		}
	}

	for (a = 0; a < vCurMods.size(); a++) {
		CModule* pCurMod = vCurMods[a];
		CModule* pNewMod = vNewMods.FindModule(pCurMod->GetModName());

		if (!pNewMod) {
			ssUnloadMods.insert(pCurMod->GetModName());
		}
	}

	for (set<CString>::iterator it = ssUnloadMods.begin(); it != ssUnloadMods.end(); ++it) {
		vCurMods.UnloadModule(*it);
	}
	// !Modules

	return true;
}
예제 #12
0
void
WUploadThread::MessageReceived(const MessageRef & msg, const String & /* sessionID */)
{
	PRINT("WUploadThread::MessageReceived\n");
	switch (msg()->what)
	{
		case WTransfer::TransferCommandPeerID:
		{
			PRINT("WUpload::TransferCommandPeerID\n");
			const char *id = NULL;
                        if (msg()->FindString("beshare:FromSession", id) == B_OK)
			{
				fRemoteSessionID = QString::fromUtf8(id);

				{
					const char *name = NULL;

                                        if (msg()->FindString("beshare:FromUserName", name) ==  B_OK)
					{
						QString user = QString::fromUtf8(name);
						if ((user.isEmpty()) || (fRemoteUser == fRemoteSessionID))
							fRemoteUser = GetUserName(fRemoteSessionID);
						else
							fRemoteUser = user;
					}
					else
					{
						fRemoteUser = GetUserName(fRemoteSessionID);
					}
				}

				if (gWin->IsIgnored(fRemoteSessionID, true))
				{
					SetBlocked(true);
				}

				WUploadEvent *ui = new WUploadEvent(WUploadEvent::UpdateUI);
				if (ui)
				{
//					ui->SetSession(id);
					SendReply(ui);
				}

			}

			bool c = false;

                        if (!fTunneled && msg()->FindBool("unishare:supports_compression", c) == B_OK)
			{
				SetCompression(6);
			}

			double dpps = GetPacketSize() * 1024.0;
			int32 pps = lrint(dpps);

                        if ((msg()->FindInt32("unishare:preferred_packet_size", pps) == B_OK) && (pps < lrint(dpps)))
				SetPacketSize((double) pps / 1024.0);
			break;
		}

		case WTransfer::TransferFileList:
		{
			// TransferFileList(msg);
			WMessageEvent *wme = new WMessageEvent(msg);
			if (wme)
			{
				QApplication::postEvent(this, wme);
			}
			break;
		}
	}
}
예제 #13
0
void
WUploadThread::TransferFileList(MessageRef msg)
{
	PRINT("WUploadThread::TransferFileList\n");

	if (msg())
	{

		if (fShutdownFlag && *fShutdownFlag)	// do we need to abort?
		{
			Reset();
			return;
		}

		if (gWin->IsScanning())
		{
			fSavedFileList = msg;
			if (!fBlocked)
			{
				SetLocallyQueued(true);
				SendQueuedNotification();
			}
			return;
		}

		QString user;

		if (GetInt32FromMessage(msg, "mm", fMungeMode) != B_OK)
			fMungeMode = WTransfer::MungeModeNone;

		GetStringFromMessage(msg, "beshare:FromSession", fRemoteSessionID);

		if (GetStringFromMessage(msg, "beshare:FromUserName", user) ==  B_OK)
		{
			if (!user.isEmpty() && (user != fRemoteSessionID))
				fRemoteUser = user;
		}
		if (fRemoteUser == QString::null)
		{
			fRemoteUser = GetUserName(fRemoteSessionID);
		}

		QString file;

		for (int i = 0; (GetStringFromMessage(msg, "files", i, file) == B_OK); i++)
		{
			MessageRef fileRef;

			if (fFileThread->FindFile(file, fileRef))
			{
				if (fileRef()) // <*****@*****.**> 20021023
				{
					// see if we need to add them
					int64 offset = 0L;
					ByteBufferRef hisDigest;
					uint32 numBytes = 0L;
					if (msg()->FindInt64("offsets", i, offset) == B_OK &&
						msg()->FindFlat("md5", i, hisDigest) == B_OK &&
						numBytes == MD5_DIGEST_SIZE)
					{
						uint8 myDigest[MD5_DIGEST_SIZE];
						uint64 readLen = 0;
						int64 onSuccessOffset = offset;

						for (uint32 j = 0; j < ARRAYITEMS(myDigest); j++)
							myDigest[j] = 'x';

						if ((msg()->FindInt64("numbytes", i, readLen) == B_OK) && (readLen > 0))
						{
							PRINT("\t\tULT: peer requested partial resume\n");
							int64 temp = readLen;
							readLen = offset - readLen; // readLen is now the seekTo value
							offset = temp;				// offset is now the numBytes value
						}

						// figure the path to our requested file
						QString file = MakeUploadPath(fileRef);

						// Notify window of our hashing
						WUploadEvent *hash = new WUploadEvent(WUploadEvent::FileHashing);
						if (hash)
						{
							hash->SetFile(SimplifyPath(file));
							SendReply(hash);
						}

						// Hash

						if (HashFileMD5(file, offset, readLen, NULL, myDigest, fShutdownFlag) == B_OK &&
							memcmp((const uint8*) hisDigest()->GetBuffer(), myDigest, sizeof(myDigest)) == 0)
						{
							// put this into our message ref
							fileRef.EnsureRefIsPrivate();
							fileRef()->AddInt64("secret:offset", (int64) onSuccessOffset);
						}
					}

					fUploads.AddTail(fileRef);
					fNames.AddTail(file);
				}
			}
		}

		msg()->GetInfo("files", NULL, &fNumFiles);

		fWaitingForUploadToFinish = false;
		SendQueuedNotification();

		// also send a message along to our GUI telling it what the first file is

		if (fUploads.IsEmpty())
		{
			PRINT("WUploadThread: No Files!!!\n");
			Reset();
			return;
		}

		if (IsLocallyQueued())
		{
			MessageRef fref;
			fUploads.GetItemAt(0, fref);
			if (fref())
			{
				QString filename = MakeUploadPath(fref);

				if (!filename.isEmpty())
				{
					// Check file size if is smaller than minimum size wanted for queue
					int64 filesize;
					if (fref()->FindInt64("beshare:File Size", filesize) == B_OK)
					{
						if (filesize < gWin->fSettings->GetMinQueuedSize())
						{
							SignalUpload();
							return;
						}
					}

					WUploadEvent *init = new WUploadEvent(WUploadEvent::Init);
					if (init)
					{
						init->SetFile(SimplifyPath(filename));
//						init->SetSession(fRemoteSessionID);
						SendReply(init);
					}
				}
			}
		}
		else
		{
			SignalUpload();
			return;
		}

	}
}
예제 #14
0
char *par_mktmpdir ( char **argv ) {
    int i;
    const char *tmpdir = NULL;
    const char *key = NULL , *val = NULL;

    /* NOTE: all arrays below are NULL terminated */
    const char *temp_dirs[] = { 
        P_tmpdir, 
#ifdef WIN32
        "C:\\TEMP", 
#endif
        ".", NULL };
    const char *temp_keys[] = { "PAR_TMPDIR", "TMPDIR", "TEMPDIR", 
                                 "TEMP", "TMP", NULL };
    const char *user_keys[] = { "USER", "USERNAME", NULL };

    const char *subdirbuf_prefix = "par-";
    const char *subdirbuf_suffix = "";

    char *progname = NULL, *username = NULL;
    char *stmpdir = NULL, *top_tmpdir = NULL;
    int f, j, k, stmp_len = 0;
    char sha1[41];
    SHA_INFO sha_info;
    unsigned char buf[32768];
    unsigned char sha_data[20];

    if ( (val = par_getenv(PAR_TEMP)) && strlen(val) ) {
        par_setup_libpath(val);
        return strdup(val);
    }

#ifdef WIN32
    {
        DWORD buflen = MAXPATHLEN;
        username = malloc(MAXPATHLEN);
        GetUserName((LPTSTR)username, &buflen);
        // FIXME this is uncondifionally overwritten below - WTF?
    }
#endif

    /* Determine username */
    username = get_username_from_getpwuid();
    if ( !username ) { /* fall back to env vars */
        for ( i = 0 ; username == NULL && (key = user_keys[i]); i++) {
            if ( (val = par_getenv(key)) && strlen(val) ) 
                username = strdup(val);
        }
    }
    if ( username == NULL )
        username = "******";
   
    /* sanitize username: encode all bytes as 2 hex digits */
    {
        char *hexname = malloc(2 * strlen(username) + 1);
        char *u, *h;
        for ( u = username, h = hexname ; *u != '\0' ; u++, h += 2)
            sprintf(h, "%02x", *(unsigned char*)u);
        username = hexname;
    }

    /* Try temp environment variables */
    for ( i = 0 ; tmpdir == NULL && (key = temp_keys[i]); i++ ) {
        if ( (val = par_getenv(key)) && strlen(val) && isWritableDir(val) ) {
            tmpdir = strdup(val);
            break;
        }
    }

#ifdef WIN32
    /* Try the windows temp directory */
    if ( tmpdir == NULL && (val = par_getenv("WinDir")) && strlen(val) ) {
        char* buf = malloc(strlen(val) + 5 + 1);
        sprintf(buf, "%s\\temp", val);
        if (isWritableDir(buf)) {
            tmpdir = buf;
        } else {
            free(buf);
        }
    }
#endif

    /* Try default locations */
    for ( i = 0 ; tmpdir == NULL && (val = temp_dirs[i]) && strlen(val) ; i++ ) {
        if ( isWritableDir(val) ) {
            tmpdir = strdup(val);
        }
    }

    /* "$TEMP/par-$USER" */
    stmp_len = 
        strlen(tmpdir) +
        strlen(subdirbuf_prefix) +
        strlen(username) +
        strlen(subdirbuf_suffix) + 1024;

    /* stmpdir is what we are going to return; 
       top_tmpdir is the top $TEMP/par-$USER, needed to build stmpdir.  
       NOTE: We need 2 buffers because snprintf() can't write to a buffer
       it is also reading from. */
    top_tmpdir = malloc( stmp_len );
    sprintf(top_tmpdir, "%s%s%s%s", tmpdir, dir_sep, subdirbuf_prefix, username);
#ifdef WIN32
    _mkdir(top_tmpdir);         /* FIXME bail if error (other than EEXIST) */
#else
    {
        if (mkdir(top_tmpdir, 0700) == -1 && errno != EEXIST) {
            fprintf(stderr, "%s: creation of private subdirectory %s failed (errno=%i)\n", 
                    argv[0], top_tmpdir, errno);
            return NULL;
        }

        if (!isSafeDir(top_tmpdir)) {
            fprintf(stderr, "%s: private subdirectory %s is unsafe (please remove it and retry your operation)\n",
                    argv[0], top_tmpdir);
            return NULL;
        }
    }
#endif

    stmpdir = malloc( stmp_len );

    /* Doesn't really work - XXX */
    val = par_getenv( "PATH" );
    if (val != NULL)
        progname = par_findprog(argv[0], strdup(val));
    if (progname == NULL)
        progname = argv[0];

    /* If invoked as "/usr/bin/parl foo.par myscript.pl" then progname should
     * be ".../parl", and we don't want to base our checksum on that, but
     * rather on "foo.par".
     */
    {
#ifdef WIN32
#define STREQ(a,b) (strcasecmp(a,b) == 0)
#else
#define STREQ(a,b) (strcmp(a,b) == 0)
#endif
	int prog_len = strlen(progname);
	int parl_len = strlen(PARL_EXE);

	if (prog_len >= parl_len
	    && STREQ(progname + prog_len - parl_len, PARL_EXE)
	    && (prog_len == parl_len || progname[prog_len - parl_len - 1] == dir_sep[0])
	    && argv[1]
	    && strlen(argv[1]) >= 4
	    && STREQ(argv[1] + strlen(argv[1]) - 4, ".par"))
		progname = argv[1];
#undef STREQ
    }

    if ( !par_env_clean() && (f = open( progname, O_RDONLY | OPEN_O_BINARY ))) {
        lseek(f, -18, 2);
        read(f, buf, 6);
        if(buf[0] == 0 && buf[1] == 'C' && buf[2] == 'A' && buf[3] == 'C' && buf[4] == 'H' && buf[5] == 'E') {
            /* pre-computed cache_name in this file */
            /* "$TEMP/par-$USER/cache-$cache_name" */
            lseek(f, -58, 2);
            read(f, buf, 41);
            sprintf(
                stmpdir,
                "%s%scache-%s%s",
                top_tmpdir, dir_sep, buf, subdirbuf_suffix
            );
        }
        else {
            /* "$TEMP/par-$USER/cache-$SHA1" */
	    lseek(f, 0, 0);
            sha_init( &sha_info );
            while( ( j = read( f, buf, sizeof( buf ) ) ) > 0 )
            {
                sha_update( &sha_info, buf, j );
            }
            close( f );
            sha_final( sha_data, &sha_info );
            for( k = 0; k < 20; k++ )
            {
                sprintf( sha1+k*2, "%02x", sha_data[k] );
            }
            sha1[40] = '\0';
            sprintf(
                stmpdir,
                "%s%scache-%s%s",
                top_tmpdir, dir_sep, sha1, subdirbuf_suffix
            );
        }
    }
    else {
        int i = 0;

        /* "$TEMP/par-$USER/temp-$PID" */

        par_setenv("PAR_CLEAN", "1");
        sprintf(
            stmpdir,
            "%s%stemp-%u%s",
            top_tmpdir, dir_sep, getpid(), subdirbuf_suffix
        );

        /* Ensure we pick an unused directory each time.  If the directory
           already exists when we try to create it, bump a counter and try
           "$TEMP/par-$USER/temp-$PID-$i". This will guard against cases where
           a prior invocation crashed leaving garbage in a temp directory that
           might interfere. */

        while (my_mkdir(stmpdir, 0700) == -1 && errno == EEXIST) {
            sprintf(
                stmpdir,
                "%s%stemp-%u-%u%s",
                top_tmpdir, dir_sep, getpid(), ++i, subdirbuf_suffix
                );
        }
    }

    free(top_tmpdir);

    /* set dynamic loading path */
    par_setenv(PAR_TEMP, stmpdir);

    par_setup_libpath( stmpdir );

    return stmpdir;
}
예제 #15
0
void *mdsip_connect(char *host)
{
  static int activated=0;
  int status;
  static globus_xio_stack_t stack_tcp;
  static globus_xio_stack_t stack_gsi;
  static globus_xio_driver_t tcp_driver;
  static globus_xio_driver_t gsi_driver;
  globus_result_t result;
  globus_xio_handle_t xio_handle;
  globus_xio_attr_t attr;
  char *contact_string;
  int is_gsi;
  mdsip_message_t *m;

  if (activated == 0)
  {
    result = globus_module_activate(GLOBUS_XIO_MODULE);
    mdsip_test_status(0,result,"mdsip_connect globus_module_activate");
    if (result != GLOBUS_SUCCESS) return 0;
    result = globus_xio_driver_load("tcp",&tcp_driver);
    mdsip_test_status(0,result,"mdsip_connect load tcp driver");
    if (result != GLOBUS_SUCCESS) return 0;
    result = globus_xio_driver_load("gsi",&gsi_driver);
    mdsip_test_status(0,result,"mdsip_connect load gsi driver");
    if (result != GLOBUS_SUCCESS) return 0;
    result = globus_xio_stack_init(&stack_tcp, NULL);
    mdsip_test_status(0,result,"mdsip_connect globus_xio_stack_init");
    if (result != GLOBUS_SUCCESS) return 0;
    result = globus_xio_stack_init(&stack_gsi, NULL);
    mdsip_test_status(0,result,"mdsip_connect globus_xio_stack_init");
    if (result != GLOBUS_SUCCESS) return 0;
    result = globus_xio_stack_push_driver(stack_tcp, tcp_driver);
    mdsip_test_status(0,result,"mdsip_connect globus_xio_stack_push_driver");
    if (result != GLOBUS_SUCCESS) return 0;
    result = globus_xio_stack_push_driver(stack_gsi, tcp_driver);
    mdsip_test_status(0,result,"mdsip_connect globus_xio_stack_push_driver");
    if (result != GLOBUS_SUCCESS) return 0;
    result = globus_xio_stack_push_driver(stack_gsi, gsi_driver);
    mdsip_test_status(0,result,"mdsip_connect globus_xio_stack_push_driver");
    if (result != GLOBUS_SUCCESS) return 0;
    activated = 1;
  }

  if (host == NULL || strlen(host) == 0)
    return 0;
  is_gsi = host[0] == '_';
  result = globus_xio_handle_create(&xio_handle, is_gsi ? stack_gsi : stack_tcp);
  mdsip_test_status(0,result,"mdsip_connect globus_xio_handle_create");
  if (result != GLOBUS_SUCCESS) return 0;

  contact_string = strcpy((char *)malloc(strlen(host)+10),&host[is_gsi ? 1 : 0]);
  
  if (strstr(contact_string,":") == NULL)
    strcat(contact_string,is_gsi ? ":8200" : ":8000");
  result = globus_xio_attr_init(&attr);
  mdsip_test_status(0,result,"mdsip_connect globus_xio_attr_init");
  if (result != GLOBUS_SUCCESS) return 0;
  if (is_gsi)
  {
    result = globus_xio_attr_cntl(attr,gsi_driver,GLOBUS_XIO_GSI_SET_DELEGATION_MODE,
				  GLOBUS_XIO_GSI_DELEGATION_MODE_FULL);
    mdsip_test_status(0,result,"mdsip_connect globus_xio_attr_cntl");
    if (result != GLOBUS_SUCCESS) return 0;
    result = globus_xio_attr_cntl(attr,
			 gsi_driver,
			 GLOBUS_XIO_GSI_SET_AUTHORIZATION_MODE,
			 GLOBUS_XIO_GSI_HOST_AUTHORIZATION);
    mdsip_test_status(0,result,"mdsip_connect globus_xio_attr_cntl");
    if (result != GLOBUS_SUCCESS) return 0;
  }
  result = globus_xio_attr_cntl(attr,tcp_driver,GLOBUS_XIO_TCP_SET_SNDBUF,MDSIP_SNDBUF);
  mdsip_test_status(0,result,"mdsip_connect SET_SNDBUF");
  if (result != GLOBUS_SUCCESS) return 0;
  result = globus_xio_attr_cntl(attr,tcp_driver,GLOBUS_XIO_TCP_SET_RCVBUF,MDSIP_RCVBUF);
  mdsip_test_status(0,result,"mdsip_connect SET_RCVBUF");
  if (result != GLOBUS_SUCCESS) return 0;
  result = globus_xio_attr_cntl(attr,tcp_driver,GLOBUS_XIO_TCP_SET_NODELAY,GLOBUS_TRUE);
  mdsip_test_status(0,result,"mdsip_connect SET_NODELAY");
  if (result != GLOBUS_SUCCESS) return 0;
  result = globus_xio_attr_cntl(attr,tcp_driver,GLOBUS_XIO_TCP_SET_KEEPALIVE,GLOBUS_TRUE);
  mdsip_test_status(0,result,"mdsip_connect SET_KEEPALIVE");
  if (result != GLOBUS_SUCCESS) return 0;
  result = globus_xio_open(xio_handle, contact_string, attr);
  mdsip_test_status(0,result,"mdsip_connect globus_xio_open");
  if (result != GLOBUS_SUCCESS) 
    xio_handle = 0;
  else
  {
#ifdef _WIN32
    static char user[128];
    int bsize=128;
    char *user_p = GetUserName(user,&bsize) ? user : "******";
#elif __MWERKS__
    static char user[128];
    int bsize=128;
    char *user_p = "Macintosh User";
#elif __APPLE__
    char *user_p;
    struct passwd *pwd;
    pwd = getpwuid(geteuid());
    user_p = pwd->pw_name;
#else
    char *user_p;
#ifdef HAVE_VXWORKS_H
    user_p = "vxWorks";
#else
    user_p = (getpwuid(geteuid()))->pw_name;
#endif
#endif
    m = malloc(sizeof(mdsip_message_header_t)+strlen(user_p)+1);
    memset(m,0,sizeof(mdsip_message_header_t));
    m->h.length=strlen(user_p);
    m->h.msglen=sizeof(mdsip_message_header_t)+m->h.length;
    m->h.dtype=DTYPE_CSTRING;
    m->h.status=0;
    m->h.ndims=0;
    strcpy(m->bytes,user_p);
    mdsip_send_message(xio_handle,m,0);
    free(m);
    m = NULL;
    m = mdsip_get_message(xio_handle,&status);
    if (!(status & 1))
    {
      fprintf(stderr,"ERROR: mdsip_connect\n");
      return NULL;
    }
    else
    {
      if (!(m->h.status & 1))
      {
        fprintf(stderr,"ERROR: mdsip_connect - Access Denied\n");
        globus_xio_close(xio_handle,NULL);
        return NULL;
      }
    }
    if (m != NULL)
      free(m);
  }
  return (void *)xio_handle;
}
예제 #16
0
//------------------------------------------------------------------------------
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms649016%28v=vs.85%29.aspx
DWORD WINAPI Scan_clipboard(LPVOID lParam)
{
  //check if local or not :)
  if (!LOCAL_SCAN)
  {
    h_thread_test[(unsigned int)lParam] = 0;
    check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan
    return 0;
  }

  //db
  sqlite3 *db = (sqlite3 *)db_scan;
  if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"BEGIN TRANSACTION;", NULL, NULL, NULL);

  //lecture du contenu du presse papier et extraction
  if (OpenClipboard(0))
  {
    char description[MAX_LINE_SIZE], format[DEFAULT_TMP_SIZE],
    data[MAX_LINE_SIZE],user[NB_USERNAME_SIZE+1]="";
    unsigned int session_id = current_session_id;
    HGLOBAL hMem;

    //user
    DWORD s=NB_USERNAME_SIZE;
    GetUserName(user,&s);

    int nb_items = CountClipboardFormats();
    if (nb_items > 0)
    {
      unsigned int uFormat = EnumClipboardFormats(0);
      #ifdef CMD_LINE_ONLY_NO_DB
      printf("\"Clipboard\";\"format\";\"code\";\"description\";\"user\";\"session_id\";\"data\";\r\n");
      #endif // CMD_LINE_ONLY_NO_DB
      while (uFormat && start_scan && GetLastError() == ERROR_SUCCESS && --nb_items>0)
      {
        //check if ok
        if (IsClipboardFormatAvailable(uFormat) == FALSE)
        {
          uFormat = EnumClipboardFormats(uFormat);
          continue;
        }

        description[0] = 0;
        data[0]= 0;
        if (GetClipboardFormatName(uFormat, description, MAX_LINE_SIZE) != 0)
        {
          hMem = GetClipboardData(uFormat);
          if (hMem != NULL)
          {
            switch(uFormat)
            {
              case CF_TEXT:
                //format
                strncpy(format,"CF_TEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_BITMAP:
                //format
                strncpy(format,"CF_BITMAP",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Bitmap Picture",DEFAULT_TMP_SIZE);
                //do in bitmap to hexa
                SaveBitmapToHexaStr((HBITMAP)hMem , data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_METAFILEPICT:
                //format
                strncpy(format,"CF_METAFILEPICT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Meta-File Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
                GlobalUnlock(hMem);
              break;
              case CF_SYLK:
                //format
                strncpy(format,"CF_SYLK",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Microsoft Symbolic Link (SYLK) data",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%s",(char*)GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_OEMTEXT:
                //format
                strncpy(format,"CF_OEMTEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text (OEM)",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_DIB:
                //format
                strncpy(format,"CF_DIB",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"DIB Bitmap Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_DIF:
                //format
                strncpy(format,"CF_DIF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Software Arts' Data Interchange information",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_TIFF:
                //format
                strncpy(format,"CF_TIFF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Tagged Image File Format (TIFF) Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_PALETTE:
                //format
                strncpy(format,"CF_PALETTE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Colour Palette",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_PENDATA:
                //format
                strncpy(format,"CF_PENDATA",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Pen Data",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_UNICODETEXT:
                //format
                strncpy(format,"CF_UNICODETEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text Unicode",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%S",GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);h_thread_test[(unsigned int)lParam] = 0;
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_RIFF:
                //format
                strncpy(format,"CF_RIFF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"RIFF Audio data",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_WAVE:
                //format
                strncpy(format,"CF_WAVE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Wave File",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_ENHMETAFILE:
                //format
                strncpy(format,"CF_ENHMETAFILE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Enhanced Meta-File Picture",DEFAULT_TMP_SIZE);
                //datas
                DWORD dwSize = GetEnhMetaFileBits((HENHMETAFILE)hMem, 0, NULL);
                if (dwSize > 0)
                {
                  LPBYTE buffer = (LPBYTE)malloc(dwSize);
                  if (buffer != NULL)
                  {
                    if (GetEnhMetaFileBits((HENHMETAFILE)hMem, dwSize, buffer)!=0)
                    {
                      DatatoHexa(buffer, dwSize, data, MAX_LINE_SIZE);
                    }
                    free(buffer);
                  }
                }
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_HDROP:
              {
                //format
                strncpy(format,"CF_HDROP",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"File List",DEFAULT_TMP_SIZE);

                HDROP H_DropInfo = (HDROP)hMem;
                char tmp[MAX_PATH];
                DWORD i,nb_path = DragQueryFile(H_DropInfo, 0xFFFFFFFF, tmp, MAX_PATH);
                long int s2 =MAX_LINE_SIZE;
                for (i=0;i<nb_path;i++)
                {
                  //traitement des données ^^
                  DragQueryFile(H_DropInfo, i, tmp, MAX_PATH);

                  //add
                  if (s2>0)
                  {
                    snprintf(data+strlen(data),s,"%s\r\n",tmp);
                    //strncpy(data+strlen(data),tmp,s);
                    s2-=strlen(data);
                  }
                }
                convertStringToSQL(data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              }
              break;
              case CF_LOCALE:
                //format
                strncpy(format,"CF_LOCALE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text Locale Identifier",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"0x%X",(unsigned int)GlobalLock(hMem));
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 17: //CF_DIBV5
                //format
                strncpy(format,"CF_DIBV5",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), sizeof(BITMAPV5HEADER), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49155:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"OwnerLink",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49156:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Native Bitmap Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49158:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"FileName",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49159:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"FileNameW",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%S",GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49298:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Rich Text Format",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%s",(char*)GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              default:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
            }
          }
        }
        uFormat = EnumClipboardFormats(uFormat);
      }
    }
    CloseClipboard();
  }
  if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"END TRANSACTION;", NULL, NULL, NULL);

  check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan
  h_thread_test[(unsigned int)lParam] = 0;
  return 0;
}
예제 #17
0
DWORD WINAPI imp_desktop_thread(LPVOID lpParam)
{
	vncServer *server = (vncServer *)lpParam;
	HDESK desktop;
	//vnclog.Print(LL_INTERR, VNCLOG("SelectDesktop \n"));
	//vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop2 NULL\n"));
	desktop = OpenInputDesktop(0, FALSE,
								DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
								DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
								DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
								DESKTOP_SWITCHDESKTOP | GENERIC_WRITE
								);

	if (desktop == NULL)
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop Error \n"));
	else
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop OK\n"));

	HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;

	char new_name[256];

	if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
	{
		vnclog.Print(LL_INTERR, VNCLOG("!GetUserObjectInformation \n"));
	}

	vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK to %s (%x) from %x\n"), new_name, desktop, old_desktop);

	if (!SetThreadDesktop(desktop))
	{
		vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK:!SetThreadDesktop \n"));
	}

//	ImpersonateCurrentUser_();

	char m_username[UNLEN+1];
	HWINSTA station = GetProcessWindowStation();
	if (station != NULL)
	{
		DWORD usersize;
		GetUserObjectInformation(station, UOI_USER_SID, NULL, 0, &usersize);
		DWORD  dwErrorCode = GetLastError();
		SetLastError(0);
		if (usersize != 0)
		{
			DWORD length = sizeof(m_username);
			if (GetUserName(m_username, &length) == 0)
			{
				UINT error = GetLastError();
				if (error != ERROR_NOT_LOGGED_ON)
				{
					vnclog.Print(LL_INTERR, VNCLOG("getusername error %d\n"), GetLastError());
					SetThreadDesktop(old_desktop);
                	CloseDesktop(desktop);
					Sleep(500);
					return FALSE;
				}
			}
		}
	}
    vnclog.Print(LL_INTERR, VNCLOG("Username %s \n"),m_username);

	// Create tray icon and menu
	vncMenu *menu = new vncMenu(server);
	if (menu == NULL)
	{
		vnclog.Print(LL_INTERR, VNCLOG("failed to create tray menu\n"));
		PostQuitMessage(0);
	}

	// This is a good spot to handle the old PostAdd messages
	if (PostAddAutoConnectClient_bool)
		vncService::PostAddAutoConnectClient( pszId_char );
	if (PostAddAutoConnectClient_bool_null)
		vncService::PostAddAutoConnectClient( NULL );

	if (PostAddConnectClient_bool)
		vncService::PostAddConnectClient( pszId_char );
	if (PostAddConnectClient_bool_null)
		vncService::PostAddConnectClient( NULL );

	if (PostAddNewClient_bool)
	{
		PostAddNewClient_bool=false;
		vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIIII\n"));
		vncService::PostAddNewClient(address_vcard, port_int);
	}
	//adzm 2009-06-20
	if (PostAddNewRepeaterClient_bool)
	{
		PostAddNewRepeaterClient_bool=false;
		vnclog.Print(LL_INTERR, VNCLOG("PostAddNewRepeaterClient II\n"));
		vncService::PostAddNewRepeaterClient();
	}
	bool Runonce=false;
	MSG msg;
	while (GetMessage(&msg,0,0,0) != 0)
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
		if (fShutdownOrdered && !Runonce)
		{
			Runonce=true;
			if (menu) menu->Shutdown(true);
		}

		if (hShutdownEvent)
		{
			// vnclog.Print(LL_INTERR, VNCLOG("****************** SDTimer tic\n"));
			DWORD result = WaitForSingleObject(hShutdownEvent, 1);
			if (WAIT_OBJECT_0 == result)
			{
				ResetEvent(hShutdownEvent);
				fShutdownOrdered = true;
				vnclog.Print(LL_INTERR, VNCLOG("****************** WaitForSingleObject - Shutdown server\n"));
			}
		}
	}

	// sf@2007 - Close all (vncMenu,tray icon, connections...)

	if (menu != NULL)
		delete menu;

	//vnclog.Print(LL_INTERR, VNCLOG("GetMessage stop \n"));
	SetThreadDesktop(old_desktop);
	CloseDesktop(desktop);
//	RevertToSelf();
	return 0;
}
예제 #18
0
void logThread(void *dummy)
{
	SetProcessPriorityBoost	(GetCurrentProcess(),TRUE);

	logWindow = CreateDialog(
		HINSTANCE(GetModuleHandle(0)),
	 	MAKEINTRESOURCE(IDD_LOG),
		0, logDlgProc );
	if (!logWindow) {
		R_CHK			(GetLastError());
	};
	SetWindowPos(logWindow,HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
	hwLog		= GetDlgItem(logWindow, IDC_LOG);
	hwProgress	= GetDlgItem(logWindow, IDC_PROGRESS);
	hwInfo		= GetDlgItem(logWindow, IDC_INFO);
	hwStage		= GetDlgItem(logWindow, IDC_STAGE);
	hwTime		= GetDlgItem(logWindow, IDC_TIMING);
	hwPText		= GetDlgItem(logWindow, IDC_P_TEXT);
	hwPhaseTime	= GetDlgItem(logWindow, IDC_PHASE_TIME);

	SendMessage(hwProgress, PBM_SETRANGE,	0, MAKELPARAM(0, 1000)); 
	SendMessage(hwProgress, PBM_SETPOS,		0, 0); 

	Msg("\"LevelBuilder v4.1\" beta build\nCompilation date: %s\n",__DATE__);
	{
		char tmpbuf[128];
		Msg("Startup time: %s",_strtime(tmpbuf));
	}

	BOOL		bHighPriority	= FALSE;
	string256	u_name;
	unsigned long		u_size	= sizeof(u_name)-1;
	GetUserName	(u_name,&u_size);
	_strlwr		(u_name);
	if ((0==xr_strcmp(u_name,"oles"))||(0==xr_strcmp(u_name,"alexmx")))	bHighPriority	= TRUE;

	// Main cycle
	u32		LogSize = 0;
	float	PrSave	= 0;
	while (TRUE)
	{
		SetPriorityClass	(GetCurrentProcess(),IDLE_PRIORITY_CLASS);	// bHighPriority?NORMAL_PRIORITY_CLASS:IDLE_PRIORITY_CLASS

		// transfer data
		while (!csLog.TryEnter())	{
			_process_messages	( );
			Sleep				(1);
		}
		if (progress>1.f)		progress = 1.f;
		else if (progress<0)	progress = 0;

		BOOL bWasChanges = FALSE;
		char tbuf		[256];
		csLog.Enter		();
		if (LogSize!=LogFile->size())
		{
			bWasChanges		= TRUE;
			for (; LogSize<LogFile->size(); LogSize++)
			{
				const char *S = *(*LogFile)[LogSize];
				if (0==S)	S = "";
				SendMessage	( hwLog, LB_ADDSTRING, 0, (LPARAM) S);
			}
			SendMessage		( hwLog, LB_SETTOPINDEX, LogSize-1, 0);
			//FlushLog		( );
		}
		csLog.Leave		();
		if (_abs(PrSave-progress)>EPS_L) {
			bWasChanges = TRUE;
			PrSave = progress;
			SendMessage		( hwProgress, PBM_SETPOS, u32(progress*1000.f), 0);

			// timing
			if (progress>0.005f) {
				u32 dwCurrentTime = timeGetTime();
				u32 dwTimeDiff	= dwCurrentTime-phase_start_time;
				u32 secElapsed	= dwTimeDiff/1000;
				u32 secRemain		= u32(float(secElapsed)/progress)-secElapsed;
				xr_sprintf(tbuf,
					"Elapsed: %s\n"
					"Remain:  %s",
					make_time(secElapsed).c_str(),
					make_time(secRemain).c_str()
					);
				SetWindowText	( hwTime, tbuf );
			} else {
				SetWindowText	( hwTime, "" );
			}

			// percentage text
			xr_sprintf(tbuf,"%3.2f%%",progress*100.f);
			SetWindowText	( hwPText, tbuf );
		}

		if (bStatusChange) {
			bWasChanges		= TRUE;
			bStatusChange	= FALSE;
			SetWindowText	( hwInfo,	status);
		}
		if (bWasChanges) {
			UpdateWindow	( logWindow);
			bWasChanges		= FALSE;
		}
		csLog.Leave			();

		_process_messages	();
		if (bClose)			break;
		Sleep				(200);
	}

	// Cleanup
	DestroyWindow(logWindow);
}
예제 #19
0
void SavePrefs(int iDlg)
{
	/**************************************************************************************************/
	/********** allocate space for our string, and then set it to the currently logged on user ********/
	/**************************************************************************************************/
	DWORD dBuff = 257;
	TCHAR szUser[257];

	GetUserName(szUser, &dBuff);

	/**************************************************************************************************/
	/*********************** Test if the file exists, If it doesn't, Create It ************************/
	/**************************************************************************************************/
	TCHAR XTRAY_INI_FILE[1024];
	
#ifdef UNICODE
	char temp[1024];
    TCHAR TEMP_INI_FILE[1024];
	
	_snprintf(temp, 1024, "%s\\xtray.conf", xchat_get_info(ph, "xchatdir"));
	ConvertString(temp, TEMP_INI_FILE, 1024);

	// ok this one is really ugly
	// it checks to see if the file exists in two locations
	// HexChat default config dir, if that fails it tries hexchat\plugins\config
	// if neither one exists it tries to create it in
	// HexChat default config dir, if that fails it tries hexchat\plugins\config
	// In either case it writes \xFF\xFE to the file ( on creation )
	// so that we can save unicode away messages WritePrivateProfile doesn't 
	// do this for us, though I think it really should

	if(FileExists(TEMP_INI_FILE))
	{
		_tcscpy(XTRAY_INI_FILE, TEMP_INI_FILE);
	}
	else
	{
		if(FileExists(BACKUP_INI_FILE))
		{
			_tcscpy(XTRAY_INI_FILE, BACKUP_INI_FILE);
		}
		else
		{
			HANDLE xTemp;
			DWORD dwBytesTemp;

			if(xTemp = CreateFile(TEMP_INI_FILE, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL))
			{
				if(GetLastError() != ERROR_ALREADY_EXISTS)
				{
					WriteFile(xTemp, _T("\xFF\xFE"), 4, &dwBytesTemp, NULL);
				}
				CloseHandle(xTemp);
			}

			if(FileExists(TEMP_INI_FILE))
			{
				_tcscpy(XTRAY_INI_FILE, TEMP_INI_FILE);
			}
			else
			{
				HANDLE xBackup;
				DWORD dwBytesBackup;

				if(xBackup = CreateFile(TEMP_INI_FILE, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL))
				{
					if(GetLastError() != ERROR_ALREADY_EXISTS)
					{
						WriteFile(xBackup, _T("\xFF\xFE"), 4, &dwBytesBackup, NULL);
					}

					CloseHandle(xBackup);
				}

				if(FileExists(BACKUP_INI_FILE))
				{
					_tcscpy(XTRAY_INI_FILE, BACKUP_INI_FILE);
				}
			}
		}
	}

#else
	_tcscpy(XTRAY_INI_FILE, BACKUP_INI_FILE);
#endif

	WritePrivateProfileInt(szUser, _T("SETTINGS"),		g_dwPrefs,		XTRAY_INI_FILE);
	WritePrivateProfileInt(szUser, _T("AOT"),			g_iTime,		XTRAY_INI_FILE);
	WritePrivateProfileInt(szUser, _T("KEY"),			g_hHotKey.key,	XTRAY_INI_FILE);
	WritePrivateProfileInt(szUser, _T("MOD"),			g_hHotKey.mod,	XTRAY_INI_FILE);
	WritePrivateProfileString(szUser, _T("AWAY"),		g_szAway,		XTRAY_INI_FILE);
}
예제 #20
0
void DatabaseOutputDriver::finalizeOutput() {
	// This is where we'll send all the info we've received so far to the
	// database
	if (submittedResults) {
		return; // Only submit results for a test once
	}

	//write the header if necessary
	if (!wroteLogHeader) {
		// get hostname and username for log header
		// FIXME This needs to be platform-independent
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX (255)
#endif
		char hostname[HOST_NAME_MAX];
		if (gethostname(hostname, HOST_NAME_MAX)) {
			// TODO Handle error
		}
		
		std::string userName;

#ifdef os_windows_test
		char * szUserName = new char[MAX_USER_NAME + 1];
		LPDWORD lpnSize = (LPDWORD)malloc(sizeof(DWORD));
		*lpnSize = MAX_USER_NAME + 1;
		if (lpnSize == NULL) {
			fprintf(stderr, "[%s:%u] - Out of memory!\n", __FILE__, __LINE__);
			// TODO Handle error;
		}
		memset(szUserName, 0, MAX_USER_NAME + 1);
		if (!GetUserName(szUserName, lpnSize)) {
			fprintf(stderr, "[%s:%u] - Failed to get username: %s\n",
					__FILE__, __LINE__, GetLastError());
			//TODO Handle error
		}
		userName = std::string(szUserName);

		free(lpnSize);
		delete [] szUserName;
#else
		//note: geteuid() is always successful
		//FIXME: use getpwuid_r
		struct passwd * pw = getpwuid(geteuid());
		if (NULL == pw) {
			//TODO unknown user
			userName = "******";
		} else {
			userName = pw->pw_name;
		}
#endif

		std::string logHeader = userName + "@" + hostname;
                if (getenv("PLATFORM") != 0) {
                    logHeader += "\nPLATFORM=";
                    logHeader += getenv("PLATFORM");
                }
                logHeader += "\n\n";

		FILE * sqlLog = fopen(sqlLogFilename.c_str(), "wb");
		if (NULL == sqlLog) {
			fprintf(stderr, "[%s:%u] - Error opening log file: %s\n",
					__FILE__, __LINE__, sqlLogFilename.c_str());
			//TODO handle error
		}
		int size = strlen(logHeader.c_str());
		if (fwrite(logHeader.c_str(), sizeof(char), size, sqlLog) != size) {
			fprintf(stderr, "[%s:%u] - Error writing to log file.\n", __FILE__, __LINE__);
			//TODO handle error
		}
		fclose(sqlLog);

		wroteLogHeader = true;
	}
	
	writeSQLLog();
	return;

	//TODO: what about this stuff?
	submittedResults = true;
}
예제 #21
0
파일: User.cpp 프로젝트: b3rend/znc
bool CUser::Clone(const CUser& User, CString& sErrorRet, bool bCloneChans) {
	unsigned int a = 0;
	sErrorRet.clear();

	if (!User.IsValid(sErrorRet, true)) {
		return false;
	}

	// user names can only specified for the constructor, changing it later
	// on breaks too much stuff (e.g. lots of paths depend on the user name)
	if (GetUserName() != User.GetUserName()) {
		DEBUG("Ignoring username in CUser::Clone(), old username [" << GetUserName()
				<< "]; New username [" << User.GetUserName() << "]");
	}

	if (!User.GetPass().empty()) {
		SetPass(User.GetPass(), User.GetPassHashType(), User.GetPassSalt());
	}

	SetNick(User.GetNick(false));
	SetAltNick(User.GetAltNick(false));
	SetIdent(User.GetIdent(false));
	SetRealName(User.GetRealName());
	SetStatusPrefix(User.GetStatusPrefix());
	SetBindHost(User.GetBindHost());
	SetDCCBindHost(User.GetDCCBindHost());
	SetQuitMsg(User.GetQuitMsg());
	SetSkinName(User.GetSkinName());
	SetLanguage(User.GetLanguage());
	SetDefaultChanModes(User.GetDefaultChanModes());
	SetBufferCount(User.GetBufferCount(), true);
	SetJoinTries(User.JoinTries());
	SetMaxJoins(User.MaxJoins());

	// Allowed Hosts
	m_ssAllowedHosts.clear();
	const set<CString>& ssHosts = User.GetAllowedHosts();
	for (set<CString>::const_iterator it = ssHosts.begin(); it != ssHosts.end(); ++it) {
		AddAllowedHost(*it);
	}

	for (a = 0; a < m_vClients.size(); a++) {
		CClient* pSock = m_vClients[a];

		if (!IsHostAllowed(pSock->GetRemoteIP())) {
			pSock->PutStatusNotice("You are being disconnected because your IP is no longer allowed to connect to this user");
			pSock->Close();
		}
	}

	// !Allowed Hosts

	// Networks
	const vector<CIRCNetwork*>& vNetworks = User.GetNetworks();
	for (a = 0; a < vNetworks.size(); a++) {
		new CIRCNetwork(this, vNetworks[a], bCloneChans);
	}
	// !Networks

	// CTCP Replies
	m_mssCTCPReplies.clear();
	const MCString& msReplies = User.GetCTCPReplies();
	for (MCString::const_iterator it = msReplies.begin(); it != msReplies.end(); ++it) {
		AddCTCPReply(it->first, it->second);
	}
	// !CTCP Replies

	// Flags
	SetIRCConnectEnabled(User.GetIRCConnectEnabled());
	SetKeepBuffer(User.KeepBuffer());
	SetMultiClients(User.MultiClients());
	SetDenyLoadMod(User.DenyLoadMod());
	SetAdmin(User.IsAdmin());
	SetDenySetBindHost(User.DenySetBindHost());
	SetTimestampAppend(User.GetTimestampAppend());
	SetTimestampPrepend(User.GetTimestampPrepend());
	SetTimestampFormat(User.GetTimestampFormat());
	SetTimezoneOffset(User.GetTimezoneOffset());
	// !Flags

	// Modules
	set<CString> ssUnloadMods;
	CModules& vCurMods = GetModules();
	const CModules& vNewMods = User.GetModules();

	for (a = 0; a < vNewMods.size(); a++) {
		CString sModRet;
		CModule* pNewMod = vNewMods[a];
		CModule* pCurMod = vCurMods.FindModule(pNewMod->GetModName());

		if (!pCurMod) {
			vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(), CModInfo::UserModule, this, NULL, sModRet);
		} else if (pNewMod->GetArgs() != pCurMod->GetArgs()) {
			vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(), this, NULL, sModRet);
		}
	}

	for (a = 0; a < vCurMods.size(); a++) {
		CModule* pCurMod = vCurMods[a];
		CModule* pNewMod = vNewMods.FindModule(pCurMod->GetModName());

		if (!pNewMod) {
			ssUnloadMods.insert(pCurMod->GetModName());
		}
	}

	for (set<CString>::iterator it = ssUnloadMods.begin(); it != ssUnloadMods.end(); ++it) {
		vCurMods.UnloadModule(*it);
	}
	// !Modules

	return true;
}
예제 #22
0
void PerfDataRefresh(void)
{
    ULONG                            ulSize;
    LONG                            status;
    LPBYTE                            pBuffer;
    ULONG                            BufferSize;
    PSYSTEM_PROCESS_INFORMATION        pSPI;
    PPERFDATA                        pPDOld;
    ULONG                            Idx, Idx2;
    HANDLE                            hProcess;
    HANDLE                            hProcessToken;
    TCHAR                            szTemp[MAX_PATH];
    DWORD                            dwSize;
    SYSTEM_PERFORMANCE_INFORMATION    SysPerfInfo;
    SYSTEM_TIME_INFORMATION            SysTimeInfo;
    SYSTEM_CACHE_INFORMATION        SysCacheInfo;
    LPBYTE                            SysHandleInfoData;
    PSYSTEM_PROCESSORTIME_INFO        SysProcessorTimeInfo;
    double                            CurrentKernelTime;


    if (!NtQuerySystemInformation)
        return;

    /* Get new system time */
    status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo, sizeof(SysTimeInfo), 0);
    if (status != NO_ERROR)
        return;

    /* Get new CPU's idle time */
    status = NtQuerySystemInformation(SystemPerformanceInformation, &SysPerfInfo, sizeof(SysPerfInfo), NULL);
    if (status != NO_ERROR)
        return;

    /* Get system cache information */
    status = NtQuerySystemInformation(SystemCacheInformation, &SysCacheInfo, sizeof(SysCacheInfo), NULL);
    if (status != NO_ERROR)
        return;

    /* Get processor time information */
    SysProcessorTimeInfo = HeapAlloc(GetProcessHeap(), 0,
                                sizeof(SYSTEM_PROCESSORTIME_INFO) * SystemBasicInfo.bKeNumberProcessors);
    status = NtQuerySystemInformation(SystemProcessorTimeInformation, SysProcessorTimeInfo, sizeof(SYSTEM_PROCESSORTIME_INFO) * SystemBasicInfo.bKeNumberProcessors, &ulSize);
    if (status != NO_ERROR) {
        HeapFree(GetProcessHeap(), 0, SysProcessorTimeInfo);
        return;
    }

    /* Get handle information
     * We don't know how much data there is so just keep
     * increasing the buffer size until the call succeeds
     */
    BufferSize = 0;
    do
    {
        BufferSize += 0x10000;
        SysHandleInfoData = HeapAlloc(GetProcessHeap(), 0, BufferSize);

        status = NtQuerySystemInformation(SystemHandleInformation, SysHandleInfoData, BufferSize, &ulSize);

        if (status == 0xC0000004 /*STATUS_INFO_LENGTH_MISMATCH*/) {
            HeapFree(GetProcessHeap(), 0, SysHandleInfoData);
        }

    } while (status == 0xC0000004 /*STATUS_INFO_LENGTH_MISMATCH*/);

    /* Get process information
     * We don't know how much data there is so just keep
     * increasing the buffer size until the call succeeds
     */
    BufferSize = 0;
    do
    {
        BufferSize += 0x10000;
        pBuffer = HeapAlloc(GetProcessHeap(), 0, BufferSize);

        status = NtQuerySystemInformation(SystemProcessInformation, pBuffer, BufferSize, &ulSize);

        if (status == 0xC0000004 /*STATUS_INFO_LENGTH_MISMATCH*/) {
            HeapFree(GetProcessHeap(), 0, pBuffer);
        }

    } while (status == 0xC0000004 /*STATUS_INFO_LENGTH_MISMATCH*/);

    EnterCriticalSection(&PerfDataCriticalSection);

    /*
     * Save system performance info
     */
    memcpy(&SystemPerfInfo, &SysPerfInfo, sizeof(SYSTEM_PERFORMANCE_INFORMATION));

    /*
     * Save system cache info
     */
    memcpy(&SystemCacheInfo, &SysCacheInfo, sizeof(SYSTEM_CACHE_INFORMATION));
    
    /*
     * Save system processor time info
     */
    HeapFree(GetProcessHeap(), 0, SystemProcessorTimeInfo);
    SystemProcessorTimeInfo = SysProcessorTimeInfo;
    
    /*
     * Save system handle info
     */
    memcpy(&SystemHandleInfo, SysHandleInfoData, sizeof(SYSTEM_HANDLE_INFORMATION));
    HeapFree(GetProcessHeap(), 0, SysHandleInfoData);
    
    for (CurrentKernelTime=0, Idx=0; Idx<SystemBasicInfo.bKeNumberProcessors; Idx++) {
        CurrentKernelTime += Li2Double(SystemProcessorTimeInfo[Idx].KernelTime);
        CurrentKernelTime += Li2Double(SystemProcessorTimeInfo[Idx].DpcTime);
        CurrentKernelTime += Li2Double(SystemProcessorTimeInfo[Idx].InterruptTime);
    }

    /* If it's a first call - skip idle time calcs */
    if (liOldIdleTime.QuadPart != 0) {
        /*  CurrentValue = NewValue - OldValue */
        dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
        dbKernelTime = CurrentKernelTime - OldKernelTime;
        dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);

        /*  CurrentCpuIdle = IdleTime / SystemTime */
        dbIdleTime = dbIdleTime / dbSystemTime;
        dbKernelTime = dbKernelTime / dbSystemTime;
        
        /*  CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors */
        dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SystemBasicInfo.bKeNumberProcessors; /* + 0.5; */
        dbKernelTime = 100.0 - dbKernelTime * 100.0 / (double)SystemBasicInfo.bKeNumberProcessors; /* + 0.5; */
    }

    /* Store new CPU's idle and system time */
    liOldIdleTime = SysPerfInfo.liIdleTime;
    liOldSystemTime = SysTimeInfo.liKeSystemTime;
    OldKernelTime = CurrentKernelTime;

    /* Determine the process count
     * We loop through the data we got from NtQuerySystemInformation
     * and count how many structures there are (until RelativeOffset is 0)
     */
    ProcessCountOld = ProcessCount;
    ProcessCount = 0;
    pSPI = (PSYSTEM_PROCESS_INFORMATION)pBuffer;
    while (pSPI) {
        ProcessCount++;
        if (pSPI->RelativeOffset == 0)
            break;
        pSPI = (PSYSTEM_PROCESS_INFORMATION)((LPBYTE)pSPI + pSPI->RelativeOffset);
    }

    /* Now alloc a new PERFDATA array and fill in the data */
    HeapFree(GetProcessHeap(), 0, pPerfDataOld);
    pPerfDataOld = pPerfData;
    pPerfData = HeapAlloc(GetProcessHeap(), 0, sizeof(PERFDATA) * ProcessCount);
    pSPI = (PSYSTEM_PROCESS_INFORMATION)pBuffer;
    for (Idx=0; Idx<ProcessCount; Idx++) {
        /* Get the old perf data for this process (if any) */
        /* so that we can establish delta values */
        pPDOld = NULL;
        for (Idx2=0; Idx2<ProcessCountOld; Idx2++) {
            if (pPerfDataOld[Idx2].ProcessId == pSPI->ProcessId) {
                pPDOld = &pPerfDataOld[Idx2];
                break;
            }
        }

        /* Clear out process perf data structure */
        memset(&pPerfData[Idx], 0, sizeof(PERFDATA));

        if (pSPI->Name.Buffer)
            lstrcpyW(pPerfData[Idx].ImageName, pSPI->Name.Buffer);
        else
        {
            static const WCHAR idleW[] = {'S','y','s','t','e','m',' ','I','d','l','e',' ','P','r','o','c','e','s','s',0};
            lstrcpyW(pPerfData[Idx].ImageName, idleW );
        }

        pPerfData[Idx].ProcessId = pSPI->ProcessId;

        if (pPDOld)    {
            double    CurTime = Li2Double(pSPI->KernelTime) + Li2Double(pSPI->UserTime);
            double    OldTime = Li2Double(pPDOld->KernelTime) + Li2Double(pPDOld->UserTime);
            double    CpuTime = (CurTime - OldTime) / dbSystemTime;
            CpuTime = CpuTime * 100.0 / (double)SystemBasicInfo.bKeNumberProcessors; /* + 0.5; */
            pPerfData[Idx].CPUUsage = (ULONG)CpuTime;
        }
        pPerfData[Idx].CPUTime.QuadPart = pSPI->UserTime.QuadPart + pSPI->KernelTime.QuadPart;
        pPerfData[Idx].WorkingSetSizeBytes = pSPI->TotalWorkingSetSizeBytes;
        pPerfData[Idx].PeakWorkingSetSizeBytes = pSPI->PeakWorkingSetSizeBytes;
        if (pPDOld)
            pPerfData[Idx].WorkingSetSizeDelta = labs((LONG)pSPI->TotalWorkingSetSizeBytes - (LONG)pPDOld->WorkingSetSizeBytes);
        else
            pPerfData[Idx].WorkingSetSizeDelta = 0;
        pPerfData[Idx].PageFaultCount = pSPI->PageFaultCount;
        if (pPDOld)
            pPerfData[Idx].PageFaultCountDelta = labs((LONG)pSPI->PageFaultCount - (LONG)pPDOld->PageFaultCount);
        else
            pPerfData[Idx].PageFaultCountDelta = 0;
        pPerfData[Idx].VirtualMemorySizeBytes = pSPI->TotalVirtualSizeBytes;
        pPerfData[Idx].PagedPoolUsagePages = pSPI->TotalPagedPoolUsagePages;
        pPerfData[Idx].NonPagedPoolUsagePages = pSPI->TotalNonPagedPoolUsagePages;
        pPerfData[Idx].BasePriority = pSPI->BasePriority;
        pPerfData[Idx].HandleCount = pSPI->HandleCount;
        pPerfData[Idx].ThreadCount = pSPI->ThreadCount;
        pPerfData[Idx].SessionId = pSPI->SessionId;
        
        hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pSPI->ProcessId);
        if (hProcess) {
            if (OpenProcessToken(hProcess, TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_IMPERSONATE, &hProcessToken)) {
                ImpersonateLoggedOnUser(hProcessToken);
                memset(szTemp, 0, sizeof(TCHAR[MAX_PATH]));
                dwSize = MAX_PATH;
                GetUserName(szTemp, &dwSize);
#ifndef UNICODE
                MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szTemp, -1, pPerfData[Idx].UserName, MAX_PATH);
/*
int MultiByteToWideChar(
  UINT CodePage,         // code page
  DWORD dwFlags,         //  character-type options
  LPCSTR lpMultiByteStr, //  string to map
  int cbMultiByte,       //  number of bytes in string
  LPWSTR lpWideCharStr,  //  wide-character buffer
  int cchWideChar        //  size of buffer
);
 */
#endif
                RevertToSelf();
                CloseHandle(hProcessToken);
            }
            if (pGetGuiResources) {
                pPerfData[Idx].USERObjectCount = pGetGuiResources(hProcess, GR_USEROBJECTS);
                pPerfData[Idx].GDIObjectCount = pGetGuiResources(hProcess, GR_GDIOBJECTS);
            }
            if (pGetProcessIoCounters)
                pGetProcessIoCounters(hProcess, &pPerfData[Idx].IOCounters);
            CloseHandle(hProcess);
        }
        pPerfData[Idx].UserTime.QuadPart = pSPI->UserTime.QuadPart;
        pPerfData[Idx].KernelTime.QuadPart = pSPI->KernelTime.QuadPart;
        pSPI = (PSYSTEM_PROCESS_INFORMATION)((LPBYTE)pSPI + pSPI->RelativeOffset);
    }
    HeapFree(GetProcessHeap(), 0, pBuffer);
    LeaveCriticalSection(&PerfDataCriticalSection);
}
예제 #23
0
파일: help.c 프로젝트: pguyot/postgres
void
usage(void)
{
	const char *env;
	const char *user;

#ifndef WIN32
	struct passwd *pw = NULL;
#endif

	/* Find default user, in case we need it. */
	user = getenv("PGUSER");
	if (!user)
	{
#if !defined(WIN32) && !defined(__OS2__)
		pw = getpwuid(geteuid());
		if (pw)
			user = pw->pw_name;
		else
		{
			psql_error("could not get current user name: %s\n", strerror(errno));
			exit(EXIT_FAILURE);
		}
#else							/* WIN32 */
		char		buf[128];
		DWORD		bufsize = sizeof(buf) - 1;

		if (GetUserName(buf, &bufsize))
			user = buf;
#endif   /* WIN32 */
	}

	printf(_("psql is the PostgreSQL interactive terminal.\n\n"));
	printf(_("Usage:\n"));
	printf(_("  psql [OPTION]... [DBNAME [USERNAME]]\n\n"));

	printf(_("General options:\n"));
	/* Display default database */
	env = getenv("PGDATABASE");
	if (!env)
		env = user;
	printf(_("  -c, --command=COMMAND    run only single command (SQL or internal) and exit\n"));
	printf(_("  -d, --dbname=DBNAME      database name to connect to (default: \"%s\")\n"), env);
	printf(_("  -f, --file=FILENAME      execute commands from file, then exit\n"));
	printf(_("  -l, --list               list available databases, then exit\n"));
	printf(_("  -v, --set=, --variable=NAME=VALUE\n"
			 "                           set psql variable NAME to VALUE\n"));
	printf(_("  -X, --no-psqlrc          do not read startup file (~/.psqlrc)\n"));
	printf(_("  -1 (\"one\"), --single-transaction\n"
			 "                           execute command file as a single transaction\n"));
	printf(_("  --help                   show this help, then exit\n"));
	printf(_("  --version                output version information, then exit\n"));

	printf(_("\nInput and output options:\n"));
	printf(_("  -a, --echo-all           echo all input from script\n"));
	printf(_("  -e, --echo-queries       echo commands sent to server\n"));
	printf(_("  -E, --echo-hidden        display queries that internal commands generate\n"));
	printf(_("  -L, --log-file=FILENAME  send session log to file\n"));
	printf(_("  -n, --no-readline        disable enhanced command line editing (readline)\n"));
	printf(_("  -o, --output=FILENAME    send query results to file (or |pipe)\n"));
	printf(_("  -q, --quiet              run quietly (no messages, only query output)\n"));
	printf(_("  -s, --single-step        single-step mode (confirm each query)\n"));
	printf(_("  -S, --single-line        single-line mode (end of line terminates SQL command)\n"));

	printf(_("\nOutput format options:\n"));
	printf(_("  -A, --no-align           unaligned table output mode\n"));
	printf(_("  -F, --field-separator=STRING\n"
	   "                           set field separator (default: \"%s\")\n"),
		   DEFAULT_FIELD_SEP);
	printf(_("  -H, --html               HTML table output mode\n"));
	printf(_("  -P, --pset=VAR[=ARG]     set printing option VAR to ARG (see \\pset command)\n"));
	printf(_("  -R, --record-separator=STRING\n"
	"                           set record separator (default: newline)\n"));
	printf(_("  -t, --tuples-only        print rows only\n"));
	printf(_("  -T, --table-attr=TEXT    set HTML table tag attributes (e.g., width, border)\n"));
	printf(_("  -x, --expanded           turn on expanded table output\n"));

	printf(_("\nConnection options:\n"));
	/* Display default host */
	env = getenv("PGHOST");
	printf(_("  -h, --host=HOSTNAME      database server host or socket directory (default: \"%s\")\n"),
		   env ? env : _("local socket"));
	/* Display default port */
	env = getenv("PGPORT");
	printf(_("  -p, --port=PORT          database server port (default: \"%s\")\n"),
		   env ? env : DEF_PGPORT_STR);
	/* Display default user */
	env = getenv("PGUSER");
	if (!env)
		env = user;
	printf(_("  -U, --username=USERNAME  database user name (default: \"%s\")\n"), env);
	printf(_("  -w, --no-password        never prompt for password\n"));
	printf(_("  -W, --password           force password prompt (should happen automatically)\n"));

	printf(_("\nFor more information, type \"\\?\" (for internal commands) or \"\\help\" (for SQL\n"
			 "commands) from within psql, or consult the psql section in the PostgreSQL\n"
			 "documentation.\n\n"));
	printf(_("Report bugs to <*****@*****.**>.\n"));
}
예제 #24
0
파일: ctm.c 프로젝트: hoangduit/reactos
void PerfDataRefresh()
{
	LONG							status;
	ULONG							ulSize;
	LPBYTE							pBuffer;
	ULONG							Idx, Idx2;
	PSYSTEM_PROCESS_INFORMATION		pSPI;
	PPERFDATA						pPDOld;
#ifdef EXTRA_INFO
	HANDLE							hProcess;
	HANDLE							hProcessToken;
	TCHAR							szTemp[MAX_PATH];
	DWORD							dwSize;
#endif
#ifdef TIMES
	LARGE_INTEGER 						liCurrentKernelTime;
	LARGE_INTEGER						liCurrentIdleTime;
	LARGE_INTEGER						liCurrentTime;
#endif
	PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION		SysProcessorTimeInfo;
	SYSTEM_TIMEOFDAY_INFORMATION				SysTimeInfo;

#ifdef TIMES
	// Get new system time
	status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo, sizeof(SysTimeInfo), 0);
	if (status != NO_ERROR)
		return;
#endif
	// Get processor information
	SysProcessorTimeInfo = (PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)malloc(sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * SystemBasicInfo.NumberOfProcessors);
	status = NtQuerySystemInformation(SystemProcessorPerformanceInformation, SysProcessorTimeInfo, sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * SystemBasicInfo.NumberOfProcessors, &ulSize);


	// Get process information
	PsaCaptureProcessesAndThreads((PSYSTEM_PROCESS_INFORMATION *)&pBuffer);

#ifdef TIMES
	liCurrentKernelTime.QuadPart = 0;
	liCurrentIdleTime.QuadPart = 0;
	for (Idx=0; Idx<SystemBasicInfo.NumberOfProcessors; Idx++) {
		liCurrentKernelTime.QuadPart += SysProcessorTimeInfo[Idx].KernelTime.QuadPart;
		liCurrentKernelTime.QuadPart += SysProcessorTimeInfo[Idx].DpcTime.QuadPart;
		liCurrentKernelTime.QuadPart += SysProcessorTimeInfo[Idx].InterruptTime.QuadPart;
		liCurrentIdleTime.QuadPart += SysProcessorTimeInfo[Idx].IdleTime.QuadPart;
	}

	// If it's a first call - skip idle time calcs
	if (liOldIdleTime.QuadPart != 0) {
		// CurrentValue = NewValue - OldValue
		liCurrentTime.QuadPart = liCurrentIdleTime.QuadPart - liOldIdleTime.QuadPart;
		dbIdleTime = Li2Double(liCurrentTime);
		liCurrentTime.QuadPart = liCurrentKernelTime.QuadPart - liOldKernelTime.QuadPart;
		dbKernelTime = Li2Double(liCurrentTime);
		liCurrentTime.QuadPart = SysTimeInfo.CurrentTime.QuadPart - liOldSystemTime.QuadPart;
	    	dbSystemTime = Li2Double(liCurrentTime);

		// CurrentCpuIdle = IdleTime / SystemTime
		dbIdleTime = dbIdleTime / dbSystemTime;
		dbKernelTime = dbKernelTime / dbSystemTime;

		// CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
		dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SystemBasicInfo.NumberOfProcessors;// + 0.5;
		dbKernelTime = 100.0 - dbKernelTime * 100.0 / (double)SystemBasicInfo.NumberOfProcessors;// + 0.5;
	}

	// Store new CPU's idle and system time
	liOldIdleTime = liCurrentIdleTime;
	liOldSystemTime = SysTimeInfo.CurrentTime;
	liOldKernelTime = liCurrentKernelTime;
#endif

	// Determine the process count
	// We loop through the data we got from PsaCaptureProcessesAndThreads
	// and count how many structures there are (until PsaWalkNextProcess
        // returns NULL)
	ProcessCountOld = ProcessCount;
	ProcessCount = 0;
        pSPI = PsaWalkFirstProcess((PSYSTEM_PROCESS_INFORMATION)pBuffer);
	while (pSPI) {
		ProcessCount++;
		pSPI = PsaWalkNextProcess(pSPI);
	}

	// Now alloc a new PERFDATA array and fill in the data
	if (pPerfDataOld) {
		free(pPerfDataOld);
	}
	pPerfDataOld = pPerfData;
	pPerfData = (PPERFDATA)malloc(sizeof(PERFDATA) * ProcessCount);
        pSPI = PsaWalkFirstProcess((PSYSTEM_PROCESS_INFORMATION)pBuffer);
	for (Idx=0; Idx<ProcessCount; Idx++) {
		// Get the old perf data for this process (if any)
		// so that we can establish delta values
		pPDOld = NULL;
		for (Idx2=0; Idx2<ProcessCountOld; Idx2++) {
			if (pPerfDataOld[Idx2].ProcessId == (ULONG)(pSPI->UniqueProcessId) &&
			    /* check also for the creation time, a new process may have an id of an old one */
			    pPerfDataOld[Idx2].CreateTime.QuadPart == pSPI->CreateTime.QuadPart) {
				pPDOld = &pPerfDataOld[Idx2];
				break;
			}
		}

		// Clear out process perf data structure
		memset(&pPerfData[Idx], 0, sizeof(PERFDATA));

		if (pSPI->ImageName.Buffer) {
			wcsncpy(pPerfData[Idx].ImageName, pSPI->ImageName.Buffer, pSPI->ImageName.Length / sizeof(WCHAR));
                        pPerfData[Idx].ImageName[pSPI->ImageName.Length / sizeof(WCHAR)] = 0;
		}
		else
		{
#ifdef _UNICODE
			wcscpy(pPerfData[Idx].ImageName, lpIdleProcess);
#else
			MultiByteToWideChar(CP_ACP, 0, lpIdleProcess, strlen(lpIdleProcess), pPerfData[Idx].ImageName, MAX_PATH);
#endif
		}

		pPerfData[Idx].ProcessId = (ULONG)(pSPI->UniqueProcessId);
		pPerfData[Idx].CreateTime = pSPI->CreateTime;

		if (pPDOld)	{
#ifdef TIMES
			double	CurTime = Li2Double(pSPI->KernelTime) + Li2Double(pSPI->UserTime);
			double	OldTime = Li2Double(pPDOld->KernelTime) + Li2Double(pPDOld->UserTime);
			double	CpuTime = (CurTime - OldTime) / dbSystemTime;
			CpuTime = CpuTime * 100.0 / (double)SystemBasicInfo.NumberOfProcessors; // + 0.5;

			pPerfData[Idx].CPUUsage = (ULONG)CpuTime;
#else
			pPerfData[Idx].CPUUsage = 0;
#endif
		}

		pPerfData[Idx].CPUTime.QuadPart = pSPI->UserTime.QuadPart + pSPI->KernelTime.QuadPart;
		pPerfData[Idx].WorkingSetSizeBytes = pSPI->WorkingSetSize;
		pPerfData[Idx].PeakWorkingSetSizeBytes = pSPI->PeakWorkingSetSize;
		if (pPDOld)
			pPerfData[Idx].WorkingSetSizeDelta = labs((LONG)pSPI->WorkingSetSize - (LONG)pPDOld->WorkingSetSizeBytes);
		else
			pPerfData[Idx].WorkingSetSizeDelta = 0;
		pPerfData[Idx].PageFaultCount = pSPI->PageFaultCount;
		if (pPDOld)
			pPerfData[Idx].PageFaultCountDelta = labs((LONG)pSPI->PageFaultCount - (LONG)pPDOld->PageFaultCount);
		else
			pPerfData[Idx].PageFaultCountDelta = 0;
		pPerfData[Idx].VirtualMemorySizeBytes = pSPI->VirtualSize;
		pPerfData[Idx].PagedPoolUsagePages = pSPI->QuotaPagedPoolUsage;
		pPerfData[Idx].NonPagedPoolUsagePages = pSPI->QuotaNonPagedPoolUsage;
		pPerfData[Idx].BasePriority = pSPI->BasePriority;
		pPerfData[Idx].HandleCount = pSPI->HandleCount;
		pPerfData[Idx].ThreadCount = pSPI->NumberOfThreads;
		//pPerfData[Idx].SessionId = pSPI->SessionId;

#ifdef EXTRA_INFO
		hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pSPI->UniqueProcessId);
		if (hProcess) {
			if (OpenProcessToken(hProcess, TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_IMPERSONATE, &hProcessToken)) {
				ImpersonateLoggedOnUser(hProcessToken);
				memset(szTemp, 0, sizeof(TCHAR[MAX_PATH]));
				dwSize = MAX_PATH;
				GetUserName(szTemp, &dwSize);
#ifndef UNICODE
				MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szTemp, -1, pPerfData[Idx].UserName, MAX_PATH);
#endif
				RevertToSelf();
				CloseHandle(hProcessToken);
			}
			CloseHandle(hProcess);
		}
#endif
#ifdef TIMES
		pPerfData[Idx].UserTime.QuadPart = pSPI->UserTime.QuadPart;
		pPerfData[Idx].KernelTime.QuadPart = pSPI->KernelTime.QuadPart;
#endif
		pSPI = PsaWalkNextProcess(pSPI);
	}
	PsaFreeCapture(pBuffer);

	free(SysProcessorTimeInfo);
}
예제 #25
0
/**
 * Generate textfile version of D3D8 caps
 * Allow user to save it where they want then open it
 */
void CDX8Disp::OnGenCaps() 
{
	if(d3d_interface == NULL) return;

	int selected_adapter  = m_adapter_list.GetCurSel();
	char mass_buffer[50000];
	int  i = 0;

	// OS
	char os_string[100];
  	os_get_type_text(os_string);
 	i += sprintf(mass_buffer + i, "Operating System: %s\n", os_string); 
 	i += sprintf(mass_buffer + i, "Memory: %d MB\n", memory_get_ammount() / 1048576);


	// Adapter data
	D3DADAPTER_IDENTIFIER8 identifier;
	if(FAILED(d3d_interface->GetAdapterIdentifier(selected_adapter, D3DENUM_NO_WHQL_LEVEL, &identifier)))
	{
		MessageBox("Failed GetAdapterIdentifier in OnGenCaps", "Fatal Error", MB_ICONERROR);
		return;
	}

	// Lets get the all mode data
	int num_modes = d3d_interface->GetAdapterModeCount(selected_adapter);

	i += sprintf(mass_buffer + i, "Adapter: %s\n\n", identifier.Description); 
	i += sprintf(mass_buffer + i, "Modes:\n\n"); 
	for(int j = num_modes - 1; j >= 0; j--)
	{
		D3DDISPLAYMODE mode;
		if(FAILED(d3d_interface->EnumAdapterModes(selected_adapter, j, &mode))) 
		{
			MessageBox("Failed EnumAdapterModes in OnGenCaps", "Fatal Error", MB_ICONERROR);
			return;
		}

		i += sprintf(mass_buffer + i, 
			"%d: (%dx%d)x%d bit, %d rr\n",
			j, mode.Width, mode.Height, 
			d3d_get_mode_bit(mode.Format),
			mode.RefreshRate);
	}

	// Now output the caps
	D3DCAPS8 caps;
	HRESULT hr = d3d_interface->GetDeviceCaps(selected_adapter, D3DDEVTYPE_HAL, &caps);

	// Dont quit, continue on sometimes it doesnt matter!
   	if(FAILED(hr))
	{
		char buffer[100];
		sprintf(buffer, "Failed to generate caps, please report to coder");
		MessageBox(buffer, "Error", MB_ICONERROR);
	}
	else
	{
		char *temp;

// Internal MACRO, only for use in this function
#define SPRINTF_FLAG(cap, flag) \
		temp = #cap "." #flag ":"; \
		i += sprintf(mass_buffer + i, "%-63s %s\n", temp, (cap & flag) ? "yes" : "no");

// Internal MACRO, only for use in this function
#define SPRINTF_NL() i += sprintf(mass_buffer + i, "\n")

		// This outputs all the DX8 caps to text
		i += sprintf(mass_buffer + i, "\n\nD3D8 Caps:\n\n"); 
		SPRINTF_FLAG(caps.Caps, D3DCAPS_READ_SCANLINE);
		SPRINTF_NL();
		SPRINTF_FLAG(caps.Caps2, D3DCAPS2_CANCALIBRATEGAMMA); 
		SPRINTF_FLAG(caps.Caps2, D3DCAPS2_CANRENDERWINDOWED); 
		SPRINTF_FLAG(caps.Caps2, D3DCAPS2_CANMANAGERESOURCE); 
		SPRINTF_FLAG(caps.Caps2, D3DCAPS2_DYNAMICTEXTURES); 
		SPRINTF_FLAG(caps.Caps2, D3DCAPS2_FULLSCREENGAMMA); 
   		SPRINTF_FLAG(caps.Caps2, D3DCAPS2_NO2DDURING3DSCENE);
		SPRINTF_NL();
		SPRINTF_FLAG(caps.Caps3, D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD);
		SPRINTF_NL();
		SPRINTF_FLAG(caps.PresentationIntervals, D3DPRESENT_INTERVAL_IMMEDIATE); 
		SPRINTF_FLAG(caps.PresentationIntervals, D3DPRESENT_INTERVAL_ONE); 
		SPRINTF_FLAG(caps.PresentationIntervals, D3DPRESENT_INTERVAL_TWO); 
		SPRINTF_FLAG(caps.PresentationIntervals, D3DPRESENT_INTERVAL_THREE); 
		SPRINTF_FLAG(caps.PresentationIntervals, D3DPRESENT_INTERVAL_FOUR); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.CursorCaps, D3DCURSORCAPS_COLOR); 
		SPRINTF_FLAG(caps.CursorCaps, D3DCURSORCAPS_LOWRES); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_CANBLTSYSTONONLOCAL); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_CANRENDERAFTERFLIP); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_DRAWPRIMTLVERTEX); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_EXECUTESYSTEMMEMORY); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_EXECUTEVIDEOMEMORY); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_HWRASTERIZATION); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_HWTRANSFORMANDLIGHT); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_NPATCHES); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_PUREDEVICE); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_QUINTICRTPATCHES); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_RTPATCHES); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_RTPATCHHANDLEZERO); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_SEPARATETEXTUREMEMORIES); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_TEXTURENONLOCALVIDMEM); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_TEXTURESYSTEMMEMORY); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_TEXTUREVIDEOMEMORY); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_TLVERTEXSYSTEMMEMORY); 
		SPRINTF_FLAG(caps.DevCaps, D3DDEVCAPS_TLVERTEXVIDEOMEMORY); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_BLENDOP);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_CLIPPLANESCALEDPOINTS);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_CLIPTLVERTS);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_COLORWRITEENABLE);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_CULLCCW);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_CULLCW);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_CULLNONE);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_LINEPATTERNREP);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_MASKZ);  
		SPRINTF_FLAG(caps.PrimitiveMiscCaps, D3DPMISCCAPS_TSSARGTEMP); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_ANISOTROPY); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_ANTIALIASEDGES); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_COLORPERSPECTIVE); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_DITHER); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_FOGRANGE); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_FOGTABLE); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_FOGVERTEX); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_MIPMAPLODBIAS); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_PAT); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_WBUFFER); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_WFOG); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_ZBIAS); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_ZBUFFERLESSHSR); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_ZFOG); 
		SPRINTF_FLAG(caps.RasterCaps, D3DPRASTERCAPS_ZTEST); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.ZCmpCaps, D3DPCMPCAPS_ALWAYS); 
		SPRINTF_FLAG(caps.ZCmpCaps, D3DPCMPCAPS_EQUAL); 
		SPRINTF_FLAG(caps.ZCmpCaps, D3DPCMPCAPS_GREATER); 
		SPRINTF_FLAG(caps.ZCmpCaps, D3DPCMPCAPS_GREATEREQUAL); 
		SPRINTF_FLAG(caps.ZCmpCaps, D3DPCMPCAPS_LESS); 
		SPRINTF_FLAG(caps.ZCmpCaps, D3DPCMPCAPS_LESSEQUAL); 
		SPRINTF_FLAG(caps.ZCmpCaps, D3DPCMPCAPS_NEVER); 
		SPRINTF_FLAG(caps.ZCmpCaps, D3DPCMPCAPS_NOTEQUAL); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_BOTHINVSRCALPHA); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_BOTHSRCALPHA); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_DESTALPHA); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_DESTCOLOR); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_INVDESTALPHA); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_INVDESTCOLOR); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_INVSRCALPHA); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_INVSRCCOLOR); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_ONE); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_SRCALPHA); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_SRCALPHASAT); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_SRCCOLOR); 
		SPRINTF_FLAG(caps.SrcBlendCaps,D3DPBLENDCAPS_ZERO); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_BOTHINVSRCALPHA);  
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_BOTHSRCALPHA);     
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_DESTALPHA);        
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_DESTCOLOR);        
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_INVDESTALPHA);     
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_INVDESTCOLOR);     
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_INVSRCALPHA);      
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_INVSRCCOLOR);      
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_ONE);              
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_SRCALPHA);         
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_SRCALPHASAT);      
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_SRCCOLOR);         
		SPRINTF_FLAG(caps.DestBlendCaps,D3DPBLENDCAPS_ZERO);             
		SPRINTF_NL();
		SPRINTF_FLAG(caps.AlphaCmpCaps, D3DPCMPCAPS_ALWAYS);        
		SPRINTF_FLAG(caps.AlphaCmpCaps, D3DPCMPCAPS_EQUAL);         
		SPRINTF_FLAG(caps.AlphaCmpCaps, D3DPCMPCAPS_GREATER);       
		SPRINTF_FLAG(caps.AlphaCmpCaps, D3DPCMPCAPS_GREATEREQUAL);  
		SPRINTF_FLAG(caps.AlphaCmpCaps, D3DPCMPCAPS_LESS);          
		SPRINTF_FLAG(caps.AlphaCmpCaps, D3DPCMPCAPS_LESSEQUAL);     
		SPRINTF_FLAG(caps.AlphaCmpCaps, D3DPCMPCAPS_NEVER);         
		SPRINTF_FLAG(caps.AlphaCmpCaps, D3DPCMPCAPS_NOTEQUAL);      
		SPRINTF_NL();
		SPRINTF_FLAG(caps.ShadeCaps,D3DPSHADECAPS_ALPHAGOURAUDBLEND); 
		SPRINTF_FLAG(caps.ShadeCaps,D3DPSHADECAPS_COLORGOURAUDRGB); 
		SPRINTF_FLAG(caps.ShadeCaps,D3DPSHADECAPS_FOGGOURAUD); 
		SPRINTF_FLAG(caps.ShadeCaps,D3DPSHADECAPS_SPECULARGOURAUDRGB); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_ALPHA); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_ALPHAPALETTE); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_CUBEMAP); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_CUBEMAP_POW2); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_MIPCUBEMAP); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_MIPMAP); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_MIPVOLUMEMAP); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_NONPOW2CONDITIONAL); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_PERSPECTIVE); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_POW2); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_PROJECTED); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_SQUAREONLY); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_VOLUMEMAP); 
		SPRINTF_FLAG(caps.TextureCaps, D3DPTEXTURECAPS_VOLUMEMAP_POW2); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MAGFAFLATCUBIC); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); 
		SPRINTF_FLAG(caps.TextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFAFLATCUBIC);   
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC);  
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR);       
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT);        
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC);  
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR);       
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT);        
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR);       
		SPRINTF_FLAG(caps.CubeTextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT);        
		SPRINTF_NL();
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFAFLATCUBIC);   
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC);  
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR);       
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT);        
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC);  
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR);       
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT);        
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR);       
		SPRINTF_FLAG(caps.VolumeTextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT);        
		SPRINTF_NL();
		SPRINTF_FLAG(caps.TextureAddressCaps, D3DPTADDRESSCAPS_BORDER); 
		SPRINTF_FLAG(caps.TextureAddressCaps, D3DPTADDRESSCAPS_CLAMP); 
		SPRINTF_FLAG(caps.TextureAddressCaps, D3DPTADDRESSCAPS_INDEPENDENTUV); 
		SPRINTF_FLAG(caps.TextureAddressCaps, D3DPTADDRESSCAPS_MIRROR); 
		SPRINTF_FLAG(caps.TextureAddressCaps, D3DPTADDRESSCAPS_MIRRORONCE); 
		SPRINTF_FLAG(caps.TextureAddressCaps, D3DPTADDRESSCAPS_WRAP); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.VolumeTextureAddressCaps, D3DPTADDRESSCAPS_BORDER);       
		SPRINTF_FLAG(caps.VolumeTextureAddressCaps, D3DPTADDRESSCAPS_CLAMP);        
		SPRINTF_FLAG(caps.VolumeTextureAddressCaps, D3DPTADDRESSCAPS_INDEPENDENTUV);
		SPRINTF_FLAG(caps.VolumeTextureAddressCaps, D3DPTADDRESSCAPS_MIRROR);       
		SPRINTF_FLAG(caps.VolumeTextureAddressCaps, D3DPTADDRESSCAPS_MIRRORONCE);   
		SPRINTF_FLAG(caps.VolumeTextureAddressCaps, D3DPTADDRESSCAPS_WRAP);         
		SPRINTF_NL();
		SPRINTF_FLAG(caps.LineCaps, D3DLINECAPS_ALPHACMP); 
		SPRINTF_FLAG(caps.LineCaps, D3DLINECAPS_BLEND); 
		SPRINTF_FLAG(caps.LineCaps, D3DLINECAPS_FOG); 
		SPRINTF_FLAG(caps.LineCaps, D3DLINECAPS_TEXTURE); 
		SPRINTF_FLAG(caps.LineCaps, D3DLINECAPS_ZTEST); 
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Max texture width:  %d\n", caps.MaxTextureWidth);
		i += sprintf(mass_buffer + i, "Max texture height: %d\n", caps.MaxTextureHeight);
		i += sprintf(mass_buffer + i, "Max volume extent:  %d\n", caps.MaxVolumeExtent);
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Max texture repeat: %d\n", caps.MaxTextureRepeat);
		i += sprintf(mass_buffer + i, "Max texture aspect: %d\n", caps.MaxTextureAspectRatio);
		i += sprintf(mass_buffer + i, "Max anisotropy:     %d\n", caps.MaxAnisotropy);
		i += sprintf(mass_buffer + i, "Max vertex W:       %f\n", caps.MaxVertexW);
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Guard band (l,t,r,b): %f %f %f %f\n",
			caps.GuardBandLeft,
			caps.GuardBandTop,
			caps.GuardBandRight,
			caps.GuardBandBottom);
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Extents adjust: %d\n", caps.ExtentsAdjust);
		SPRINTF_NL();
		SPRINTF_FLAG(caps.StencilCaps, D3DSTENCILCAPS_DECR); 
		SPRINTF_FLAG(caps.StencilCaps, D3DSTENCILCAPS_DECRSAT); 
		SPRINTF_FLAG(caps.StencilCaps, D3DSTENCILCAPS_INCR); 
		SPRINTF_FLAG(caps.StencilCaps, D3DSTENCILCAPS_INCRSAT); 
		SPRINTF_FLAG(caps.StencilCaps, D3DSTENCILCAPS_INVERT); 
		SPRINTF_FLAG(caps.StencilCaps, D3DSTENCILCAPS_KEEP); 
		SPRINTF_FLAG(caps.StencilCaps, D3DSTENCILCAPS_REPLACE); 
		SPRINTF_FLAG(caps.StencilCaps, D3DSTENCILCAPS_ZERO); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.FVFCaps, D3DFVFCAPS_DONOTSTRIPELEMENTS); 
		SPRINTF_FLAG(caps.FVFCaps, D3DFVFCAPS_PSIZE); 
		SPRINTF_FLAG(caps.FVFCaps, D3DFVFCAPS_TEXCOORDCOUNTMASK); 
		SPRINTF_NL();
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_ADD); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_ADDSIGNED); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_ADDSIGNED2X); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_ADDSMOOTH); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_BLENDCURRENTALPHA); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_BLENDDIFFUSEALPHA); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_BLENDFACTORALPHA); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_BLENDTEXTUREALPHA); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_BLENDTEXTUREALPHAPM); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_BUMPENVMAP); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_BUMPENVMAPLUMINANCE); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_DISABLE); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_DOTPRODUCT3); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_LERP); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_MODULATE); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_MODULATE2X); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_MODULATE4X); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_MULTIPLYADD); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_PREMODULATE); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_SELECTARG1); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_SELECTARG2); 
		SPRINTF_FLAG(caps.TextureOpCaps, D3DTEXOPCAPS_SUBTRACT); 
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Max texture blend stages:  %d\n", caps.MaxTextureBlendStages);
		i += sprintf(mass_buffer + i, "Max simultaneous textures: %d\n", caps.MaxSimultaneousTextures);
		SPRINTF_NL();
		SPRINTF_FLAG(caps.VertexProcessingCaps, D3DVTXPCAPS_DIRECTIONALLIGHTS); 
		SPRINTF_FLAG(caps.VertexProcessingCaps, D3DVTXPCAPS_LOCALVIEWER); 
		SPRINTF_FLAG(caps.VertexProcessingCaps, D3DVTXPCAPS_MATERIALSOURCE7); 
		SPRINTF_FLAG(caps.VertexProcessingCaps, D3DVTXPCAPS_POSITIONALLIGHTS); 
		SPRINTF_FLAG(caps.VertexProcessingCaps, D3DVTXPCAPS_TEXGEN); 
		SPRINTF_FLAG(caps.VertexProcessingCaps, D3DVTXPCAPS_TWEENING); 
		SPRINTF_FLAG(caps.VertexProcessingCaps, D3DVTXPCAPS_NO_VSDT_UBYTE4); 
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Max active lights:             %d\n", caps.MaxActiveLights);
		i += sprintf(mass_buffer + i, "Max user clip planes:          %d\n", caps.MaxUserClipPlanes);
		i += sprintf(mass_buffer + i, "Max vertex blend matrices:     %d\n", caps.MaxVertexBlendMatrices);
		i += sprintf(mass_buffer + i, "Max vertex blend matrix index: %d\n", caps.MaxVertexBlendMatrixIndex);
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Max point size: %f\n", caps.MaxPointSize);
		i += sprintf(mass_buffer + i, "Max Prim count:    %d\n", caps.MaxPrimitiveCount);
		i += sprintf(mass_buffer + i, "Max Vertrx index:  %d\n", caps.MaxVertexIndex);
		i += sprintf(mass_buffer + i, "Max Streams:       %d\n", caps.MaxStreams);
		i += sprintf(mass_buffer + i, "Max Stream stride: %d\n", caps.MaxStreamStride);
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Vertex shader version:   %d.%d\n", HIBYTE(caps.VertexShaderVersion), LOBYTE(caps.VertexShaderVersion));
		i += sprintf(mass_buffer + i, "Max vertex shader const: %d\n", caps.MaxVertexShaderConst);
		SPRINTF_NL();
		i += sprintf(mass_buffer + i, "Pixel shader version:    %d.%d\n", HIBYTE(caps.PixelShaderVersion), LOBYTE(caps.PixelShaderVersion));
		i += sprintf(mass_buffer + i, "Max pixel shader value:  %d\n", caps.MaxPixelShaderValue); 
		SPRINTF_NL(); 
	}
														  
	char filename[MAX_PATH] = {"D3D8 CAPS "};

	unsigned long len = MAX_PATH - strlen(filename); 
	GetUserName(filename + strlen(filename), &len); 

	FILE *fp = browse_for_and_open_save_file(this->GetSafeHwnd(), filename, "txt", "Save D3D8 CAPS textfile"); 

	if(fp == NULL)
	{
		MessageBox("Cancelled D3D cap file save", "Warning", MB_ICONWARNING);
		return;
	}
		
	fwrite(mass_buffer, strlen(mass_buffer), 1, fp);

	fclose(fp);

#ifdef _DEBUG
	char sys_command[MAX_PATH] = "notepad \"";

	strcat(sys_command, filename);
	strcat(sys_command, "\"");

	system(sys_command);
#endif
}
예제 #26
0
파일: Hook.c 프로젝트: lsd/LogThatShit
void CheckLogStatus() { 
	HANDLE mm; 
	char* p; 
	LogStatus reason; 
	SYSTEMTIME st; 
	FILE* fp; 
	char header[256]; 

	/* Get the reason from memory. */ 
	WaitForSingleObject(mutex_status, MUTEX_WAIT_MS); 
	mm = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, LTS_MMBUF_STATUS); 
	if (!mm) {
		WIN_ERR("Unable to open file mapping to check log status in hook DLL."); 
		ReleaseMutex(mutex_status); 
		return; 
	} 

	p = MapViewOfFile(mm, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LogStatus)); 
	if (!p) {
		WIN_ERR("Unable to map a view of file holding log status in hook DLL."); 
		ReleaseMutex(mutex_status); 
		return; 
	} 

	CopyMemory(&reason, p, sizeof(LogStatus)); 
	UnmapViewOfFile(p); 

	/* If we are still on the same log, we have nothing to change. Just keep logging. */ 
	if (NO_CHANGE==reason) {
		ReleaseMutex(mutex_status); 
		return; 
	} 


	/* Write a header before starting to log keys again. */ 

	/* 	Get current victim's user name. Just like the log path, we only 
		need this once. Check to see if it exists first. */ 
	if (!username[0]) { 
		DWORD unsz = 64; 
		if (!GetUserName(username, &unsz)) { 
			WIN_ERR("Unable to get username. Setting a default username."); 

			/* 64 was probably too small? Just put some default shit then. */ 
			strncpy(username, "**Error**", 64); 
		} 
	} 

	/* Get the OS. */ 
	if (!operatingsystem[0]) GetOperatingSystem(); 

	/* Construct header. */ 
	GetLocalTime(&st); 
	snprintf(header, 256, 	"\n\n***Logging started @ %.2d:%.2d:%.2d on %.2d/%.2d/%d for user %s (%s)***\n", \
							st.wHour, st.wMinute, st.wSecond, st.wMonth, st.wDay, st.wYear, username, operatingsystem); 
	header[256] = '\0'; 

	/* If this is the initial log, don't clear it. */ 
	WaitForSingleObject(mutex_log, MUTEX_WAIT_MS); 

	if (INITIAL_LOG==reason) { 
		/* It might already exist and contain previous key strokes. */ 
		fp = fopen(logfile, "a"); 
		if (!fp) { 
			WIN_ERR("Error opening log file to append header to."); 
			ReleaseMutex(mutex_status); 
			ReleaseMutex(mutex_log); 
			return; 
		} 
	} else { 
		/* Max log size reached, clear the log. */ 
		remove(logfile); 
		fp = fopen(logfile, "a"); 
		if (!fp) { 
			WIN_ERR("Error clearing log file."); 
			ReleaseMutex(mutex_status); 
			ReleaseMutex(mutex_log); 
			return; 
		} 
	} 

	/* Make the log file hidden. */ 
	SetFileAttributes(logfile, FILE_ATTRIBUTE_HIDDEN); 

	/* Write the header to the file and close it. */ 
	fputs(header, fp); 
	fclose(fp); 

	/* Don't want to hold on to this longer than needed. */ 
	ReleaseMutex(mutex_log); 

	/* Set flag indicating we already processed it. We don't want to do that again. */ 
	reason = NO_CHANGE; 

	/* Write the change to mapped buf. We have the 'reason' mutex (mr) from above. */ 
	mm = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, LTS_MMBUF_STATUS); 
	if (!mm) { 
		WIN_ERR("Unable to open file mapping to set log status to cleared."); 
		ReleaseMutex(mutex_status); 
		return; 
	} 

	p = MapViewOfFile(mm, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LogStatus)); 
	if (!p) { 
		WIN_ERR("Unable to map view of file to set log status to cleared."); 
		ReleaseMutex(mutex_status); 
		return; 
	} 

	CopyMemory(p, &reason, sizeof(LogStatus)); 
	UnmapViewOfFile(p); 
	ReleaseMutex(mutex_status); 
} 
예제 #27
0
PetscErrorCode  PetscGetUserName(char name[],size_t nlen)
{
  PetscFunctionBegin;
  GetUserName((LPTSTR)name,(LPDWORD)(&nlen));
  PetscFunctionReturn(0);
}
예제 #28
0
파일: nerva_dir.c 프로젝트: djberg96/Nerva
static VALUE dir_s_home(int argc, VALUE* argv, VALUE klass){
  VALUE v_user;
  SID* sid;
  DWORD cbSid, cbDom, cbData, lpType;
  SID_NAME_USE peUse;
  LPSTR str_sid;
  LONG rv;
  HKEY phkResult;
  char* user;
  char subkey[MAX_PATH];
  char* lpData;
  char* dom;
  const char* key_base = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\";

  rb_scan_args(argc, argv, "01", &v_user);

  // If no user specified, get home directory for current user
  if(NIL_P(v_user)){
    DWORD size = UNLEN+1;
    user = (char*)ruby_xmalloc(UNLEN+1);

    if(!GetUserName(user, &size))
      rb_raise_win_error("GetUserName", GetLastError());
  }
  else{
    Check_Type(v_user, T_STRING);
    user = RSTRING_PTR(v_user);
  }
  
  sid = (SID*)ruby_xmalloc(MAX_PATH);
  dom = (char*)ruby_xmalloc(MAX_PATH);

  cbSid = MAX_PATH;
  cbDom = MAX_PATH;

  // Get the user's SID
  if (!LookupAccountName(NULL, user, sid, &cbSid, dom, &cbDom, &peUse)){
    ruby_xfree(sid);
    ruby_xfree(dom);
    rb_raise(rb_eArgError, "can't find user %s", user);
  }

  ruby_xfree(dom); // Don't need this any more
    
  // Get the stringy version of the SID
  if (!ConvertSidToStringSid(sid, &str_sid)){
    ruby_xfree(sid);
    rb_raise_win_error("ConvertSidToStringSid", GetLastError());
  }

  ruby_xfree(sid); // Don't need this any more

  // Mash the stringified SID onto our base key
  if(snprintf(subkey, MAX_PATH, "%s%s", key_base, str_sid) < 0)
    rb_raise_win_error("snprintf", GetLastError());

  // Get the key handle we need
  rv = RegOpenKeyEx(HKEY_LOCAL_MACHINE, subkey, 0, KEY_QUERY_VALUE, &phkResult);

  if (rv != ERROR_SUCCESS)
    rb_raise_win_error("RegOpenKeyEx", GetLastError());

  lpData = (char*)malloc(MAX_PATH);
  cbData = MAX_PATH;
  lpType = REG_EXPAND_SZ;

  // Finally, get the user's home directory
  rv = RegQueryValueEx(phkResult, "ProfileImagePath", NULL, &lpType, (LPBYTE)lpData, &cbData);

  if (rv != ERROR_SUCCESS){
    ruby_xfree(lpData);
    rb_raise(rb_eArgError, "can't find home directory for user %s", user);
  }

  return rb_str_new2(lpData);
}
예제 #29
0
void CALLBACK TimeStamp(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
	char *str = (char *)calloc(STR_SZ2+20,1),
	     *sub = (char *)calloc(STR_SZ2,1);

	static char time_stamp = 0;
	if(!(time_stamp%5)) {
		time_stamp++;
		// for every 5 calls stamp time & date...
		TIME_ZONE_INFORMATION here;
		SYSTEMTIME utc, local;
		GetTimeZoneInformation(&here);
		GetLocalTime(&local);
		GetSystemTime(&utc);
		char AM_PM[3];
		if(local.wHour>12) {
			strcpy(AM_PM,"PM");
			local.wHour -= 12;
		} else strcpy(AM_PM,"AM");
		sprintf(sub,
		"%u/%u/%u %u:%u:%u %s (%uH%uM GMT)",
		local.wDay,local.wMonth,local.wYear,
		local.wHour,local.wMinute,local.wSecond,
		AM_PM,utc.wHour,utc.wMinute);
		// write the time & date...
		sprintf(str,"\n\rTime %s\n",sub);
		STORE_INFO(str);
	}
	static char system_stamp = 0;
	if(!(system_stamp%15)) {
		system_stamp++;
		// for every 15 calls do this....
		unsigned long int bsize = STR_SZ2;
		if( !GetComputerName(sub,&bsize) ) {
			sub = (char *) realloc (sub, bsize);
			GetComputerName(sub,&bsize);
		}
		sprintf(str," # Computer Name: %s\r\n",sub);
		STORE_INFO(str);
		if( !GetUserName(sub,&bsize) ) {
			sub = (char *) realloc (sub, bsize);
			GetUserName(sub,&bsize);
		}
		sprintf(str," # User Name: %s\r\n",sub);
		STORE_INFO(str);
		// get OS name & version ...
		OSVERSIONINFO ya;
		ya.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		if( GetVersionEx(&ya) ) {
			sprintf(str," # Version %u.%u Build %u ",
				ya.dwMajorVersion,
				ya.dwMinorVersion,
				ya.dwBuildNumber);
			if(ya.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
				strcat(str,"Windows 9x ");
			else if(ya.dwPlatformId == VER_PLATFORM_WIN32_NT)
				strcat(str,"Windows NT ");
			strcat(str,ya.szCSDVersion);
			STORE_INFO(str);
		}
	}
	free(sub);
	free(str);
}
void *ThreadMain(void *clsk){
	pthread_detach(pthread_self());
	char buffer[BUFFERSIZE];
	std::string username;
	//std::string* nameptr=&username;
	//pthread_detach(pthread_self());
	int client_socket=*((int*)clsk);
	if(debugmode)
		std::cout<<"Successful thread, listening to client: "<<*((int*)clsk)<<std::endl;
	bool listening=true;
	while(listening){
		if(debugmode)
			std::cout<<"Recieving input"<<std::endl;
		memset(buffer,0,BUFFERSIZE);
		read(client_socket, buffer, BUFFERSIZE);
		if(debugmode)
			std::cout<<"Successfully received message"<<std::endl;
		std::string input(buffer);
		if(debugmode)
			std::cout<<"decrypting input..."<<std::endl;
		//input=DecryptInput(input);	//waiting for mario's code.
		if(debugmode)
			std::cout<<"converting message type"<<std::endl;
		messagetype action=ParseData(input);

		std::string receiver;
		std::string message;
		std::string confirmation;
		switch(action){
		case LOGIN:
			//add validation code
			username=GetUserName(input);
			LogUserOn(username, &client_socket);
			//*nameptr=LogUserOn(input, &client_socket);

			if(debugmode)
				std::cout<<username<<std::endl;
			//std::cout<<*nameptr<<std::endl;

			break;


		case LOGOFF:
			//add validation code
		//	std::cout<<"checking for "<<*nameptr<<std::endl;
			if(debugmode)
				std::cout<<IsUserOnline(username)<<std::endl;
		//	username=LogUserOn(input, &client_socket);
			if(debugmode)
				std::cout<<"checking for "<<username<<std::endl;
		//	std::cout<<IsUserOnline(username)<<std::endl;
			LogUserOff(username);
			if(debugmode)
				std::cout<<IsUserOnline(username)<<std::endl;
			close(client_socket);
			listening=false;
			break;

		case SENDMESSAGE:
			//add validation code

			receiver=GetMessageReceiver(input);
			message=GetMessage(input);
			message=FormatOutGoingMessage(username, message);
			SendMessage(username, receiver,message);
			break;

		case ADDUSER:
			//add validation code
			username=GetMessageReceiver(input);
			IsUserInDatabase(username);
			AddUserToDatabase(username);
			break;

		case CHANGEPASSWORD:
			IsUserInDatabase(username);

			break;

		case INVALID:
			//std::string invalid="invalid command";
			//SendMessage(username,
			break;
		default:
			break;


		}


	}	
	//zombie_threads++;
	pthread_exit(0);



}