Ejemplo n.º 1
0
buffer_t *conn_transmit(connection_t conn, const unsigned char *buf, size_t size, int timeout)
{
	//int retries = 3;
	unsigned int bytes;
	SYSTEMTIME systemTime;
	unsigned long adj_timeout = timeout;
	int ret;
	buffer_t *rb;
    DWORD nBytes, nTransfer;
	
	debug("Transmitting data, size %d\n",size);

	hdlc_sendpacket(conn,buf,size);

	GetSystemTime( &systemTime );

	/* Prepare event for overlapped receive */

	conn->rol.Offset = conn->rol.OffsetHigh = 0;
	ResetEvent( conn->rol.hEvent );

	do {
		bytes = get_bytes_in_rxqueue(conn);

		debug("Bytes in RX queue: %lu\n",bytes);

		/* If RX queue already contains bytes, read them at once */
		if (bytes) {
			if (ReadFile( conn->hcomm, conn->rxbuf, bytes, &nBytes, &conn->rol)==0) {
				/* Something weird happened.. */
				fprintf(stderr,"Error in ReadFile(): %lu\n", GetLastError());
				return NULL;
			}

			debug("Read %lu bytes, processing\n", nBytes);

			if (verbose>2) {
				int i;
				printf("Rx:");
				for (i=0; i<nBytes; i++) {
					printf(" 0x%02x",conn->rxbuf[i]);
				}
				printf("\n");
			}

			/* Send to processing at once */
			rb = hdlc_process(conn->rxbuf, nBytes);
			if (rb) {
				return rb;
			}
			/* Not enough data yet. Let go. */

		} else {
			/* No known size, have to read one byte at once */
			debug("No bytes in queue\n");

			ResetEvent( conn->rol.hEvent );

			ret = ReadFile( conn->hcomm, conn->rxbuf, 1, &nBytes, &conn->rol);
			switch (ret) {
			default:
				/* We read data OK */
				if (nBytes) {
					debug("Read %lu bytes\n", nBytes);
					rb = hdlc_process(conn->rxbuf,1);
					if (rb)
						return rb;
				}
				break;
			case 0:
				if (GetLastError()==ERROR_IO_PENDING) {
					/* Overlapped read going on */
					switch (WaitForSingleObject(conn->rol.hEvent, adj_timeout)) {
					case WAIT_TIMEOUT:
                        break;
					case WAIT_OBJECT_0:
						/* Read data */
						if (!GetOverlappedResult(conn->hcomm, &conn->rol, &nTransfer, FALSE)) {
							/* Some error occured... */
							fprintf(stderr,"Error in GetOverlappedResult(): %lu\n",GetLastError());
							return NULL;
						} else {
							/* RX finished, process */
							rb = hdlc_process(conn->rxbuf,1);
							if (rb)
								return rb;
						}
                        break;
					default:
						return NULL;

					}
				} else {
					fprintf(stderr,"Error in ReadFile: %lu\n",GetLastError());
					return NULL;
				}
			}
		}
	} while (1);

	return NULL;
}
Ejemplo n.º 2
0
//---------------------------------------------------------------------------
void __fastcall TFormLog::ButtonLogClick(TObject *Sender)
{
        if(EditQRZ->Text=="") return;

        int H;
        AnsiString LogName = ThePath + "\\stream.adi";

        if(FileExists(LogName))
        {
           H = FileOpen(LogName,fmOpenReadWrite);
           if(H<0)
           {
              Application->MessageBox("Cannot write to log","IZ8BLY PSK31 Lab",MB_OK | MB_ICONSTOP);
              return;
           }
           FileSeek(H,0,2);
        }
        else
        {
           H = FileCreate(LogName);
           if(H<0)
           {
              Application->MessageBox("Cannot write to log","IZ8BLY PSK31 Lab",MB_OK | MB_ICONSTOP);
              return;
           }
           FileWriteString(H,"Created by IZ8BLY PSK31 Lab\r\n<EOH>\r\n");
        }

        AnsiString Linea;

        TDateTime TD;
        if(UTCTimeLog)
        {
           SYSTEMTIME SystemTime;
           GetSystemTime(&SystemTime);
           TD = SystemTimeToDateTime(SystemTime);
        }
        else
        {
           TD = TDateTime().CurrentDateTime();
        }

        Linea = FormatAdif("CALL",EditQRZ->Text) +
                FormatAdif("NAME",EditName->Text)+
                FormatAdif("QTH",EditQTH->Text)+
                FormatAdif("RST_RCVD",EditRSTReceived->Text)+
                FormatAdif("RST_SENT",EditRSTSent->Text)+
                FormatAdif("FREQ",EditFrequency->Text)+
                FormatAdif("MODE","STREAM")+
                FormatAdif("QSO_DATE",TD.FormatString("yyyymmdd"))+
                FormatAdif("TIME_ON",TD.FormatString("hhmm"))+
                FormatAdif("COMMENT",EditComments->Text)+
                "<EOR>\r\n";

        FileWriteString(H,Linea);
        FileClose(H);

        char oldclip[2048];
        Clipboard()->GetTextBuf(oldclip,2048);

        Clipboard()->SetTextBuf(Linea.c_str());
        SendMessage(HWND_BROADCAST,IZ8BLY,0,0);
        Clipboard()->SetTextBuf(oldclip);

        ButtonLog->Enabled = false;
}
Ejemplo n.º 3
0
static HRESULT GenerateCrashDump(MINIDUMP_TYPE flags, EXCEPTION_POINTERS *seh) {
	HRESULT error = S_OK;

	// get the time
	SYSTEMTIME sysTime;
	GetSystemTime(&sysTime);

	// build the filename: APPNAME_COMPUTERNAME_DATE_TIME.DMP
	char path[MAX_PATH] = { 0 };
	char moduleName[MAX_PATH] = { 0 };

	const size_t len = GetModuleFileName(GetCurrentModule(), moduleName, sizeof(moduleName));
	moduleName[len] = 0;

	const char *slash = strrchr(moduleName, '\\');

	if (!slash) {
		slash = moduleName;
	} else {
		slash++;
	}

	const char *dot = strrchr(moduleName, '.');
	const size_t nameLength = dot ? (dot - slash) : strlen(slash);

	g_strlcpy(moduleName, slash, nameLength + 1);

	sprintf_s(path, ARRAYSIZE(path),
	          ".\\%s_%04u-%02u-%02u_%02u-%02u-%02u.dmp",
	          moduleName,
	          sysTime.wYear, sysTime.wMonth, sysTime.wDay,
	          sysTime.wHour, sysTime.wMinute, sysTime.wSecond);

	// open the file
	HANDLE hFile = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
	                           NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	if (hFile == INVALID_HANDLE_VALUE) {

		error = GetLastError();
		error = HRESULT_FROM_WIN32(error);
		return error;
	}

	// get the process information
	HANDLE hProc = GetCurrentProcess();
	DWORD procID = GetProcessId(hProc);

	// if we have SEH info, package it up
	MINIDUMP_EXCEPTION_INFORMATION sehInfo;
	MINIDUMP_EXCEPTION_INFORMATION *sehPtr = NULL;

	if (seh) {

		sehInfo.ThreadId = GetCurrentThreadId();
		sehInfo.ExceptionPointers = seh;
		sehInfo.ClientPointers = FALSE;
		sehPtr = &sehInfo;
	}

	// generate the crash dump
	BOOL result = MiniDumpWriteDump(hProc, procID, hFile, flags, sehPtr, NULL, NULL);

	if (!result) {
		error = (HRESULT)GetLastError();    // already an HRESULT
	}

	// close the file
	CloseHandle(hFile);

	MessageBox(NULL, "A dump has been generated. Check the bin folder for a .dmp file.", "Crash!", MB_OK | MB_ICONERROR);

	return error;
}
Ejemplo n.º 4
0
void CCrashInfoReader::CollectMiscCrashInfo(CErrorReportInfo& eri)
{   
    // Get crash time
    Utility::GetSystemTimeUTC(eri.m_sSystemTimeUTC);

    // Open parent process handle
    HANDLE hProcess = OpenProcess(
        PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, 
        FALSE, 
        m_dwProcessId);
		
    if(hProcess!=NULL)
    {	
		SIZE_T uBytesRead = 0;
		BYTE buff[1024];
		memset(&buff, 0, 1024);
		
		// Read exception information from process memory
		if(m_pExInfo!=NULL)
		{			
			if(ReadProcessMemory(hProcess, m_pExInfo, &buff, sizeof(EXCEPTION_POINTERS), &uBytesRead) &&
				uBytesRead==sizeof(EXCEPTION_POINTERS))
			{
				EXCEPTION_POINTERS* pExcPtrs = (EXCEPTION_POINTERS*)buff;

				if(pExcPtrs->ExceptionRecord!=NULL)
				{
					DWORD64 dwExcRecordAddr = (DWORD64)pExcPtrs->ExceptionRecord;
					if(ReadProcessMemory(hProcess, (LPCVOID)dwExcRecordAddr, &buff, sizeof(EXCEPTION_RECORD), &uBytesRead) &&
						uBytesRead==sizeof(EXCEPTION_RECORD))
					{
						EXCEPTION_RECORD* pExcRec = (EXCEPTION_RECORD*)buff;

						eri.m_dwExceptionAddress = (DWORD64)pExcRec->ExceptionAddress;
					}
				}				
			}
		}
		else
			eri.m_dwExceptionAddress = 0;

        // Get number of GUI resources in use  
        eri.m_dwGuiResources = GetGuiResources(hProcess, GR_GDIOBJECTS);

        // Determine if GetProcessHandleCount function available
        typedef BOOL (WINAPI *LPGETPROCESSHANDLECOUNT)(HANDLE, PDWORD);
        HMODULE hKernel32 = LoadLibrary(_T("kernel32.dll"));
        if(hKernel32!=NULL)
        {
            LPGETPROCESSHANDLECOUNT pfnGetProcessHandleCount = 
                (LPGETPROCESSHANDLECOUNT)GetProcAddress(hKernel32, "GetProcessHandleCount");
            if(pfnGetProcessHandleCount!=NULL)
            {    
                // Get count of opened handles
                DWORD dwHandleCount = 0;
                BOOL bGetHandleCount = pfnGetProcessHandleCount(hProcess, &dwHandleCount);
                if(bGetHandleCount)
                    eri.m_dwProcessHandleCount = dwHandleCount;
                else
                    eri.m_dwProcessHandleCount = 0;
            }

            FreeLibrary(hKernel32);
            hKernel32=NULL;
        }

        // Get memory usage info
        PROCESS_MEMORY_COUNTERS meminfo;
        BOOL bGetMemInfo = GetProcessMemoryInfo(hProcess, &meminfo, 
            sizeof(PROCESS_MEMORY_COUNTERS));
        if(bGetMemInfo)
        {    
            CString sMemUsage;
#ifdef _WIN64
            sMemUsage.Format(_T("%I64u"), meminfo.WorkingSetSize/1024);
#else
            sMemUsage.Format(_T("%lu"), meminfo.WorkingSetSize/1024);
#endif 
            eri.m_sMemUsage = sMemUsage;
        }

        // Determine the period of time the process is working.
        FILETIME CreationTime, ExitTime, KernelTime, UserTime;
        /*BOOL bGetTimes = */GetProcessTimes(hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime);
        /*ATLASSERT(bGetTimes);*/
        SYSTEMTIME AppStartTime;
        FileTimeToSystemTime(&CreationTime, &AppStartTime);

        SYSTEMTIME CurTime;
        GetSystemTime(&CurTime);
        ULONG64 uCurTime = Utility::SystemTimeToULONG64(CurTime);
        ULONG64 uStartTime = Utility::SystemTimeToULONG64(AppStartTime);

        // Check that the application works for at least one minute before crash.
        // This might help to avoid cyclic error report generation when the applciation
        // crashes on startup.
        double dDiffTime = (double)(uCurTime-uStartTime)*10E-08;
        if(dDiffTime<60)
        {
            m_bAppRestart = FALSE; // Disable restart.
        } 
    }

    // Get operating system friendly name from registry.
    Utility::GetOSFriendlyName(eri.m_sOSName);

    // Determine if Windows is 64-bit.
    eri.m_bOSIs64Bit = Utility::IsOS64Bit();

    // Get geographic location.
    Utility::GetGeoLocation(eri.m_sGeoLocation);  
}
Ejemplo n.º 5
0
PBYTE LogfAllocAndBuildNewRecord(LPDWORD lpRecSize,
                                 DWORD   dwRecordNumber,
                                 WORD    wType,
                                 WORD    wCategory,
                                 DWORD   dwEventId,
                                 LPCWSTR SourceName,
                                 LPCWSTR ComputerName,
                                 DWORD   dwSidLength,
                                 PSID    lpUserSid,
                                 WORD    wNumStrings,
                                 WCHAR   * lpStrings,
                                 DWORD   dwDataSize,
                                 LPVOID  lpRawData)
{
    DWORD dwRecSize;
    PEVENTLOGRECORD pRec;
    SYSTEMTIME SysTime;
    WCHAR *str;
    UINT i, pos;
    PBYTE Buffer;

    dwRecSize =
        sizeof(EVENTLOGRECORD) + (lstrlenW(ComputerName) +
                                  lstrlenW(SourceName) + 2) * sizeof(WCHAR);

    if (dwRecSize % 4 != 0)
        dwRecSize += 4 - (dwRecSize % 4);

    dwRecSize += dwSidLength;

    for (i = 0, str = lpStrings; i < wNumStrings; i++)
    {
        dwRecSize += (lstrlenW(str) + 1) * sizeof(WCHAR);
        str += lstrlenW(str) + 1;
    }

    dwRecSize += dwDataSize;
    if (dwRecSize % 4 != 0)
        dwRecSize += 4 - (dwRecSize % 4);

    dwRecSize += 4;

    Buffer = HeapAlloc(MyHeap, HEAP_ZERO_MEMORY, dwRecSize);

    if (!Buffer)
    {
        DPRINT1("Can't allocate heap!\n");
        return NULL;
    }

    pRec = (PEVENTLOGRECORD) Buffer;
    pRec->Length = dwRecSize;
    pRec->Reserved = LOGFILE_SIGNATURE;
    pRec->RecordNumber = dwRecordNumber;

    GetSystemTime(&SysTime);
    SystemTimeToEventTime(&SysTime, &pRec->TimeGenerated);
    SystemTimeToEventTime(&SysTime, &pRec->TimeWritten);

    pRec->EventID = dwEventId;
    pRec->EventType = wType;
    pRec->EventCategory = wCategory;

    pos = sizeof(EVENTLOGRECORD);

    lstrcpyW((WCHAR *) (Buffer + pos), SourceName);
    pos += (lstrlenW(SourceName) + 1) * sizeof(WCHAR);
    lstrcpyW((WCHAR *) (Buffer + pos), ComputerName);
    pos += (lstrlenW(ComputerName) + 1) * sizeof(WCHAR);

    pRec->UserSidOffset = pos;

    if (pos % 4 != 0)
        pos += 4 - (pos % 4);

    if (dwSidLength)
    {
        CopyMemory(Buffer + pos, lpUserSid, dwSidLength);
        pRec->UserSidLength = dwSidLength;
        pRec->UserSidOffset = pos;
        pos += dwSidLength;
    }

    pRec->StringOffset = pos;
    for (i = 0, str = lpStrings; i < wNumStrings; i++)
    {
        lstrcpyW((WCHAR *) (Buffer + pos), str);
        pos += (lstrlenW(str) + 1) * sizeof(WCHAR);
        str += lstrlenW(str) + 1;
    }
    pRec->NumStrings = wNumStrings;

    pRec->DataOffset = pos;
    if (dwDataSize)
    {
        pRec->DataLength = dwDataSize;
        CopyMemory(Buffer + pos, lpRawData, dwDataSize);
        pos += dwDataSize;
    }

    if (pos % 4 != 0)
        pos += 4 - (pos % 4);

    *((PDWORD) (Buffer + pos)) = dwRecSize;

    *lpRecSize = dwRecSize;
    return Buffer;
}
Ejemplo n.º 6
0
/*
* Returns millisecond timing (in seconds) for the current time.
*
* Note: This function should be called once in single-threaded mode in Win32,
*       to get it initialized.
*/
time_d now_secs(void) {

#if THREADAPI == THREADAPI_WINDOWS
    /*
    * Windows FILETIME values are "100-nanosecond intervals since 
    * January 1, 1601 (UTC)" (MSDN). Well, we'd want Unix Epoch as
    * the offset and it seems, so would they:
    *
    * <http://msdn.microsoft.com/en-us/library/ms724928(VS.85).aspx>
    */
    SYSTEMTIME st;
    FILETIME ft;
    ULARGE_INTEGER uli;
    static ULARGE_INTEGER uli_epoch;   // Jan 1st 1970 0:0:0

    if (uli_epoch.HighPart==0) {
        st.wYear= 1970;
        st.wMonth= 1;   // Jan
        st.wDay= 1;
        st.wHour= st.wMinute= st.wSecond= st.wMilliseconds= 0;

        if (!SystemTimeToFileTime( &st, &ft ))
            FAIL( "SystemTimeToFileTime", GetLastError() );

        uli_epoch.LowPart= ft.dwLowDateTime;
        uli_epoch.HighPart= ft.dwHighDateTime;
    }

    GetSystemTime( &st );	// current system date/time in UTC
    if (!SystemTimeToFileTime( &st, &ft ))
        FAIL( "SystemTimeToFileTime", GetLastError() );

    uli.LowPart= ft.dwLowDateTime;
    uli.HighPart= ft.dwHighDateTime;

    /* 'double' has less accuracy than 64-bit int, but if it were to degrade,
     * it would do so gracefully. In practise, the integer accuracy is not
     * of the 100ns class but just 1ms (Windows XP).
     */
# if 1
    // >= 2.0.3 code
    return (double) ((uli.QuadPart - uli_epoch.QuadPart)/10000) / 1000.0;
# elif 0
    // fix from Kriss Daniels, see: 
    // <http://luaforge.net/forum/forum.php?thread_id=22704&forum_id=1781>
    //
    // "seem to be getting negative numbers from the old version, probably number
    // conversion clipping, this fixes it and maintains ms resolution"
    //
    // This was a bad fix, and caused timer test 5 sec timers to disappear.
    // --AKa 25-Jan-2009
    //
    return ((double)((signed)((uli.QuadPart/10000) - (uli_epoch.QuadPart/10000)))) / 1000.0;
# else
    // <= 2.0.2 code
    return (double)(uli.QuadPart - uli_epoch.QuadPart) / 10000000.0;
# endif
#else // THREADAPI == THREADAPI_PTHREAD
    struct timeval tv;
        // {
        //   time_t       tv_sec;   /* seconds since Jan. 1, 1970 */
        //   suseconds_t  tv_usec;  /* and microseconds */
        // };

    int rc= gettimeofday( &tv, NULL /*time zone not used any more (in Linux)*/ );
    assert( rc==0 );

    return (double)(tv.tv_sec*1000000 + tv.tv_usec) / 1000000.0;
#endif // THREADAPI THREADAPI_PTHREAD
}
Ejemplo n.º 7
0
INLINE 
#endif /* PTW32_BUILD_INLINED */
DWORD
ptw32_relmillisecs (const struct timespec * abstime)
{
  const int64_t NANOSEC_PER_MILLISEC = 1000000;
  const int64_t MILLISEC_PER_SEC = 1000;
  DWORD milliseconds;
  int64_t tmpAbsMilliseconds;
  int64_t tmpCurrMilliseconds;
#if defined(NEED_FTIME)
  struct timespec currSysTime;
  FILETIME ft;
  SYSTEMTIME st;
#else /* ! NEED_FTIME */
#if ( defined(_MSC_VER) && _MSC_VER >= 1300 ) /* MSVC7+ */ || \
    ( defined(PTW32_CONFIG_MINGW) && __MSVCRT_VERSION__ >= 0x0601 )
  struct __timeb64 currSysTime;
#else
  struct _timeb currSysTime;
#endif
#endif /* NEED_FTIME */


  /* 
   * Calculate timeout as milliseconds from current system time. 
   */

  /*
   * subtract current system time from abstime in a way that checks
   * that abstime is never in the past, or is never equivalent to the
   * defined INFINITE value (0xFFFFFFFF).
   *
   * Assume all integers are unsigned, i.e. cannot test if less than 0.
   */
  tmpAbsMilliseconds =  (int64_t)abstime->tv_sec * MILLISEC_PER_SEC;
  tmpAbsMilliseconds += ((int64_t)abstime->tv_nsec + (NANOSEC_PER_MILLISEC/2)) / NANOSEC_PER_MILLISEC;

  /* get current system time */

#if defined(NEED_FTIME)

  GetSystemTime(&st);
  SystemTimeToFileTime(&st, &ft);
  /*
   * GetSystemTimeAsFileTime(&ft); would be faster,
   * but it does not exist on WinCE
   */

  ptw32_filetime_to_timespec(&ft, &currSysTime);

  tmpCurrMilliseconds = (int64_t)currSysTime.tv_sec * MILLISEC_PER_SEC;
  tmpCurrMilliseconds += ((int64_t)currSysTime.tv_nsec + (NANOSEC_PER_MILLISEC/2))
			   / NANOSEC_PER_MILLISEC;

#else /* ! NEED_FTIME */

#if defined(_MSC_VER) && _MSC_VER >= 1400  /* MSVC8+ */
  _ftime64_s(&currSysTime);
#elif ( defined(_MSC_VER) && _MSC_VER >= 1300 ) /* MSVC7+ */ || \
      ( defined(PTW32_CONFIG_MINGW) && __MSVCRT_VERSION__ >= 0x0601 )
  _ftime64(&currSysTime);
#else
  _ftime(&currSysTime);
#endif

  tmpCurrMilliseconds = (int64_t) currSysTime.time * MILLISEC_PER_SEC;
  tmpCurrMilliseconds += (int64_t) currSysTime.millitm;

#endif /* NEED_FTIME */

  if (tmpAbsMilliseconds > tmpCurrMilliseconds)
    {
      milliseconds = (DWORD) (tmpAbsMilliseconds - tmpCurrMilliseconds);
      if (milliseconds == INFINITE)
        {
          /* Timeouts must be finite */
          milliseconds--;
        }
    }
  else
    {
      /* The abstime given is in the past */
      milliseconds = 0;
    }

  return milliseconds;
}
Ejemplo n.º 8
0
/*
 *--Full format

            1         2         3         4         5         6         7
  01234567890123456789012345678901234567890123456789012345678901234567890123456789
  Sep  1  1990   - start with ' '
  Sep 11 11:59
  Sep 11 01:59   - start with 0
  Sep 11  1:59   - start with ' '
  Dec 12 1989
  FCv 23 1990

 *--Short format:

            1         2         3         4         5         6         7
  01234567890123456789012345678901234567890123456789012345678901234567890123456789
  f 01:07   - time
  f 01:7    - minutes with one digit
  F 15:43
  f  2002   - only year

 *--Expanded format:

            1         2         3         4         5         6         7
  01234567890123456789012345678901234567890123456789012345678901234567890123456789
 *2005-06-20 14:22
 *2005-07-08 19:21
 *2004-10-14 14:14
 *2004-10-14 14:14
*/
BOOL net_convert_unix_date(LPSTR& datestr, Time_t& decoded)
{
	SYSTEMTIME st;
	GetSystemTime(&st);
	st.wMilliseconds = 0;
	st.wSecond       = 0;
	st.wDayOfWeek    = 0;
	char *bcol = datestr;         /* Column begin */
	char *ecol;                   /* Column end */
	//Expanded format (DDDD-)
	if(NET_IS_DIGIT(bcol[0]) && NET_IS_DIGIT(bcol[1]) && NET_IS_DIGIT(bcol[2]) && NET_IS_DIGIT(bcol[3]) &&
	        bcol[4] == '-')
	{
#define CVT( nm, start, end )              bcol[end] = 0;                       \
	st.nm = atoi(bcol+start);   \
	CHECK( (st.nm == MAX_WORD), FALSE )
		CVT(wYear,   0,  4)
		CVT(wMonth,  5,  7)
		CVT(wDay,    8, 10)
		CVT(wHour,  11, 13)
		CVT(wMinute,14, 16)
#undef CVT
		datestr = bcol + 17;
		return SystemTimeToFileTime(&st, decoded);
	}

	//Month+day or short format
	// (ecol must be set to char after decoded part)
	if(NET_TO_UPPER(bcol[0]) == 'F' &&
	        NET_IS_SPACE(bcol[1]))
	{
		//Short format - ignore month and day
		ecol = bcol + 2;
	}
	else
	{
		//Month
		if(NET_IS_DIGIT(bcol[0]) && NET_IS_DIGIT(bcol[1]) && NET_IS_SPACE(bcol[2]))
			st.wMonth = AtoI(bcol,MAX_WORD);
		else
			st.wMonth = NET_MonthNo(datestr);

		CHECK((st.wMonth == MAX_WORD), FALSE)
		bcol = SkipSpace(SkipNSpace(bcol));
		CHECK((*bcol == 0), FALSE)
		//Day
		ecol = SkipNSpace(bcol);

		if(*ecol != ' ')
			return FALSE;

		*ecol = 0;
		st.wDay = AtoI(bcol,MAX_WORD);
		*ecol = ' ';
		CHECK((st.wDay == MAX_WORD), FALSE)
	}

	//Year or time
	ecol = SkipSpace(ecol);
	bcol = ecol;

	if(bcol[2] != ':' && bcol[1] != ':')
	{
		//Four digits year
		ecol = SkipDigit(bcol);
		CHECK((ecol == bcol), FALSE)
		*ecol = 0;
		st.wYear = AtoI(bcol,MAX_WORD);
		ecol++;
		CHECK((st.wYear == MAX_WORD), FALSE)

		//Only first three digits of year with cut last digit
		if(st.wYear > 190 && st.wYear < 300)
		{
			st.wYear *= 10;
		}

		st.wSecond = 0;
		st.wMinute = 0;
		st.wHour   = 0;
	}
Ejemplo n.º 9
0
void STDCALL GetTimeCounter(int64_t* v)
{
	SYSTEMTIME t;
	GetSystemTime(&t);
	*v = (t.wDay*24+t.wHour)*60*60*1000+(t.wMinute*60+t.wSecond)*1000+t.wMilliseconds;
}
Ejemplo n.º 10
0
void CMediaDatabase::GetStatisticFromDatabase(SallyAPI::GUI::CAppBase* appBase, SallyAPI::GUI::CListViewExt* listView, int type, int advancedType)
{
	listView->Clear();

	std::string mediaDirectory = SallyAPI::System::SallyHelper::GetMediaDirectory(appBase);
	mediaDirectory.append("media.db");

	bool bFileExists = SallyAPI::File::FileHelper::FileExistsAndNotEmpty(mediaDirectory);
	if (!bFileExists)
		return;

	SallyAPI::Database::CDatabaseConnection* dbconn = SallyAPI::Database::CDatabaseConnection::Open(mediaDirectory);

	std::string query;
	switch (type)
	{
	case 0:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE PlayTime != 0 ORDER BY PlayTime DESC LIMIT 200;");
		break;
	case 1:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE PlayTime = 0 ORDER BY Title ASC LIMIT 200;");
		break;
	case 2:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE Rating = 5 ORDER BY Title ASC LIMIT 200;");
		break;
	case 3:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE Rating = 4 ORDER BY Title ASC LIMIT 200;");
		break;
	case 4:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE Rating = 3 ORDER BY Title ASC LIMIT 200;");
		break;
	case 5:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE Rating = 2 ORDER BY Title ASC LIMIT 200;");
		break;
	case 6:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE Rating = 1 ORDER BY Title ASC LIMIT 200;");
		break;
	case 7:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE Rating = 0 ORDER BY Title ASC LIMIT 200;");
		break;
	case 8:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media ORDER BY DBAddDate DESC, Title ASC LIMIT 200;");
		break;
	case 9:
		query.append("SELECT Filename, Type, Artist, Title, Album FROM media WHERE PlayTime > 10 AND ");
		
		SYSTEMTIME dateToConvert;
		SYSTEMTIME currentDate;

		GetSystemTime(&currentDate);

		dateToConvert.wDay = currentDate.wDay;

		dateToConvert.wHour = 0;
		dateToConvert.wMinute = 0;
		dateToConvert.wSecond = 0;

		switch (advancedType)
		{
		case 0:
			if (currentDate.wMonth == 1)
			{
				currentDate.wMonth = 12;
				dateToConvert.wYear = currentDate.wYear - 1;
			}
			else
			{
				dateToConvert.wMonth = currentDate.wMonth - 1;
				dateToConvert.wYear = currentDate.wYear;
			}
			break;
		case 1:
			if (currentDate.wMonth <= 6)
			{
				currentDate.wMonth = 12 - ((currentDate.wMonth - 6) * -1);
				dateToConvert.wYear = currentDate.wYear - 1;
			}
			else
			{
				dateToConvert.wMonth = currentDate.wMonth - 6;
				dateToConvert.wYear = currentDate.wYear;
			}
			break;
		case 2:
			dateToConvert.wMonth = currentDate.wMonth;
			dateToConvert.wYear = currentDate.wYear - 1;
			break;
		case 3:
			dateToConvert.wMonth = currentDate.wMonth;
			dateToConvert.wYear = currentDate.wYear - 2;
			break;
		case 4:
			dateToConvert.wMonth = currentDate.wMonth;
			dateToConvert.wYear = currentDate.wYear - 3;
			break;
		case 5:
			dateToConvert.wMonth = currentDate.wMonth;
			dateToConvert.wYear = currentDate.wYear - 4;
			break;
		case 6:
			dateToConvert.wMonth = currentDate.wMonth;
			dateToConvert.wYear = currentDate.wYear - 5;
			break;
		}
		std::string oderThan = SallyAPI::Date::DateHelper::GetDateString(dateToConvert, false);

		query.append("LastPlayDate < '");
		query.append(oderThan);
		query.append("'");
		query.append(" ORDER BY LastPlayDate ASC LIMIT 200;");
		break;
	}


	dbconn->LockDatabase();
	SallyAPI::Database::CStatement* stmt = dbconn->CreateStatement();

	try
	{
		SallyAPI::Database::CResultSet* rslt = stmt->ExecuteQuery(query.c_str());

		while (rslt->Next())
		{
			std::string sDBFilename = rslt->GetString(1);
			std::string sDBArtist = rslt->GetString(3);
			std::string sDBTitle = rslt->GetString(4);
			std::string sDBAlbum = rslt->GetString(5);

			sDBArtist = SallyAPI::String::StringHelper::ReplaceString(sDBArtist, "#", "'");
			sDBTitle = SallyAPI::String::StringHelper::ReplaceString(sDBTitle, "#", "'");
			sDBFilename = SallyAPI::String::StringHelper::ReplaceString(sDBFilename, "#", "'");
			sDBAlbum = SallyAPI::String::StringHelper::ReplaceString(sDBAlbum, "#", "'");

			std::string firstLine = "";

			if ((sDBTitle.length() != 0) && (sDBArtist.length() != 0))
			{
				firstLine.append(sDBArtist);
				firstLine.append(" - ");
				firstLine.append(sDBTitle);
			}
			else
			{
				firstLine.append(SallyAPI::String::PathHelper::GetFileFromPath(sDBFilename));
			}

			SallyAPI::GUI::CListViewItem listItem(sDBFilename);

			listItem.SetImageId(GUI_THEME_SALLY_ICON_ADD, 0);

			if (rslt->GetInt(2))
				listItem.SetImageId(GUI_THEME_SALLY_ICON_MIMETYPE_VIDEO, 1);
			else
				listItem.SetImageId(GUI_THEME_SALLY_ICON_MIMETYPE_MP3, 1);
			listItem.SetText(firstLine, 1);
			listItem.SetText(sDBAlbum, 2);

			listItem.SetSmallFont(true, 0);
			listItem.SetSmallFont(false, 1);
			listItem.SetSmallFont(true, 2);

			listItem.SetLocalised(SallyAPI::GUI::LISTVIEW_LOCALISATION_FALSE, 1);
			listItem.SetLocalised(SallyAPI::GUI::LISTVIEW_LOCALISATION_FALSE, 2);

			listView->AddItem(listItem);
		}
	}
	catch (SallyAPI::Database::CSQLException* e)
	{
		SallyAPI::System::CLogger* logger = SallyAPI::Core::CGame::GetLogger();
		logger->Error(e->GetMessage());
	}
	dbconn->ReleaseDatabase();

	SallyAPI::Database::CDatabaseConnection::Close(mediaDirectory);
}
Ejemplo n.º 11
0
double CExpression::vexp ( arbore a )
{
	double v;
	SYSTEMTIME tm;
	
	GetSystemTime(&tm);

	if (a->operatie==NULL) {error_code=10;return 0;}
	switch(a->operatie){
	case '+' : return( vexp(a->left)+vexp(a->right) );
	case '-' : return( vexp(a->left)-vexp(a->right) );
	case '*' : return( vexp(a->left)*vexp(a->right) );
	case '%':
		{
			v = vexp(a->right);
			if(v == 0){
				error_code = DIVISION_BY_0;
				return 0;
			}
			return (int)vexp(a->left) % (int)v;
		}
	case '/' : v=vexp(a->right) ;
		if (v==0){
			error_code=DIVISION_BY_0;
			return -vexp(a->left)/0.001;
		}else{
			return(vexp(a->left)/v);
		}
	case 150 : return(sin(vexp(a->left)));
	case 151 : return(cos(vexp(a->left)));
	case 152 : return(exp(vexp(a->left)));
	case 153 : v=vexp(a->left) ;
		if (v<0) {error_code=INVALID_DOMAIN;return 0;}
		else return(sqrt(v));
	case 154 : v=vexp(a->left) ;
		if (v<=0) {error_code=INVALID_DOMAIN;return 0;}
		else return(log(v));
	case 155 : return (tan (vexp(a->left)));
	case 156 : return (1 / tan (vexp(a->left)));
	case 157 : return (asin (vexp(a->left)));
	case 158 : return (acos (vexp(a->left)));
	case 159 : return (atan (vexp(a->left)));
	case 173 : return (fabs (vexp(a->left)));
	case 160 : return tm.wYear;
	case 161 : return tm.wMonth;
	case 162 : return tm.wDay;
	case 163 : return tm.wHour;
	case 164 : return tm.wMinute;
	case 165 : return tm.wSecond;
	case 166 : return max(vexp(a->left),vexp(a->right));
	case 167 : return min(vexp(a->left),vexp(a->right));
	case 168 : return rng_rand(0,RAND_MAX)*vexp(a->left)/RAND_MAX;
	//case '|' : return(fabs(vexp(a->left)));
	case '^' : return(pow(vexp(a->left),vexp(a->right)));
	case '@' : return (a->valoare);
		//logical operations evaluation
	case '<' : return( vexp(a->left) < vexp(a->right) );
	case '>' : return( vexp(a->left) > vexp(a->right) );
	case '!' : return(!vexp(a->right)) ;
	// added by chenj, @2008-5-22
	case '=' : return( vexp(a->left) == vexp(a->right) );
	case '&' : return (int)(vexp(a->left)) & (int)(vexp(a->right));
	case '|' : return (int)(vexp(a->left)) | (int)(vexp(a->right));
		
	case 169:
		{
			RTK_TIME t;
			rtk_time_mark(&t);
			return (double)(__int64)t.Data / 1e7;
		}
		
	case 170:
		{
			/* last update time */
			PRTK_TAG tte;
			__r8 retval = 0;
			
			tte  = (PRTK_TAG)a->left->pvObj;
			if(!tte){
				error_code=UNDEFINED_VARIABLE;
				retval = 0;
			}else{ 
				if(!(tte->d.Value.Flags & TF_Valid)){
					error_code=UNDEFINED_VARIABLE;
					retval = 0;
				}else{
					PRTK_TIME pTime = (PRTK_TIME)&tte->d.BinaryAddress[8];
					retval = (double)(__int64)pTime->Data / 1e7;
					rtk_time_mark(pTime);
				}
			}

			return retval;
		}

	case 171  : 
		{
			// a database tag
			PRTK_TAG tte;
			__r8 retval = 0;
			tte = (PRTK_TAG)a->pvObj;
			if(!tte){
				error_code=UNDEFINED_VARIABLE;
				retval = 0;
			}else{ 
				if(!(tte->d.Value.Flags & TF_Valid)){
					error_code=UNDEFINED_VARIABLE;
					retval = 0;
				}else{
					pmc_value_t dblVal;
					set_value_type(dblVal.Flags, dt_real8);
					pmc_type_cast(&tte->d.Value, &dblVal);
					retval = dblVal.Value.dbl;
				}
			}
			return retval;
		}
	
	case 172:
		{
			/* span time */
			PRTK_TAG tte;
			RTK_TIME now;
			__r8 retval = 0;
			
			tte  = (PRTK_TAG)a->left->pvObj;
			if(!tte){
				error_code=UNDEFINED_VARIABLE;
				retval = 0;
			}else{ 
				if(!(tte->d.Value.Flags & TF_Valid)){
					error_code=UNDEFINED_VARIABLE;
					retval = 0;
				}else{
					PRTK_TIME pTime = (PRTK_TIME)&(tte->d.BinaryAddress[8]);
					rtk_time_mark(&now);
					if(pTime->Data != 0){
						/* yes, the field is previouly stored with a resonable value,
						thus valid for a sub-operation to get a duration time */
						retval = rtk_time_diff(&now, pTime);
					}else{
						/* this might be the first time that a time-span was requested
						for this tag
						*/
						retval = 0;
					}
					
					*pTime = now;
				}
			}

			return retval;
		}

	}

	return 0;
}
Ejemplo n.º 12
0
/*
** Read the options specified in the ini file.
**
*/
void CMeasureTime::ReadOptions(CConfigParser& parser, const WCHAR* section)
{
	CMeasure::ReadOptions(parser, section);

	m_Format = parser.ReadString(section, L"Format", L"");

	m_TimeStamp = parser.ReadFloat(section, L"TimeStamp", -1);

	if (m_TimeStamp < 0.0)
	{
		const WCHAR* timezone = parser.ReadString(section, L"TimeZone", L"local").c_str();
		if (_wcsicmp(L"local", timezone) == 0)
		{
			SYSTEMTIME sysLocalTime, sysUTCTime;
			GetLocalTime(&sysLocalTime);
			GetSystemTime(&sysUTCTime);

			FILETIME ftLocalTime, ftUTCTime;
			SystemTimeToFileTime(&sysLocalTime, &ftLocalTime);
			SystemTimeToFileTime(&sysUTCTime, &ftUTCTime);

			LARGE_INTEGER largeInt1, largeInt2;
			largeInt1.HighPart = ftLocalTime.dwHighDateTime;
			largeInt1.LowPart = ftLocalTime.dwLowDateTime;
			largeInt2.HighPart = ftUTCTime.dwHighDateTime;
			largeInt2.LowPart = ftUTCTime.dwLowDateTime;

			m_DeltaTime.QuadPart = largeInt1.QuadPart - largeInt2.QuadPart;
		}
		else
		{
			double zone = parser.ParseDouble(timezone, 0.0);
			bool dst = 1 == parser.ReadInt(section, L"DaylightSavingTime", 1);

			struct tm* today;
			time_t now;
			time(&now);
			today = localtime(&now);

			if (dst && today->tm_isdst)
			{
				// Add DST
				TIME_ZONE_INFORMATION tzi;
				GetTimeZoneInformation(&tzi);

				m_DeltaTime.QuadPart = (LONGLONG)((zone * 3600) - tzi.DaylightBias * 60) * 10000000;
			}
			else
			{
				m_DeltaTime.QuadPart = (LONGLONG)(zone * 3600) * 10000000;
			}
		}
	}
	else
	{
		m_DeltaTime.QuadPart = 0;
	}

	if (!m_Initialized)
	{
		// Initialize m_Time to avoid causing EINVAL in TimeToString() until calling UpdateValue()
		FillCurrentTime();
	}
}
Ejemplo n.º 13
0
static int SecsSinceSystemTime(SYSTEMTIME& time)
{
    SYSTEMTIME currTime;
    GetSystemTime(&currTime);
    return SystemTimeDiffInSecs(currTime, time);
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
  CURL    *curl;
  conf_t  conf[1];
  int     OptionIndex;
  struct  tm *lt;
  struct  tm *gmt;
  time_t  tt;
  time_t  tt_local;
  time_t  tt_gmt;
  double  tzonediffFloat;
  int     tzonediffWord;
  char    timeBuf[61];
  char    tzoneBuf[16];
  int     RetValue;

  OptionIndex     = 0;
  ShowAllHeader   = 0;    /* Do not show HTTP Header */
  AutoSyncTime    = 0;    /* Do not synchronise computer clock */
  RetValue        = 0;    /* Successful Exit */
  conf_init(conf);

  if (argc > 1) {
    while (OptionIndex < argc) {
      if (strncmp(argv[OptionIndex], "--server=", 9) == 0)
        snprintf(conf->timeserver, MAX_STRING, "%s", &argv[OptionIndex][9]);

      if (strcmp(argv[OptionIndex], "--showall") == 0)
        ShowAllHeader = 1;

      if (strcmp(argv[OptionIndex], "--synctime") == 0)
        AutoSyncTime = 1;

      if (strncmp(argv[OptionIndex], "--proxy-user="******"%s", &argv[OptionIndex][13]);

      if (strncmp(argv[OptionIndex], "--proxy=", 8) == 0)
        snprintf(conf->http_proxy, MAX_STRING, "%s", &argv[OptionIndex][8]);

      if ((strcmp(argv[OptionIndex], "--help") == 0) ||
          (strcmp(argv[OptionIndex], "/?") == 0)) {
        showUsage();
        return 0;
      }
      OptionIndex++;
    }
  }

  if (*conf->timeserver == 0)     /* Use default server for time information */
    snprintf(conf->timeserver, MAX_STRING, "%s", DefaultTimeServer[0]);

  /* Init CURL before usage */
  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();
  if (curl) {
    SyncTime_CURL_Init(curl, conf->http_proxy, conf->proxy_user);

    /* Calculating time diff between GMT and localtime */
    tt       = time(0);
    lt       = localtime(&tt);
    tt_local = mktime(lt);
    gmt      = gmtime(&tt);
    tt_gmt   = mktime(gmt);
    tzonediffFloat = difftime(tt_local, tt_gmt);
    tzonediffWord  = (int)(tzonediffFloat/3600.0);

    if ((double)(tzonediffWord * 3600) == tzonediffFloat)
      snprintf(tzoneBuf, 15, "%+03d'00'", tzonediffWord);
    else
      snprintf(tzoneBuf, 15, "%+03d'30'", tzonediffWord);

    /* Get current system time and local time */
    GetSystemTime(&SYSTime);
    GetLocalTime(&LOCALTime);
    snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
             DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
             MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
             LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
             LOCALTime.wMilliseconds);

    fprintf(stderr, "Fetch: %s\n\n", conf->timeserver);
    fprintf(stderr, "Before HTTP. Date: %s%s\n\n", timeBuf, tzoneBuf);

    /* HTTP HEAD command to the Webserver */
    SyncTime_CURL_Fetch(curl, conf->timeserver, "index.htm",
                        HTTP_COMMAND_HEAD);

    GetLocalTime(&LOCALTime);
    snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
             DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
             MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
             LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
             LOCALTime.wMilliseconds);
    fprintf(stderr, "\nAfter  HTTP. Date: %s%s\n", timeBuf, tzoneBuf);

    if (AutoSyncTime == 3) {
      /* Synchronising computer clock */
      if (!SetSystemTime(&SYSTime)) {  /* Set system time */
        fprintf(stderr, "ERROR: Unable to set system time.\n");
        RetValue = 1;
      }
      else {
        /* Successfully re-adjusted computer clock */
        GetLocalTime(&LOCALTime);
        snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
                 DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
                 MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
                 LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
                 LOCALTime.wMilliseconds);
        fprintf(stderr, "\nNew System's Date: %s%s\n", timeBuf, tzoneBuf);
      }
    }

    /* Cleanup before exit */
    conf_init(conf);
    curl_easy_cleanup(curl);
  }
  return RetValue;
}
Ejemplo n.º 15
0
DWORD
HTENTRY
DbgElapseTime(
    DBG_TIMEx   OldTime
    )
{
#ifndef UMODE

    return(0);

#else

#if defined(_OS2_) || defined(_OS_20_) || defined(_DOS_)

    return((DWORD)clock() - OldTime);

#else

#if 1

    return(GetTickCount() - OldTime.dw);

#else

    SYSTEMTIME  SysTime;
    DBG_TIMEx   CurTime;
    DWORD       ElapseTime;

    GetSystemTime(&SysTime);

    CurTime.t.Milli = (SHORT)SysTime.wMilliseconds;
    CurTime.t.Sec   = (BYTE)SysTime.wSecond;
    CurTime.t.Min   = (BYTE)SysTime.wMinute;

    if ((CurTime.t.Milli -= OldTime.t.Milli) < (SHORT)0) {

        CurTime.t.Milli += 1000;
        ++OldTime.t.Sec;
    }

    ElapseTime = (DWORD)CurTime.t.Milli;

    if (CurTime.t.Sec < OldTime.t.Sec) {

        CurTime.t.Sec += 60;
        ++OldTime.t.Min;
    }

    if (CurTime.t.Sec -= OldTime.t.Sec) {

        ElapseTime += (DWORD)CurTime.t.Sec * (DWORD)1000;
    }

    if (CurTime.t.Min < OldTime.t.Min) {

        CurTime.t.Min += 60;
        ++OldTime.t.Min;
    }

    if (CurTime.t.Min -= OldTime.t.Min) {

        ElapseTime += (DWORD)CurTime.t.Min * (DWORD)60000;
    }

    return(ElapseTime);

#endif
#endif
#endif
}
Ejemplo n.º 16
0
/* Function 28 */
NET_API_STATUS
__stdcall
NetrRemoteTOD(
    SRVSVC_HANDLE ServerName,
    LPTIME_OF_DAY_INFO *BufferPtr)
{
    SYSTEMTIME SystemTime;
    LARGE_INTEGER Time;
    TIME_ZONE_INFORMATION TimeZoneInfo;
    DWORD TimeZoneId;
    LPTIME_OF_DAY_INFO lpTod;

    TRACE("NetrRemoteTOD(%p %p)\n", ServerName, BufferPtr);

    *BufferPtr = midl_user_allocate(sizeof(TIME_OF_DAY_INFO));
    if (*BufferPtr == NULL)
        return ERROR_NOT_ENOUGH_MEMORY;

    lpTod = *BufferPtr;

    /* Set the seconds since 1970 */
    NtQuerySystemTime(&Time);
    RtlTimeToSecondsSince1970(&Time,
                              &lpTod->tod_elapsedt);

    /* Set the tick count */
    lpTod->tod_msecs = GetTickCount();

    /* Set the timezone */
    TimeZoneId = GetTimeZoneInformation(&TimeZoneInfo);

    switch (TimeZoneId)
    {
        case TIME_ZONE_ID_UNKNOWN:
            lpTod->tod_timezone = TimeZoneInfo.Bias;
            break;

        case TIME_ZONE_ID_STANDARD:
            lpTod->tod_timezone = TimeZoneInfo.Bias + TimeZoneInfo.StandardBias;
            break;

        case TIME_ZONE_ID_DAYLIGHT:
            lpTod->tod_timezone = TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias;
            break;

        default:
            lpTod->tod_timezone = 0;
    }

    /* Set the ??? */
    lpTod->tod_tinterval = 310;

    /* Set the date and time */
    GetSystemTime(&SystemTime);
    lpTod->tod_hours = SystemTime.wHour;
    lpTod->tod_mins = SystemTime.wMinute;
    lpTod->tod_secs = SystemTime.wSecond;
    lpTod->tod_hunds = SystemTime.wMilliseconds / 10;
    lpTod->tod_day = SystemTime.wDay;
    lpTod->tod_month = SystemTime.wMonth;
    lpTod->tod_year = SystemTime.wYear;
    lpTod->tod_weekday = SystemTime.wDayOfWeek;

    return NERR_Success;
}
Ejemplo n.º 17
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);
}
Ejemplo n.º 18
0
unsigned int getLocalTime() {
    //watchout for 23:59:59.999 -> 0:0:0.000
    SYSTEMTIME now;
    GetSystemTime(&now);
    return(((now.wHour * 60 + now.wMinute) * 60 + now.wSecond) * 1000 + now.wMilliseconds);
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
	int Index = 0;
	int Arg = 1;
	char *VirtualCard = NULL;
	BCAS::Manager::Abstract *Card;

	argc--;
	while (argc > 0) {
		if (strcmp(argv[Arg], "-virtual") == 0) {
			if (argc == 1) {
				printf("Missing file parameter.\n");
				return 1;
			}	
			VirtualCard = _strdup(argv[++Arg]);
			argc--;
		} else if (strcmp(argv[Arg], "-reader") == 0) {
			if (argc == 1) {
				printf("Missing file parameter.\n");
				return 1;
			}
			Index = atoi(argv[++Arg]);
			argc--;
		} else if (strcmp(argv[Arg], "-list") == 0) {
			Index = -1;
		} else {
			printf("Invalid parameter: %s\n", argv[Arg]);
			return 1;
		}
		Arg++;
		argc--;
	}

	if (VirtualCard == NULL) {
		SCARDCONTEXT Ctx;
		LONG Result;
		char *Reader = NULL;

		Result = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &Ctx);

		if (Result != SCARD_S_SUCCESS) {
			printf("Failed to establish context, error: %08x\n", Result);
			return 1;
		}

		DWORD Count = SCARD_AUTOALLOCATE;
		LPTSTR Readers = NULL;

		Result = SCardListReaders(Ctx, NULL, (LPTSTR)&Readers, &Count);
		if (Result != SCARD_S_SUCCESS) {
			if (Result == SCARD_E_NO_READERS_AVAILABLE)
				printf("No card readers available.\n");
			else
				printf("Failed to list card readers, error: %08x\n", Result);
			SCardReleaseContext(Ctx);
			return 1;
		}

		LPTSTR R = Readers;
		Count = 0;
		while (*R != 0) {
			if (Index == Count) {
				Reader = _strdup(R);
				break;
			} else if (Index == -1) {
				printf("Reader %d: %s\n", Count, R);
			}
			R += strlen(R) + 1;
			Count++;
		}
		SCardFreeMemory(Ctx, Readers);

		if (Reader == NULL) {
			if (Index != -1)
				printf("Cannot find a reader at index %d\n", Index);
			SCardReleaseContext(Ctx);
			return 1;
		}
		BCAS::Manager::Card *RealCard = new BCAS::Manager::Card;
		RealCard->SetReader(Reader);
		Card = RealCard;
	} else {
		BCAS::Manager::Virtual *Dump = new BCAS::Manager::Virtual;
		Dump->SetReader(VirtualCard);
		Card = Dump;
	}

	BCAS::Keys::RegisterAll();

	Card->Init();
	BCAS::Manager::Ops *Ops = new BCAS::Manager::Ops;
	Ops->SetCard(Card);

	BCAS::Manager::Manager *Mgr = new BCAS::Manager::Manager(Ops);

	bool Quit = false;
	u16 Date;
	SYSTEMTIME Time;

	GetSystemTime(&Time);
	Date = ConvertDateToMJD(Time.wYear, Time.wMonth & 0xff, Time.wDay & 0xff) + 7;

	while (!Quit) {
		bool NewCard = false;
		bool HasCard;
		u16 Expiry;

		HasCard = Card->WaitForEvent(NewCard);
		if (NewCard == true) {
			Mgr->PrintCardInformation(CardType);
			if (CardType == kType_INVALID)
				break;
			PrintMenu();
			continue;
		}
		if (HasCard == false) {
			if (_kbhit()) {
				int Selection = _getch();
				if (Selection == 27) {
					break;
				}
				if (Selection == 0)
					_getch();
			}
			continue;
		}

		int Key = _getch();
		switch (Key) {
		case 27:
				Quit = true;
				break;

		case 0:
			Key = _getch();
			switch (Key) {
			case 59:
				Mgr->DumpMode();
				break;
			case 60:
				Mgr->PrintEntitlements();
				break;
			case 61:
				Mgr->PrintEmail();
				break;
			case 62:
				DateState = (DateState + 1) % 7;
				switch (DateState) {
				case 0:
					Expiry = 7;
					break;
				case 1:
					Expiry = 15;
					break;
				case 2:
					Expiry = 30;
					break;
				case 3:
					Expiry = 90;
					break;
				case 4:
					Expiry = 180;
					break;
				case 5:
					Expiry = 365 * 2;
					break;
				case 6:
					break;
				}
				if (DateState != 6) {
					GetSystemTime(&Time);
					Date = ConvertDateToMJD(Time.wYear, Time.wMonth & 0xff, Time.wDay & 0xff) + Expiry;
				} else {
					Date = 0xffff;
				}
				break;

			default:
				printf("%d\n", Key);
				break;
			}
			break;

		// UpdateTiers
		case 49:
			Mgr->AddEntitlement(BCAS::Keys::KEYSET_WOWOW, Date);
			break;
		case 50:
			Mgr->AddEntitlement(BCAS::Keys::KEYSET_STARCHANNELHD, Date);
			break;
		case 51:
			Mgr->AddEntitlement(BCAS::Keys::KEYSET_E2_110CS, Date);
			break;
		case 52:
			Mgr->AddEntitlement(BCAS::Keys::KEYSET_SAFETYNET, Date);
			break;
		case 53:
			Mgr->AddEntitlement(BCAS::Keys::KEYSET_NHK, Date);
			break;

		// InvalidateTiers
		case 113:
			Mgr->InvalidateEntitlement(BCAS::Keys::KEYSET_WOWOW);
			break;
		case 119:
			Mgr->InvalidateEntitlement(BCAS::Keys::KEYSET_STARCHANNELHD);
			break;
		case 101:
			Mgr->InvalidateEntitlement(BCAS::Keys::KEYSET_E2_110CS);
			break;
		case 114:
			Mgr->InvalidateEntitlement(BCAS::Keys::KEYSET_SAFETYNET);
			break;
		case 116:
			Mgr->InvalidateEntitlement(BCAS::Keys::KEYSET_NHK);
			break;

		// DeleteEmail
		case 97:
			Mgr->DeleteEmail(BCAS::Keys::KEYSET_WOWOW);
			break;
		case 115:
			Mgr->DeleteEmail(BCAS::Keys::KEYSET_STARCHANNELHD);
			break;
		case 100:
			Mgr->DeleteEmail(BCAS::Keys::KEYSET_E2_110CS);
			break;
		case 102:
			Mgr->DeleteEmail(BCAS::Keys::KEYSET_SAFETYNET);
			break;
		case 103:
			Mgr->DeleteEmail(BCAS::Keys::KEYSET_NHK);
			break;
		case 104:
			Mgr->DeleteEmail(BCAS::Keys::KEYSET_EMAIL);
			break;

		// ActivateTrial
		case 122:
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_WOWOW, false, Date);
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_WOWOW, true, Date);
			break;
		case 120:
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_STARCHANNELHD, false, Date);
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_STARCHANNELHD, true, Date);
			break;
		case 99:
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_E2_110CS, false, Date);
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_E2_110CS, true, Date);
			break;
		case 118:
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_SAFETYNET, false, Date);
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_SAFETYNET, true, Date);
			break;
		case 98:
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_NHK, false, Date);
			Mgr->ActivateTrial(BCAS::Keys::KEYSET_NHK, true, Date);
			break;

		default:
			printf("%d\n", Key);
			break;
		}

		if (!Quit)
			PrintMenu();
	}

	return 0;
}
Ejemplo n.º 20
0
//-----------------------------------------------------------------------------
// Purpose: Searches for GameStartup*.mp3 files in the sound/ui folder and plays one
//-----------------------------------------------------------------------------
void CGameUI::PlayGameStartupSound()
{
#if defined( LEFT4DEAD )
	// L4D not using this path, L4D UI now handling with background menu movies
	return;
#endif

	if ( IsX360() )
		return;

	if ( CommandLine()->FindParm( "-nostartupsound" ) )
		return;

	FileFindHandle_t fh;

	CUtlVector<char *> fileNames;

	char path[ 512 ];
	Q_snprintf( path, sizeof( path ), "sound/ui/gamestartup*.mp3" );
	Q_FixSlashes( path );

	char const *fn = g_pFullFileSystem->FindFirstEx( path, "MOD", &fh );
	if ( fn )
	{
		do
		{
			char ext[ 10 ];
			Q_ExtractFileExtension( fn, ext, sizeof( ext ) );

			if ( !Q_stricmp( ext, "mp3" ) )
			{
				char temp[ 512 ];
				Q_snprintf( temp, sizeof( temp ), "ui/%s", fn );

				char *found = new char[ strlen( temp ) + 1 ];
				Q_strncpy( found, temp, strlen( temp ) + 1 );

				Q_FixSlashes( found );
				fileNames.AddToTail( found );
			}
	
			fn = g_pFullFileSystem->FindNext( fh );

		} while ( fn );

		g_pFullFileSystem->FindClose( fh );
	}

	// did we find any?
	if ( fileNames.Count() > 0 )
	{
		SYSTEMTIME SystemTime;
		GetSystemTime( &SystemTime );
		int index = SystemTime.wMilliseconds % fileNames.Count();

		if ( fileNames.IsValidIndex( index ) && fileNames[index] )
		{
			char found[ 512 ];

			// escape chars "*#" make it stream, and be affected by snd_musicvolume
			Q_snprintf( found, sizeof( found ), "play *#%s", fileNames[index] );

			engine->ClientCmd_Unrestricted( found );
		}

		fileNames.PurgeAndDeleteElements();
	}
}
Ejemplo n.º 21
0
bool ErrorReport::GetMiscCrashInfo() {
	
	// Get crash time
	m_CrashDateTime = QDateTime::currentDateTime();
	
	m_ProcessArchitecture = ARX_ARCH_NAME;
	
	m_OSName = QString::fromUtf8(platform::getOSName().c_str());
	m_OSArchitecture = QString::fromUtf8(platform::getOSArchitecture().c_str());
	m_OSDistribution = QString::fromUtf8(platform::getOSDistribution().c_str());
	
#if ARX_PLATFORM == ARX_PLATFORM_WIN32
	
	// Open parent process handle
	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, m_pCrashInfo->processId);
	if(hProcess != NULL)
	{
		// Get memory usage info
		PROCESS_MEMORY_COUNTERS meminfo;
		BOOL bGetMemInfo = GetProcessMemoryInfo(hProcess, &meminfo, sizeof(PROCESS_MEMORY_COUNTERS));
		if(bGetMemInfo)
			m_ProcessMemoryUsage = meminfo.WorkingSetSize;

		// Determine the period of time the process is working.
		FILETIME CreationTime, ExitTime, KernelTime, UserTime;
		BOOL bGetTimes = GetProcessTimes(hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime);
		if(bGetTimes)
		{
			SYSTEMTIME AppStartTime;
			FileTimeToSystemTime(&CreationTime, &AppStartTime);

			SYSTEMTIME CurTime;
			GetSystemTime(&CurTime);
			ULONG64 uCurTime = ConvertSystemTimeToULONG64(CurTime);
			ULONG64 uStartTime = ConvertSystemTimeToULONG64(AppStartTime);

			// Check that the application works for at least one minute before crash.
			// This might help to avoid cyclic error report generation when the applciation
			// crashes on startup.
			m_RunningTimeSec = (double)(uCurTime-uStartTime)*10E-08;
		}
	}
	else
	{
		m_DetailedError = QString("Unable to obtain an handle to the crashed process (Error %1).").arg(QString::number(GetLastError()));
		return false;
	}
	
	if(m_pCrashInfo->exceptionCode != 0)
	{
		QString exceptionStr = GetExceptionString(m_pCrashInfo->exceptionCode).c_str();
		if(!exceptionStr.isEmpty())
		{
			m_ReportDescription += "\nException code:\n  ";
			m_ReportDescription += exceptionStr;
			m_ReportDescription += "\n";
		}
	}

	std::string callStack, callstackTop;
	u32 callstackCrc;

	bool bCallstack = GetCallStackInfo(hProcess, m_pCrashInfo->threadHandle, &m_pCrashInfo->contextRecord, callStack, callstackTop, callstackCrc);
	if(!bCallstack) 
	{
		m_DetailedError = "A failure occured when obtaining information regarding the callstack.";
		return false;
	}
	
	m_ReportUniqueID = QString("[%1]").arg(QString::number(callstackCrc, 16).toUpper());
	
	m_ReportDescription = m_pCrashInfo->detailedCrashInfo;
	m_ReportDescription += "\nCallstack:\n";
	m_ReportDescription += callStack.c_str();
	m_ReportTitle = QString("%1 %2").arg(m_ReportUniqueID, callstackTop.c_str());

	QString registers(GetRegisters(&m_pCrashInfo->contextRecord).c_str());
	if(!registers.isEmpty())
	{
		m_ReportDescription += "\nRegisters:\n";
		m_ReportDescription += registers;
	}
	
	CloseHandle(hProcess);
	
	m_ReportDescriptionText = m_ReportDescription;
	
#else // ARX_PLATFORM != ARX_PLATFORM_WIN32
	
	getResourceUsage(m_pCrashInfo->processId, m_ProcessMemoryUsage, m_RunningTimeSec);
	
#endif

	return true;
}
Ejemplo n.º 22
0
/* Crashdumps handling */
static void check_crashdump(void)
{
    wchar_t mv_crashdump_path[MAX_PATH];
    wcscpy (mv_crashdump_path, crashdump_path);
    wcscat (mv_crashdump_path, L".mv");

    if (_wrename (crashdump_path, mv_crashdump_path))
        return;

    FILE * fd = _wfopen ( mv_crashdump_path, L"r, ccs=UTF-8" );
    if( !fd )
        return;
    fclose( fd );

    int answer = MessageBox( NULL, L"Ooops: VLC media player just crashed.\n" \
    "Would you like to send a bug report to the developers team?",
    L"VLC crash reporting", MB_YESNO);

    if(answer == IDYES)
    {
        HINTERNET Hint = InternetOpen(L"VLC Crash Reporter",
                INTERNET_OPEN_TYPE_PRECONFIG, NULL,NULL,0);
        if(Hint)
        {
            HINTERNET ftp = InternetConnect(Hint, L"crash.videolan.org",
                        INTERNET_DEFAULT_FTP_PORT, NULL, NULL,
                        INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
            if(ftp)
            {
                SYSTEMTIME now;
                GetSystemTime(&now);
                wchar_t remote_file[MAX_PATH];
                _snwprintf(remote_file, MAX_PATH,
                        L"/crashes-win32/%04d%02d%02d%02d%02d%02d",
                        now.wYear, now.wMonth, now.wDay, now.wHour,
                        now.wMinute, now.wSecond );

                if( FtpPutFile( ftp, mv_crashdump_path, remote_file,
                            FTP_TRANSFER_TYPE_BINARY, 0) )
                    MessageBox( NULL, L"Report sent correctly. Thanks a lot " \
                                "for the help.", L"Report sent", MB_OK);
                else
                    MessageBox( NULL, L"There was an error while "\
                                "transferring the data to the FTP server.\n"\
                                "Thanks a lot for the help.",
                                L"Report sending failed", MB_OK);
                InternetCloseHandle(ftp);
            }
            else
            {
                MessageBox( NULL, L"There was an error while connecting to " \
                                "the FTP server. "\
                                "Thanks a lot for the help.",
                                L"Report sending failed", MB_OK);
                fprintf(stderr,"Can't connect to FTP server 0x%08lu\n",
                        (unsigned long)GetLastError());
            }
            InternetCloseHandle(Hint);
        }
        else
        {
              MessageBox( NULL, L"There was an error while connecting to the Internet.\n"\
                                "Thanks a lot for the help anyway.",
                                L"Report sending failed", MB_OK);
        }
    }

    _wremove(mv_crashdump_path);
}
Ejemplo n.º 23
0
int
sem_timedwait (sem_t * sem, const struct timespec *abstime)
     /*
      * ------------------------------------------------------
      * DOCPUBLIC
      *      This function waits on a semaphore possibly until
      *      'abstime' time.
      *
      * PARAMETERS
      *      sem
      *              pointer to an instance of sem_t
      *
      *      abstime
      *              pointer to an instance of struct timespec
      *
      * DESCRIPTION
      *      This function waits on a semaphore. If the
      *      semaphore value is greater than zero, it decreases
      *      its value by one. If the semaphore value is zero, then
      *      the calling thread (or process) is blocked until it can
      *      successfully decrease the value or until interrupted by
      *      a signal.
      *
      *      If 'abstime' is a NULL pointer then this function will
      *      block until it can successfully decrease the value or
      *      until interrupted by a signal.
      *
      * RESULTS
      *              0               successfully decreased semaphore,
      *              -1              failed, error in errno
      * ERRNO
      *              EINVAL          'sem' is not a valid semaphore,
      *              ENOSYS          semaphores are not supported,
      *              EINTR           the function was interrupted by a signal,
      *              EDEADLK         a deadlock condition was detected.
      *              ETIMEDOUT       abstime elapsed before success.
      *
      * ------------------------------------------------------
      */
{
  int result = 0;

#ifdef NEED_FTIME

  struct timespec currSysTime;

#else /* NEED_FTIME */

  struct _timeb currSysTime;

#endif /* NEED_FTIME */

  const DWORD NANOSEC_PER_MILLISEC = 1000000;
  const DWORD MILLISEC_PER_SEC = 1000;
  DWORD milliseconds;
  DWORD tmpAbsMilliseconds;
  DWORD tmpCurrMilliseconds;

  if (sem == NULL)
    {
      result = EINVAL;
    }
  else
    {
      if (abstime == NULL)
	{
	  milliseconds = INFINITE;
	}
      else
	{
	  /* 
	   * Calculate timeout as milliseconds from current system time. 
	   */

	  /*
	   * subtract current system time from abstime in a way that checks
	   * that abstime is never in the past, or is never equivalent to the
	   * defined INFINITE value (0xFFFFFFFF).
	   *
	   * Assume all integers are unsigned, i.e. cannot test if less than 0.
	   */
	  tmpAbsMilliseconds =  abstime->tv_sec * MILLISEC_PER_SEC;
	  tmpAbsMilliseconds += (abstime->tv_nsec + (NANOSEC_PER_MILLISEC/2)) / NANOSEC_PER_MILLISEC;

	  /* get current system time */

#ifdef NEED_FTIME

	  {
	    FILETIME ft;
	    SYSTEMTIME st;

	    GetSystemTime(&st);
	    SystemTimeToFileTime(&st, &ft);
	    /*
	     * GetSystemTimeAsFileTime(&ft); would be faster,
	     * but it does not exist on WinCE
	     */

	    ptw32_filetime_to_timespec(&ft, &currSysTime);
	  }

	  tmpCurrMilliseconds = currSysTime.tv_sec * MILLISEC_PER_SEC;
	  tmpCurrMilliseconds += (currSysTime.tv_nsec + (NANOSEC_PER_MILLISEC/2)) / NANOSEC_PER_MILLISEC;

#else /* ! NEED_FTIME */

	  _ftime(&currSysTime);

	  tmpCurrMilliseconds = (DWORD) currSysTime.time * MILLISEC_PER_SEC;
	  tmpCurrMilliseconds += (DWORD) currSysTime.millitm;

#endif /* NEED_FTIME */

	  if (tmpAbsMilliseconds > tmpCurrMilliseconds)
	    {
	      milliseconds = tmpAbsMilliseconds - tmpCurrMilliseconds;
	      if (milliseconds == INFINITE)
		{
		  /* Timeouts must be finite */
		  milliseconds--;
		}
	    }
	  else
	    {
	      /* The abstime given is in the past */
	      milliseconds = 0;
	    }
	}

#ifdef NEED_SEM

      result = (pthreadCancelableTimedWait ((*sem)->event, milliseconds));

#else /* NEED_SEM */

      result = (pthreadCancelableTimedWait ((*sem)->sem, milliseconds));

#endif

    }

  if (result != 0)
    {

      errno = result;
      return -1;

    }

#ifdef NEED_SEM

  ptw32_decrease_semaphore (sem);

#endif /* NEED_SEM */

  return 0;

}				/* sem_timedwait */
Ejemplo n.º 24
0
char *
win32_ls_file(const char *name, LPWIN32_FIND_DATA file, int remote, int si_units)
{
	int ulen, glen, sz = 0;
	//struct tm *ltime = localtime(&st->st_mtime);
	char *user, *group;
	char buf[1024], mode[11+1], tbuf[12+1], ubuf[11+1], gbuf[11+1];
	char sbuf[FMT_SCALED_STRSIZE];
	SYSTEMTIME now;
	SYSTEMTIME ftime;
	
	time_t mtime = filetime_to_time_t( file->ftLastWriteTime );
	BOOL time_conv_ok = FileTimeToSystemTime( &file->ftLastWriteTime, &ftime);
	struct tm *ltime = localtime( &mtime );
	
    if (!time_conv_ok) {
		error("Failed to convert file time to localtime");
	}
	
	strmode(0644, mode);
	if (!remote) {
		user = user_from_uid(0, 0);
	} else {
		snprintf(ubuf, sizeof ubuf, "%u", 0);
		user = ubuf;
	}
	
	if (!remote) {
		group = group_from_gid(0, 0);
	} else {
		snprintf(gbuf, sizeof gbuf, "%u", 0);
		group = gbuf;
	}
	
	if (time_conv_ok) {
		//now = time(NULL);
		GetSystemTime(&now);
		
		if ( (time_diff(now, ftime) / 10000000ULL) < (365*24*60*60) ) {
		//if (now - (365*24*60*60)/2 < st->st_mtime &&
		  //  now >= st->st_mtime)
			sz = strftime(tbuf, sizeof tbuf, "%b %e %H:%M", ltime);
		} else {
			sz = strftime(tbuf, sizeof tbuf, "%b %e  %Y", ltime);
		}
	}
	if (sz == 0)
		tbuf[0] = '\0';
	ulen = MAX(strlen(user), 8);
	glen = MAX(strlen(group), 8);
	long long size = (file->nFileSizeHigh * (MAXDWORD+1)) + file->nFileSizeLow;
		
	if (si_units) {
		fmt_scaled(size, sbuf);
		snprintf(buf, sizeof buf, "%s %3u %-*s %-*s %8s %s %s", mode,
		    1 /*nlink -- FIXME */, ulen, user, glen, group,
		    sbuf, tbuf, name);
	} else {
		snprintf(buf, sizeof buf, "%s %3u %-*s %-*s %8llu %s %s", mode,
		    1 /*nlink -- FIXME */, ulen, user, glen, group,
		    size, tbuf, name);
	}
	return xstrdup(buf);
}
Ejemplo n.º 25
0
BOOL LogfWriteData(PLOGFILE LogFile, DWORD BufSize, PBYTE Buffer)
{
    DWORD dwWritten;
    DWORD dwRead;
    SYSTEMTIME st;
    EVENTLOGEOF EofRec;
    PEVENTLOGRECORD RecBuf;
    LARGE_INTEGER logFileSize;
    ULONG RecOffSet;
    ULONG WriteOffSet;

    if (!Buffer)
        return FALSE;

    GetSystemTime(&st);
    SystemTimeToEventTime(&st, &((PEVENTLOGRECORD) Buffer)->TimeWritten);

    RtlAcquireResourceExclusive(&LogFile->Lock, TRUE);

    if (!GetFileSizeEx(LogFile->hFile, &logFileSize))
    {
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    /* If the size of the file is over MaxSize */
    if ((logFileSize.QuadPart + BufSize)> LogFile->Header.MaxSize)
    {
        ULONG OverWriteLength = 0;
        WriteOffSet = LogfOffsetByNumber(LogFile, LogFile->Header.OldestRecordNumber);
        RecBuf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(EVENTLOGRECORD));
        /* Determine how many records need to be overwritten */
        while (TRUE)
        {
            DPRINT("EventLogFile has reached maximume size\n");

            if (!RecBuf)
            {
                DPRINT1("Failed to allocate buffer for OldestRecord!\n");
                HeapFree(GetProcessHeap(), 0, RecBuf);
                RtlReleaseResource(&LogFile->Lock);
                return FALSE;
            }

            /* Get the oldest record data */
            RecOffSet = LogfOffsetByNumber(LogFile, LogFile->Header.OldestRecordNumber);

            if (SetFilePointer(LogFile->hFile,
                               RecOffSet,
                               NULL,
                               FILE_BEGIN) == INVALID_SET_FILE_POINTER)
            {
                DPRINT1("SetFilePointer() failed! %d\n", GetLastError());
                HeapFree(GetProcessHeap(), 0, RecBuf);
                RtlReleaseResource(&LogFile->Lock);
                return FALSE;
            }

            if (!ReadFile(LogFile->hFile, RecBuf, sizeof(EVENTLOGRECORD), &dwRead, NULL))
            {
                DPRINT1("ReadFile() failed!\n");
                HeapFree(GetProcessHeap(), 0, RecBuf);
                RtlReleaseResource(&LogFile->Lock);
                return FALSE;
            }

            if (RecBuf->Reserved != LOGFILE_SIGNATURE)
            {
                DPRINT1("LogFile corrupt!\n");
                HeapFree(GetProcessHeap(), 0, RecBuf);
                RtlReleaseResource(&LogFile->Lock);
                return FALSE;
            }

            LogfDeleteOffsetInformation(LogFile,LogFile->Header.OldestRecordNumber);

            LogFile->Header.OldestRecordNumber++;

            OverWriteLength += RecBuf->Length;
            /* Check the size of the record as the record adding may be larger */
            if (OverWriteLength >= BufSize)
            {
                DPRINT("Record will fit. Length %d, BufSize %d\n", OverWriteLength, BufSize);
                LogFile->Header.StartOffset = LogfOffsetByNumber(LogFile, LogFile->Header.OldestRecordNumber);
                break;
            }
        }
        HeapFree(GetProcessHeap(), 0, RecBuf);
    }
    else
        WriteOffSet = LogFile->Header.EndOffset;

    if (SetFilePointer(LogFile->hFile,
                       WriteOffSet,
                       NULL,
                       FILE_BEGIN) == INVALID_SET_FILE_POINTER)
    {
        DPRINT1("SetFilePointer() failed! %d\n", GetLastError());
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    if (!WriteFile(LogFile->hFile, Buffer, BufSize, &dwWritten, NULL))
    {
        DPRINT1("WriteFile() failed! %d\n", GetLastError());
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    if (!LogfAddOffsetInformation(LogFile,
                                  LogFile->Header.CurrentRecordNumber,
                                  WriteOffSet))
    {
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    LogFile->Header.CurrentRecordNumber++;

    if (WriteOffSet == LogFile->Header.EndOffset)
    {
        LogFile->Header.EndOffset += dwWritten;
    }
    if (SetFilePointer(LogFile->hFile,
                       LogFile->Header.EndOffset,
                       NULL,
                       FILE_BEGIN) == INVALID_SET_FILE_POINTER)
    {
        DPRINT1("SetFilePointer() failed! %d\n", GetLastError());
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    EofRec.Ones = 0x11111111;
    EofRec.Twos = 0x22222222;
    EofRec.Threes = 0x33333333;
    EofRec.Fours = 0x44444444;
    EofRec.RecordSizeBeginning = sizeof(EVENTLOGEOF);
    EofRec.RecordSizeEnd = sizeof(EVENTLOGEOF);
    EofRec.CurrentRecordNumber = LogFile->Header.CurrentRecordNumber;
    EofRec.OldestRecordNumber = LogFile->Header.OldestRecordNumber;
    EofRec.BeginRecord = LogFile->Header.StartOffset;
    EofRec.EndRecord = LogFile->Header.EndOffset;

    if (!WriteFile(LogFile->hFile,
                   &EofRec,
                   sizeof(EVENTLOGEOF),
                   &dwWritten,
                   NULL))
    {
        DPRINT1("WriteFile() failed! %d\n", GetLastError());
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    if (SetFilePointer(LogFile->hFile, 0, NULL, FILE_BEGIN) ==
        INVALID_SET_FILE_POINTER)
    {
        DPRINT1("SetFilePointer() failed! %d\n", GetLastError());
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    if (!WriteFile(LogFile->hFile,
                   &LogFile->Header,
                   sizeof(EVENTLOGHEADER),
                   &dwWritten,
                   NULL))
    {
        DPRINT1("WriteFile failed! LastError = %d\n", GetLastError());
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    if (!FlushFileBuffers(LogFile->hFile))
    {
        DPRINT1("FlushFileBuffers() failed! %d\n", GetLastError());
        RtlReleaseResource(&LogFile->Lock);
        return FALSE;
    }

    RtlReleaseResource(&LogFile->Lock);
    return TRUE;
}
Ejemplo n.º 26
0
BOOL CFileLogger::CheckLogFile()
{
	if (!m_pOptions->GetOptionVal(OPTION_ENABLELOGGING)) {
		if (m_hLogFile != INVALID_HANDLE_VALUE) {
			CloseHandle(m_hLogFile);
			m_hLogFile = INVALID_HANDLE_VALUE;
		}
		return TRUE;
	}

	//Get logfile path
	TCHAR path[MAX_PATH + 1000]; //Make it large enough
	GetModuleFileName( 0, path, MAX_PATH );
	LPTSTR pos=_tcsrchr(path, '\\');
	if (pos)
		*++pos=0;
	_tcscat(path, _T("Logs\\"));

	//Get logfile name
	_int64 nLogType = m_pOptions->GetOptionVal(OPTION_LOGTYPE);
	TCHAR filename[MAX_PATH + 1];
	if (!nLogType) {
		_tcscpy(filename, _T("FileZilla Server.log"));
	}
	else {
		SYSTEMTIME time;
		GetLocalTime(&time);
		_stprintf(filename, _T("fzs-%d-%02d-%02d.log"), time.wYear, time.wMonth, time.wDay);
	}

	if (m_hLogFile == INVALID_HANDLE_VALUE || !m_pFileName || _tcscmp(m_pFileName, filename)) {
		TCHAR buffer[MAX_PATH + 1000]; //Make it large enough
		_tcscpy(buffer, path);
		CreateDirectory(buffer, NULL);

		if (m_pFileName)
			delete [] m_pFileName;
		m_pFileName = new TCHAR[_tcslen(filename)+1];
		_tcscpy(m_pFileName, filename);
		_tcscat(buffer, filename);

		if (m_hLogFile != INVALID_HANDLE_VALUE)
			CloseHandle(m_hLogFile);
		m_hLogFile = CreateFile(buffer, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
		if (m_hLogFile == INVALID_HANDLE_VALUE)
			return FALSE;

		SetFilePointer(m_hLogFile, 0, 0, FILE_END);
	}
	_int64 nLimit = m_pOptions->GetOptionVal(OPTION_LOGLIMITSIZE);

	if (nLogType) {
		//Different logfiles for each day
		//Find all log files, delete old ones
		//Also delete newer ones if total size exceeds limit

		//Get current date

		SYSTEMTIME time;
		FILETIME curFileTime;
		GetSystemTime(&time);
		SystemTimeToFileTime(&time, &curFileTime);
		_int64 nTime = curFileTime.dwLowDateTime + ((_int64)curFileTime.dwHighDateTime<<32);

		TCHAR buffer[MAX_PATH + 1000]; //Make it large enough
		_tcscpy(buffer, path);
		_tcscat(buffer, _T("fzs-*.log"));

		WIN32_FIND_DATA FindFileData;
		WIN32_FIND_DATA NextFindFileData;
		HANDLE hFind;
		hFind = FindFirstFile(buffer, &NextFindFileData);

		_int64 nDeleteTime = (_int64)m_pOptions->GetOptionVal(OPTION_LOGDELETETIME);
		if (nDeleteTime)
			nDeleteTime = (nDeleteTime+1) * 60 * 60 * 24 * 10000000;

		//Count total size of all logs, delete the oldest log if exceeding limit
		_int64 totalsize = 0;
		CStdString oldestname;
		_int64 oldestDate = 0;

		while (hFind != INVALID_HANDLE_VALUE)
		{
			FindFileData=NextFindFileData;
			if (!FindNextFile(hFind, &NextFindFileData))
			{
				FindClose(hFind);
				hFind = INVALID_HANDLE_VALUE;
			}

			if (!_tcscmp(FindFileData.cFileName, _T(".")) || !_tcscmp(FindFileData.cFileName, _T("..")))
				continue;

			_int64 size = ((_int64)FindFileData.nFileSizeHigh<<32) + FindFileData.nFileSizeLow;
			if (!_tcscmp(FindFileData.cFileName, m_pFileName))
			{
				totalsize += size;
				continue;
			}

			_int64 curtime=FindFileData.ftLastWriteTime.dwLowDateTime + ((_int64)FindFileData.ftLastWriteTime.dwHighDateTime<<32);
			_int64 span = nTime - curtime;
			TCHAR filename[MAX_PATH + 1000];
			_tcscpy(filename, path);
			_tcscat(filename, FindFileData.cFileName);
			if (nDeleteTime && span > nDeleteTime)
				DeleteFile(filename); //File is too old, delete it
			else
			{
				totalsize += size;
				if (curtime < oldestDate || !oldestDate)
				{
					oldestDate = curtime;
					oldestname = filename;
				}
			}
		}

		if (_tcscmp(oldestname, _T("")) && nLimit && totalsize > nLimit*1024)
		{
			DeleteFile(oldestname);
			return TRUE;
		}
	}

	//Single logfile, check size...
	if (nLimit)
	{
		_int64 size = GetPosition64(m_hLogFile);
		size /= 1024;
		if (size > nLimit) //Log file too large, shrink it...
		{
			int curReadPos = (int)(size * 1024 - (nLimit * 1024) * 0.9); //New log size is 10% smaller than the set limit
			int curWritePos =0;
			const int bufsize = 1024 * 64;
			char buffer[bufsize];
			DWORD numread;
			DWORD numwritten;
			BOOL bFirst = TRUE;;
			do {
				SetFilePointer(m_hLogFile, curReadPos, 0, FILE_BEGIN);
				if (!ReadFile(m_hLogFile, buffer, bufsize, &numread, 0))
					break;
				curReadPos += numread;

				SetFilePointer(m_hLogFile, curWritePos, 0, FILE_BEGIN);
				if (bFirst) //Assure log starts with complete line
				{
					unsigned int i;
					for (i=0; i<numread; i++)
					{
						if (buffer[i] == '\n')
							break;
					}
					if (i >= (numread-1))
						continue;
					bFirst = FALSE;
					if (!WriteFile(m_hLogFile, buffer + i + 1, numread - i - 1, &numwritten, 0))
						break;
				}
				else
					if (!WriteFile(m_hLogFile, buffer, numread, &numwritten, 0))
						break;
					curWritePos += numwritten;

			} while (numread == bufsize);

			SetFilePointer(m_hLogFile, curWritePos, 0, FILE_BEGIN);
			SetEndOfFile(m_hLogFile);
		}
	}
	return TRUE;
}
Ejemplo n.º 27
0
DWORD EGLExceptionHandler (DWORD exceptionCode, LPEXCEPTION_POINTERS exceptionInfo)
{
	context = *exceptionInfo->ContextRecord;

	// Show the mouse cursor
	ShowCursor (TRUE);

	// Continue searching?
#ifdef _DEBUG
	if (MessageBoxA (NULL, "An unhandled exception occured in CleanCode!\n\nThis version was built with debug information. Do you have a debugger you can attach? If so, do this now, then click Yes, otherwise click No.", "Unhandled Exception", MB_ICONERROR|MB_YESNO) == IDYES)
		return EXCEPTION_CONTINUE_SEARCH;
#endif

	// Load needed libraries and get the location of the needed functions
	hDbgHelp = LoadLibraryA ("DBGHELP");
	if (!hDbgHelp)
	{
		MessageBoxA (NULL, APP_FULLNAME " has encountered an unhandled exception and must be terminated. No crash report could be generated since " APP_FULLNAME " failed to load DBGHELP.DLL. Please obtain DBGHELP.DLL and place it in your Quake II directory to enable crash dump generation.", "Unhandled Exception", MB_OK | MB_ICONEXCLAMATION);
		return EXCEPTION_CONTINUE_SEARCH;
	}

	hVersion = LoadLibraryA ("VERSION");
	if (hVersion)
	{
		fnVerQueryValue = (VERQUERYVALUE)GetProcAddress (hVersion, "VerQueryValueA");
		fnGetFileVersionInfo = (GETFILEVERSIONINFO)GetProcAddress (hVersion, "GetFileVersionInfoA");
		fnGetFileVersionInfoSize = (GETFILEVERSIONINFOSIZE)GetProcAddress (hVersion, "GetFileVersionInfoSizeA");
	}

	fnEnumerateLoadedModules64 = (ENUMERATELOADEDMODULES64)GetProcAddress (hDbgHelp, "EnumerateLoadedModules64");
	fnSymSetOptions = (SYMSETOPTIONS)GetProcAddress (hDbgHelp, "SymSetOptions");
	fnSymInitialize = (SYMINITIALIZE)GetProcAddress (hDbgHelp, "SymInitialize");
	fnSymFunctionTableAccess64 = (SYMFUNCTIONTABLEACCESS64)GetProcAddress (hDbgHelp, "SymFunctionTableAccess64");
	fnSymGetModuleBase64 = (SYMGETMODULEBASE64)GetProcAddress (hDbgHelp, "SymGetModuleBase64");
	fnStackWalk64 = (STACKWALK64)GetProcAddress (hDbgHelp, "StackWalk64");
	fnSymFromAddr = (SYMFROMADDR)GetProcAddress (hDbgHelp, "SymFromAddr");
	fnSymCleanup = (SYMCLEANUP)GetProcAddress (hDbgHelp, "SymCleanup");
	fnSymGetModuleInfo64 = (SYMGETMODULEINFO64)GetProcAddress (hDbgHelp, "SymGetModuleInfo64");
	//fnSymLoadModule64 = (SYMLOADMODULE64)GetProcAddress (hDbgHelp, "SymLoadModule64");
	fnMiniDumpWriteDump = (MINIDUMPWRITEDUMP)GetProcAddress (hDbgHelp, "MiniDumpWriteDump");

	if (!fnEnumerateLoadedModules64 || !fnSymSetOptions || !fnSymInitialize || !fnSymFunctionTableAccess64
	|| !fnSymGetModuleBase64 || !fnStackWalk64 || !fnSymFromAddr || !fnSymCleanup || !fnSymGetModuleInfo64)
	// || !fnSymLoadModule64)
	{
		FreeLibrary (hDbgHelp);
		if (hVersion)
			FreeLibrary (hVersion);
		MessageBoxA (NULL, APP_FULLNAME " has encountered an unhandled exception and must be terminated. No crash report could be generated since " APP_FULLNAME " failed to load DBGHELP.DLL. Please obtain DBGHELP.DLL and place it in your Quake II directory to enable crash dump generation.", "Unhandled Exception", MB_OK | MB_ICONEXCLAMATION);
		return EXCEPTION_CONTINUE_SEARCH;
	}

	// Let the user know
	if (MessageBoxA (NULL, APP_FULLNAME " has encountered an unhandled exception and must be terminated. Would you like to generate a crash report?", "Unhandled Exception", MB_ICONEXCLAMATION | MB_YESNO) == IDNO)
	{
		FreeLibrary (hDbgHelp);
		if (hVersion)
			FreeLibrary (hVersion);
		return EXCEPTION_CONTINUE_SEARCH;
	}

	// Get the current process
	hProcess = GetCurrentProcess();

	fnSymSetOptions (SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_LOAD_ANYTHING);

	// Used to determine the directory for dump placement
	GetModuleFileNameA (NULL, searchPath, sizeof(searchPath));
	tempPointer = strrchr (searchPath, '\\');
	if (tempPointer)
		*tempPointer = '\0';

	// Get the system time
	GetSystemTime (&timeInfo);

	// Find the next filename to use for this dump
	sint32 dumpNum = 1;
	for (; ; dumpNum++)
	{
		Q_snprintfz (reportPath, sizeof(reportPath), "%s\\CCCrashLog%.4d-%.2d-%.2d_%d.txt", searchPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, dumpNum);
		if (Sys_FileLength (reportPath) == -1)
			break;
	}

	// Open the report dump file
	fhReport = fopen (reportPath, "wb");

	if (!fhReport)
	{
		FreeLibrary (hDbgHelp);
		if (hVersion)
			FreeLibrary (hVersion);
		return EXCEPTION_CONTINUE_SEARCH;
	}

	// Initialize symbols
	fnSymInitialize (hProcess, searchPath, TRUE);
#ifdef _M_AMD64
	InstructionPtr = context.Rip;
	frame.AddrPC.Offset = InstructionPtr;
	frame.AddrFrame.Offset = context.Rbp;
	frame.AddrPC.Offset = context.Rsp;
#else
	InstructionPtr = context.Eip;
	frame.AddrPC.Offset = InstructionPtr;
	frame.AddrFrame.Offset = context.Ebp;
	frame.AddrStack.Offset = context.Esp;
#endif

	frame.AddrFrame.Mode = AddrModeFlat;
	frame.AddrPC.Mode = AddrModeFlat;
	frame.AddrStack.Mode = AddrModeFlat;

	symInfo = (SYMBOL_INFO*)LocalAlloc (LPTR, sizeof(*symInfo) + 128);
	symInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
	symInfo->MaxNameLen = 128;
	fnOffset = 0;

	// Get OS info
	Mem_Zero (&osInfo, sizeof(osInfo));
	osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	if (!GetVersionEx ((OSVERSIONINFO *)&osInfo))
	{
		osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		GetVersionEx ((OSVERSIONINFO *)&osInfo);
	}

	// Find out which module threw the exception
	Q_strncpyz (szModuleName, "<unknown>", sizeof(szModuleName));
	fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)InstructionPtr);
	Q_strlwr (szModuleName);

	if (strstr (szModuleName, "gamex86"))
	{
		upMessage =
			"CleanCode's Gamex86 seems to be the root problem.\r\n"
			"If this is not base CleanCode, send the report to the mod author,\r\n"
			"otherwise send it to Paril (see the log .txt for more info)\r\n";
#ifdef USE_CURL
		upload = false;
#endif
	}
	else
	{
		upMessage =
			"Unable to detect where the exception occured!\r\n";
#ifdef USE_CURL
		upload = true;
#endif
	}

	// Write out the report to file
	fprintf (fhReport,
		APP_FULLNAME " encountered an unhandled exception and was terminated. If you are\r\n"
		"able to reproduce this crash, please submit the crash report when prompted, or email\r\n"
		"the file to Paril or any CleanCode project member. Goto http://code.google.com/p/cleancodequake2 and click on\r\n"
		"Issues, and file a bug report, or email [email protected] with the report.\r\n"
		"\r\n"
		"*** PLEASE MAKE SURE THAT YOU ARE USING THE LATEST VERSION OF CLEANCODE BEFORE SUBMITTING ***\r\nYour Cleancode Version: "CLEANCODE_VERSION_PRINT"\r\n", CLEANCODE_VERSION_PRINT_ARGS);

	fprintf (fhReport, "\r\n");

	// Windows information
	fprintf (fhReport, "Windows information:\r\n");
	fprintf (fhReport, "--------------------------------------------------\r\n");
	fprintf (fhReport, "String:       %s\r\n", GetOSDisplayString().CString());
	fprintf (fhReport, "Version:      %d.%d\r\n", osInfo.dwMajorVersion, osInfo.dwMinorVersion);
	fprintf (fhReport, "Build:        %d\r\n", osInfo.dwBuildNumber);
	fprintf (fhReport, "Service Pack: %s\r\n", osInfo.szCSDVersion[0] ? osInfo.szCSDVersion : "none");

	fprintf (fhReport, "\r\n");

	// Exception information
	fprintf (fhReport, "Exception information:\r\n");
	fprintf (fhReport, "--------------------------------------------------\r\n");
	fprintf (fhReport, "Code:    "HEX_VALUE_32"\r\n", exceptionCode);
	fprintf (fhReport, "Address: "HEX_VALUE_64"\r\n", InstructionPtr);
	fprintf (fhReport, "Module:  %s\r\n", szModuleName);

	fprintf (fhReport, "\r\n");

	// Symbol information
	fprintf (fhReport, "Symbol information:\r\n");
	fprintf (fhReport, "Name                                                        Symbol Type\r\n");
	fprintf (fhReport, "-----------------------------------------------------------------------\r\n");
	fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EEnumerateLoadedModulesProcSymInfoHeap::EnumerateLoadedModulesProcSymInfo, (VOID *)fhReport);

	fprintf (fhReport, "\r\n");

	// Loaded modules
	fprintf (fhReport, "Loaded modules:\r\n");
	fprintf (fhReport, "--------------------------------------------------\r\n");
	fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcDump, (VOID *)fhReport);

	fprintf (fhReport, "\r\n");

	// Stack trace
	fprintf (fhReport, "Stack trace:\r\n");
	fprintf (fhReport, "--------------------------------------------------\r\n");
	fprintf (fhReport, "Stack      EIP        Arg0       Arg1       Arg2       Arg3       Address\r\n");
	while (fnStackWalk64 (IMAGE_FILE_MACHINE_I386, hProcess, GetCurrentThread(), &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL))
	{
		Q_strncpyz (szModuleName, "<unknown>", sizeof(szModuleName));
		fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)(DWORD)frame.AddrPC.Offset);

		tempPointer = strrchr (szModuleName, '\\');
		if (tempPointer)
			tempPointer++;
		else
			tempPointer = szModuleName;

		fprintf (fhReport, ""HEX_VALUE_64" "HEX_VALUE_64" "HEX_VALUE_32" "HEX_VALUE_32" "HEX_VALUE_32" "HEX_VALUE_32" %-20s ! ",
			frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], tempPointer);

		if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
			fprintf (fhReport, "%-24s + "HEX_VALUE_64" %lu\r\n", symInfo->Name, fnOffset, symInfo->Tag);
		else
			fprintf (fhReport, ""HEX_VALUE_64"\r\n", frame.AddrPC.Offset);
	}

	fprintf (fhReport, "\r\n");

	// Write a minidump
	if (fnMiniDumpWriteDump)
	{
		HANDLE	hFile;

		//GetTempPath (sizeof(dumpPath)-16, dumpPath);
		Q_snprintfz (dumpPath, sizeof(dumpPath), "%s\\CCCrashLog%.4d-%.2d-%.2d_%d.dmp", searchPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, dumpNum);

		hFile = CreateFileA (dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hFile != INVALID_HANDLE_VALUE)
		{
			miniInfo.ClientPointers = TRUE;
			miniInfo.ExceptionPointers = exceptionInfo;
			miniInfo.ThreadId = GetCurrentThreadId ();
			if (fnMiniDumpWriteDump (hProcess, GetCurrentProcessId(), hFile, (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory|MiniDumpWithDataSegs), &miniInfo, NULL, NULL))
			{
				CloseHandle (hFile);

				FILE	*fh;
#ifdef USE_GZ
				CHAR	zPath[MAX_PATH];
#endif

				fh = fopen (dumpPath, "rb");
				if (fh)
#ifdef USE_GZ
				{
					gzFile	gz;

					Q_snprintfz (zPath, sizeof(zPath)-1, "%s\\CCCrashLog%.4d-%.2d-%.2d_%d.dmp.gz", searchPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, dumpNum);
					gz = gzopen (zPath, "wb");
					if (gz)
					{
						size_t len;
						while ((len = fread (gzBuff, 1, sizeof(gzBuff), fh)) > 0)
							gzwrite (gz, gzBuff, (uint32)len);
						gzclose (gz);
#endif
						fclose (fh);
#ifdef USE_GZ
					}
				}
#endif
		
#ifdef USE_GZ
				DeleteFileA (dumpPath);
				Q_strncpyz (dumpPath, zPath, sizeof(dumpPath));
#endif

				fprintf (fhReport, "A "
#ifdef USE_GZ
					"minidump"
#else
					"dump"
#endif
					" was saved to %s.\r\nPlease include this file when posting a crash report.\r\n", dumpPath);
			}
			else
			{
				CloseHandle (hFile);
				DeleteFileA (dumpPath);
			}
		}
	}
	else
		fprintf (fhReport, "A minidump could not be created. Minidumps are only available on Windows XP or later.\r\n");

	// Done writing reports
	fclose (fhReport);
	LocalFree (symInfo);
	fnSymCleanup (hProcess);

	// Let the client know
	String temp = String::Format("Report written to: %s\r\nMini-dump written to %s\r\nPlease include both files if you submit manually!\r\n", reportPath, dumpPath);
	MessageBoxA (NULL, temp.CString(), "Unhandled Exception", MB_ICONEXCLAMATION | MB_OK);

#ifdef USE_CURL
	if (upload)
	{
		ret = MessageBox (NULL, "Would you like to automatically upload this crash report for analysis?\nPlease do not submit multiple reports of the same crash as this will only delay processing.", "Unhandled Exception", MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2);
		if (ret == IDYES)
			EGLUploadCrashDump (dumpPath, reportPath);
		else
			MessageBox (NULL, "You have chosen to manually upload the crash report.\nPlease include BOTH the crash log and mini-dump when you post it on the EGL forums!\n", "Submit manually", MB_ICONEXCLAMATION|MB_OK);
	}
	else
#endif
	MessageBoxA (NULL, upMessage, "Unhandled Exception", MB_OK|MB_ICONEXCLAMATION);

	// Done
	FreeLibrary (hDbgHelp);
	if (hVersion)
		FreeLibrary (hVersion);

	return EXCEPTION_EXECUTE_HANDLER;
}
Ejemplo n.º 28
0
BOOL CPubThread::DoThread(LPVOID pData)
{
	DWORD enablepublishing = 0;
	CFG().GetValue( "Settings", "EnablePublishing", &enablepublishing );

	// Punt if publishing is disabled
	if ( !enablepublishing )
	{	m_bReset = TRUE;
		Sleep( 1000 ); return TRUE;
	} // end if

	DWORD tickcount = GetTickCount();
	
	SYSTEMTIME	st;
	GetSystemTime( &st );

	// Calculate seconds offset
	DWORD seconds = ( st.wHour * 60 * 60 ) + ( st.wMinute * 60 ) + st.wSecond;

	// Process each job
	LPPUBINFO ppi = NULL;
	while ( ( ppi = (LPPUBINFO)PUBLIST().GetNext( ppi ) ) != NULL )
	{
		try
		{
			// Is publishing on hold?
			if ( ppi->bHold ) continue;

			// Image information
			LPPUBIMGINFO ppii = NULL;

			// Are we doing any avi capturing?
			if ( ( ppi->f1 & ( PUBF1_AVI | PUBF1_THMAVI ) ) != 0 )
			{
				// Update AVI's
				if ( ( ppi->f1 & PUBF1_AVICAPMOTION ) == 0 || IsMotion( ppi ) )
				{
					// Check for avi
					if ( ( ppi->f1 & PUBF1_AVI ) != 0 )
					{
						// Time to capture?
						if (	( ppi->f1 & PUBF1_AVICAPMOTION ) != 0 || 
								ppi->avitimeout < tickcount )
						{
							ppii = IMGLIST().FindByName( ppi->img );
							if ( ppii != NULL )
							{
								// Refresh the image
								IMGLIST().Update( ppii, TRUE );

								// Wait for next frame
								if ( ppi->capframes < 1 ) ppi->capframes = 1;
								if ( ppi->capseconds < 1 ) ppi->capseconds = 1;
								long delay = ( ppi->capseconds * 1000 ) / ppi->capframes;
								ppi->avitimeout = tickcount + delay;

								// Write out a frame of the avi
								WriteAviFrame( ppi, ppi->avi, ppii, ppi->pub_fname );
							
							} // end if

						} // end if

					} // end if

					// Check for thumbnail avi
					if ( ( ppi->f1 & PUBF1_THMAVI ) != 0 )
					{
						// Time to capture?
						if (	( ppi->f1 & PUBF1_AVICAPMOTION ) != 0 || 
								ppi->thmavitimeout < tickcount )
						{
							// Get image if we don't already have it
							if ( ppii == NULL )
							{	ppii = IMGLIST().FindByName( ppi->img );
								IMGLIST().Update( ppii, TRUE );
							} // end if

							if ( ppii != NULL )
							{
								// Wait for next frame
								if ( ppi->capframes < 1 ) ppi->capframes = 1;
								if ( ppi->capseconds < 1 ) ppi->capseconds = 1;
								long delay = ( ppi->capseconds * 1000 ) / ppi->capframes;
								ppi->thmavitimeout = tickcount + delay;

								// Write out a frame of the avi
								WriteAviFrame( ppi, ppi->thmavi, ppii, ppi->pub_tfname );

							} // end if

						} // end if

					} // end if

				} // end if

			} // end if

			// Are we detecting motion?
			if ( ( ppi->f1 & PUBF1_MOTION ) != 0 )
			{
				if ( IsMotion( ppi ) )
				{
					// Save motion time
					if ( ppi->motioninterval == 0 ) ppi->motioninterval = 30;
					ppi->nextmotion = GetTickCount() + ( ppi->motioninterval * 1000 );

					// Get current file name
					GetFileName( ppi );

					// Refresh the image
					if ( ppii == NULL ) IMGLIST().Update( ppi->img, TRUE );

					// Handle avi
					if ( ( ppi->f1 & PUBF1_AVI ) != 0 )
					{
						if ( ppi->avi->IsOpen() )
						{
							// Save avi filename
							strcpy( ppi->avicachefile, ppi->avi->GetFileName() );
							ppi->avi->Close();

							// Save thumbnail avi filename
							strcpy( ppi->thmavicachefile, ppi->thmavi->GetFileName() );
							ppi->thmavi->Close();

						} // end if

					} // end if

					// Handle thumbnail avi
					if ( ( ppi->f1 & PUBF1_THMAVI ) != 0 )
					{
						if ( ppi->thmavi->IsOpen() )
						{
							// Save avi filename
							strcpy( ppi->thmavicachefile, ppi->thmavi->GetFileName() );
							ppi->thmavi->Close();

							// Save thumbnail avi filename
							strcpy( ppi->thmavicachefile, ppi->thmavi->GetFileName() );
							ppi->thmavi->Close();

						} // end if

					} // end if

					BOOL bPublished = FALSE;

					// Check for FTP
					if ( ppi->type == PUBTYPE_FTP ) bPublished = Ftp( ppi );

					// Check for Email
					else if ( ppi->type == PUBTYPE_EMAIL ) bPublished = Email( ppi );

					// Check for Disk
					else if ( ppi->type == PUBTYPE_DISK ) bPublished = Disk( ppi );

					if ( bPublished )
					{
						// Inform FRAME
						if ( ppi->type == PUBTYPE_FTP ) FRAME()->SetEvent( 2 );
						else if ( ppi->type == PUBTYPE_EMAIL ) FRAME()->SetEvent( 3 );
						else if ( ppi->type == PUBTYPE_DISK ) FRAME()->SetEvent( 4 );

						// Play sound if needed
						if ( ( ppi->f1 & PUBF1_PLAYSOUND ) != 0 )
						{	if ( *ppi->snd ) PLAYSOUND( ppi->snd );
							else PLAYSOUND( IDW_CAMERA );
						} // end if

					} // end if

					// Ensure cache files are gone
					if ( *ppi->avicachefile != 0 )
					{	CWinFile::Delete( ppi->avicachefile );
						*ppi->avicachefile = 0;
					} // end if
					if ( *ppi->thmavicachefile != 0 )
					{	CWinFile::Delete( ppi->thmavicachefile );
						*ppi->thmavicachefile = 0;
					} // end if

				} // end if

			} // end if

			// Has an interval been specified?
			else if ( ppi->interval != 0 )
			{
				// Set interval first time
				if ( m_bReset || ppi->timeout == 0 ) 
					ppi->timeout = tickcount + ( ppi->interval * 1000 );

				// Have we timed out?			
				BOOL publish = ppi->timeout < tickcount;

				// Do we want to sync to the system clock?
				if ( !publish && ( ppi->f1 & PUBF1_SYNCTOCLOCK ) != 0 ) 
				{
					// Is it a new second?
					if ( seconds != ppi->lasttime )
					{
						// Record last pub time
						ppi->lasttime = seconds;

						// Is it time to publish?
						if ( !( seconds % ppi->interval ) ) publish = TRUE;

					} // end if

				} // end if

				if ( publish )
				{
					// Record next timeout interval
					ppi->timeout = tickcount + ( ppi->interval * 1000 );

					// Record last pub time
					ppi->lasttime = seconds;
					
					// Get current file name
					GetFileName( ppi );

					// Refresh the image
					if ( ppii == NULL ) IMGLIST().Update( ppi->img, TRUE );

					// Handle avi
					if ( ( ppi->f1 & PUBF1_AVI ) != 0 )
					{
						if ( ppi->avi->IsOpen() )
						{
							// Save avi filename
							strcpy( ppi->avicachefile, ppi->avi->GetFileName() );
							ppi->avi->Close();

							// Save thumbnail avi filename
							strcpy( ppi->thmavicachefile, ppi->thmavi->GetFileName() );
							ppi->thmavi->Close();

						} // end if

						// Punt if no avi
						else return TRUE;

					} // end if

					// Handle thumbnail avi
					if ( ( ppi->f1 & PUBF1_THMAVI ) != 0 )
					{
						if ( ppi->thmavi->IsOpen() )
						{
							// Save avi filename
							strcpy( ppi->thmavicachefile, ppi->thmavi->GetFileName() );
							ppi->thmavi->Close();

							// Save thumbnail avi filename
							strcpy( ppi->thmavicachefile, ppi->thmavi->GetFileName() );
							ppi->thmavi->Close();

						} // end if

					} // end if

					BOOL bPublished = FALSE;

					// Check for FTP
					if ( ppi->type == PUBTYPE_FTP ) bPublished = Ftp( ppi );

					// Check for Email
					else if ( ppi->type == PUBTYPE_EMAIL ) bPublished = Email( ppi );

					// Check for Disk
					else if ( ppi->type == PUBTYPE_DISK ) bPublished = Disk( ppi );

					if ( bPublished )
					{
						// Inform FRAME
						if ( ppi->type == PUBTYPE_FTP ) FRAME()->SetEvent( 2 );
						else if ( ppi->type == PUBTYPE_EMAIL ) FRAME()->SetEvent( 3 );
						else if ( ppi->type == PUBTYPE_DISK ) FRAME()->SetEvent( 4 );

						// Play sound if needed
						if ( ( ppi->f1 & PUBF1_PLAYSOUND ) != 0 )
						{	if ( *ppi->snd ) PLAYSOUND( ppi->snd );
							else PLAYSOUND( IDW_CAMERA );
						} // end if

					} // end if

					// Ensure cache files are gone
					if ( *ppi->avicachefile != 0 )
					{	CWinFile::Delete( ppi->avicachefile );
						*ppi->avicachefile = 0;
					} // end if
					if ( *ppi->thmavicachefile != 0 )
					{	CWinFile::Delete( ppi->thmavicachefile );
						*ppi->thmavicachefile = 0;
					} // end if

				} // end if

			} // end if

		} // end try

		// Try to return to a normal life if we can...
		catch( ... ) 
		{	_Log( MB_ICONERROR, "PublishThread()", "Assert" );	
			ASSERT( 0 ); 
		}
	
	} // end while

	m_bReset = FALSE;

	Sleep( 100 );

	return TRUE;
}
Ejemplo n.º 29
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow )
{
    char pszPath[MAX_PATH];
    char pszOutput[10000];
    DWORD dwNumberOfBytesWritten;

    GetModuleFileName(NULL, pszPath, MAX_PATH);

    pszPath[strlen(pszPath)-3] = '\0';
    strcat(pszPath, "log");

    HANDLE file = NULL;

    file = CreateFile(pszPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    if(!file) {
        MessageBox(NULL, "Failed to create log file!", "ATCMControl Remove Lic", MB_OK|MB_ICONERROR);
    }

    strcpy(pszOutput, "RemoveLic\r\n");
    WriteFile(file, pszOutput, strlen(pszOutput), &dwNumberOfBytesWritten, NULL);

    SYSTEMTIME sysTime;

    GetSystemTime(&sysTime);

    sprintf(pszOutput, "%i.%i.%i,%i:%i:%i\r\n", 
            sysTime.wDay, sysTime.wMonth, sysTime.wYear, 
            sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
    WriteFile(file, pszOutput, strlen(pszOutput), &dwNumberOfBytesWritten, NULL);

    // rever to the SoftingProd.h file for all products relatet to 4C!
    // remove the V2.0 ATCM Productkeys
    int i;
    for(i=1; i<=6; i++) {
        char strKey[10];
        _itoa(i, strKey, 10);
        RemoveLicKey(file, strKey);
    }
    RemoveLicKey(file, "20");
    RemoveLicKey(file, "21");
    RemoveLicKey(file, "23");
    RemoveLicKey(file, "52");

    // remove the V2.1 ATCM Productkey
    for(i=61; i<=75; i++) {
        char strKey[10];
        _itoa(i, strKey, 10);
        RemoveLicKey(file, strKey);
    }
    RemoveLicKey(file, "79");
    RemoveLicKey(file, "85");
    RemoveLicKey(file, "86");
    
    CloseHandle(file);

    if(gError>0) {
        MessageBox(NULL, "Not all license info could be deleted!", "ATCMControl Remove Lic", MB_OK|MB_ICONERROR);
    } else {
        sprintf(pszOutput, "ATCMControl license information removed successfully.\nLog information stored in %s", pszPath);
        MessageBox(NULL, pszOutput, "ATCMControl Remove Lic", MB_OK);

    }

	return 0;
}
Ejemplo n.º 30
-1
// caller needs to free() the result
static WCHAR *GetInstallDate()
{
    SYSTEMTIME st;
    GetSystemTime(&st);
    return str::Format(L"%04d%02d%02d", st.wYear, st.wMonth, st.wDay);
}