예제 #1
0
INT_PTR srvVariablesHandler(WPARAM, LPARAM lParam)
{
	ARGUMENTSINFO *ai = (ARGUMENTSINFO*)lParam;
	ai->flags = AIF_DONTPARSE;
	TCString Result;
	if (!mir_tstrcmp(ai->targv[0], VAR_AWAYSINCE_TIME)) {
		GetTimeFormat(LOCALE_USER_DEFAULT, 0, g_ProtoStates[VarParseData.szProto].m_awaySince, (ai->argc > 1 && *ai->targv[1]) ? ai->targv[1] : _T("H:mm"), Result.GetBuffer(256), 256);
		Result.ReleaseBuffer();
	}
	else if (!mir_tstrcmp(ai->targv[0], VAR_AWAYSINCE_DATE)) {
		GetDateFormat(LOCALE_USER_DEFAULT, 0, g_ProtoStates[VarParseData.szProto].m_awaySince, (ai->argc > 1 && *ai->targv[1]) ? ai->targv[1] : NULL, Result.GetBuffer(256), 256);
		Result.ReleaseBuffer();
	}
	else if (!mir_tstrcmp(ai->targv[0], VAR_STATDESC)) {
		Result = (VarParseData.Flags & VPF_XSTATUS) ? STR_XSTATUSDESC : pcli->pfnGetStatusModeDescription(g_ProtoStates[VarParseData.szProto].m_status, 0);
	}
	else if (!mir_tstrcmp(ai->targv[0], VAR_MYNICK)) {
		if (g_MoreOptPage.GetDBValueCopy(IDC_MOREOPTDLG_MYNICKPERPROTO) && VarParseData.szProto)
			Result = db_get_s(NULL, VarParseData.szProto, "Nick", (TCHAR*)NULL);

		if (Result == NULL)
			Result = pcli->pfnGetContactDisplayName(NULL, 0);

		if (Result == NULL)
			Result = TranslateT("Stranger");
	}
	else if (!mir_tstrcmp(ai->targv[0], VAR_REQUESTCOUNT)) {
		mir_sntprintf(Result.GetBuffer(16), 16, _T("%d"), db_get_w(ai->fi->hContact, MOD_NAME, DB_REQUESTCOUNT, 0));
		Result.ReleaseBuffer();
	}
	else if (!mir_tstrcmp(ai->targv[0], VAR_MESSAGENUM)) {
		mir_sntprintf(Result.GetBuffer(16), 16, _T("%d"), db_get_w(ai->fi->hContact, MOD_NAME, DB_MESSAGECOUNT, 0));
		Result.ReleaseBuffer();
	}
	else if (!mir_tstrcmp(ai->targv[0], VAR_TIMEPASSED)) {
		ULARGE_INTEGER ul_AwaySince, ul_Now;
		SYSTEMTIME st;
		GetLocalTime(&st);
		SystemTimeToFileTime(&st, (LPFILETIME)&ul_Now);
		SystemTimeToFileTime(g_ProtoStates[VarParseData.szProto].m_awaySince, (LPFILETIME)&ul_AwaySince);
		ul_Now.QuadPart -= ul_AwaySince.QuadPart;
		ul_Now.QuadPart /= 10000000; // now it's in seconds
		Result.GetBuffer(256);
		if (ul_Now.LowPart >= 7200) // more than 2 hours
			mir_sntprintf(Result, 256, TranslateT("%d hours"), ul_Now.LowPart / 3600);
		else if (ul_Now.LowPart >= 120) // more than 2 minutes
			mir_sntprintf(Result, 256, TranslateT("%d minutes"), ul_Now.LowPart / 60);
		else
			mir_sntprintf(Result, 256, TranslateT("%d seconds"), ul_Now.LowPart);
		Result.ReleaseBuffer();
	}
	else if (!mir_tstrcmp(ai->targv[0], VAR_PREDEFINEDMESSAGE)) {
		ai->flags = 0; // reset AIF_DONTPARSE flag
		if (ai->argc != 2)
			return NULL;

		COptPage MsgTreeData(g_MsgTreePage);
		COptItem_TreeCtrl *TreeCtrl = (COptItem_TreeCtrl*)MsgTreeData.Find(IDV_MSGTREE);
		TreeCtrl->DBToMem(CString(MOD_NAME));

		for (int i = 0; i < TreeCtrl->m_value.GetSize(); i++) {
			if (!(TreeCtrl->m_value[i].Flags & TIF_GROUP) && !mir_tstrcmpi(TreeCtrl->m_value[i].Title, ai->targv[1])) {
				Result = TreeCtrl->m_value[i].User_Str1;
				break;
			}
		}
		if (Result == NULL) // if we didn't find a message with specified title
			return NULL; // return it now, as later we change NULL to ""
	}
	else if (!mir_tstrcmp(ai->targv[0], VAR_PROTOCOL)) {
		if (VarParseData.szProto) {
			CString AnsiResult;
			CallProtoService(VarParseData.szProto, PS_GETNAME, 256, (LPARAM)AnsiResult.GetBuffer(256));
			AnsiResult.ReleaseBuffer();
			Result = _A2T(AnsiResult);
		}
		if (Result == NULL) // if we didn't find a message with specified title
			return NULL; // return it now, as later we change NULL to ""
	}
	TCHAR *szResult = (TCHAR*)malloc((Result.GetLen() + 1) * sizeof(TCHAR));
	if (!szResult)
		return NULL;

	mir_tstrcpy(szResult, (Result != NULL) ? Result : _T(""));
	return (INT_PTR)szResult;
}
예제 #2
0
static int ssleay_rand_bytes(unsigned char *buf, int num, int pseudo)
	{
	static volatile int stirred_pool = 0;
	int i,j,k,st_num,st_idx;
	int num_ceil;
	int ok;
	long md_c[2];
	unsigned char local_md[MD_DIGEST_LENGTH];
	EVP_MD_CTX m;
#ifndef GETPID_IS_MEANINGLESS
	pid_t curr_pid = getpid();
#endif
	time_t curr_time = time(NULL);
	int do_stir_pool = 0;
/* time value for various platforms */
#ifdef OPENSSL_SYS_WIN32
	FILETIME tv;
# ifdef _WIN32_WCE
	SYSTEMTIME t;
	GetSystemTime(&t);
	SystemTimeToFileTime(&t, &tv);
# else
	GetSystemTimeAsFileTime(&tv);
# endif
#elif defined(OPENSSL_SYS_VXWORKS)
	struct timespec tv;
	clock_gettime(CLOCK_REALTIME, &ts);
#elif defined(OPENSSL_SYSNAME_DSPBIOS)
	unsigned long long tv, OPENSSL_rdtsc();
	tv = OPENSSL_rdtsc();
#else
	struct timeval tv;
	gettimeofday(&tv, NULL);
#endif

#ifdef PREDICT
	if (rand_predictable)
		{
		static unsigned char val=0;

		for (i=0; i<num; i++)
			buf[i]=val++;
		return(1);
		}
#endif

	if (num <= 0)
		return 1;

	EVP_MD_CTX_init(&m);
	/* round upwards to multiple of MD_DIGEST_LENGTH/2 */
	num_ceil = (1 + (num-1)/(MD_DIGEST_LENGTH/2)) * (MD_DIGEST_LENGTH/2);

	/*
	 * (Based on the rand(3) manpage:)
	 *
	 * For each group of 10 bytes (or less), we do the following:
	 *
	 * Input into the hash function the local 'md' (which is initialized from
	 * the global 'md' before any bytes are generated), the bytes that are to
	 * be overwritten by the random bytes, and bytes from the 'state'
	 * (incrementing looping index). From this digest output (which is kept
	 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
	 * bottom 10 bytes are xored into the 'state'.
	 * 
	 * Finally, after we have finished 'num' random bytes for the
	 * caller, 'count' (which is incremented) and the local and global 'md'
	 * are fed into the hash function and the results are kept in the
	 * global 'md'.
	 */

	CRYPTO_w_lock(CRYPTO_LOCK_RAND);

	/* prevent ssleay_rand_bytes() from trying to obtain the lock again */
	CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
	CRYPTO_THREADID_current(&locking_threadid);
	CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
	crypto_lock_rand = 1;

	if (!initialized)
		{
		RAND_poll();
		initialized = 1;
		}
	
	if (!stirred_pool)
		do_stir_pool = 1;
	
	ok = (entropy >= ENTROPY_NEEDED);
	if (!ok)
		{
		/* If the PRNG state is not yet unpredictable, then seeing
		 * the PRNG output may help attackers to determine the new
		 * state; thus we have to decrease the entropy estimate.
		 * Once we've had enough initial seeding we don't bother to
		 * adjust the entropy count, though, because we're not ambitious
		 * to provide *information-theoretic* randomness.
		 *
		 * NOTE: This approach fails if the program forks before
		 * we have enough entropy. Entropy should be collected
		 * in a separate input pool and be transferred to the
		 * output pool only when the entropy limit has been reached.
		 */
		entropy -= num;
		if (entropy < 0)
			entropy = 0;
		}

	if (do_stir_pool)
		{
		/* In the output function only half of 'md' remains secret,
		 * so we better make sure that the required entropy gets
		 * 'evenly distributed' through 'state', our randomness pool.
		 * The input function (ssleay_rand_add) chains all of 'md',
		 * which makes it more suitable for this purpose.
		 */

		int n = STATE_SIZE; /* so that the complete pool gets accessed */
		while (n > 0)
			{
#if MD_DIGEST_LENGTH > 20
# error "Please adjust DUMMY_SEED."
#endif
#define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
			/* Note that the seed does not matter, it's just that
			 * ssleay_rand_add expects to have something to hash. */
			ssleay_rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
			n -= MD_DIGEST_LENGTH;
			}
		if (ok)
			stirred_pool = 1;
		}

	st_idx=state_index;
	st_num=state_num;
	md_c[0] = md_count[0];
	md_c[1] = md_count[1];
	memcpy(local_md, md, sizeof md);

	state_index+=num_ceil;
	if (state_index > state_num)
		state_index %= state_num;

	/* state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num]
	 * are now ours (but other threads may use them too) */

	md_count[0] += 1;

	/* before unlocking, we must clear 'crypto_lock_rand' */
	crypto_lock_rand = 0;
	CRYPTO_w_unlock(CRYPTO_LOCK_RAND);

	while (num > 0)
		{
		/* num_ceil -= MD_DIGEST_LENGTH/2 */
		j=(num >= MD_DIGEST_LENGTH/2)?MD_DIGEST_LENGTH/2:num;
		num-=j;
		if (!MD_Init(&m))
			goto err;
#ifndef GETPID_IS_MEANINGLESS
		if (curr_pid) /* just in the first iteration to save time */
			{
			if (!MD_Update(&m,(unsigned char*)&curr_pid,
				       sizeof curr_pid))
				goto err;
			curr_pid = 0;
			}
#endif
		if (curr_time) /* just in the first iteration to save time */
			{
			if (!MD_Update(&m,(unsigned char*)&curr_time,
				       sizeof curr_time))
				goto err;
			if (!MD_Update(&m,(unsigned char*)&tv,
				       sizeof tv))
				goto err;
			curr_time = 0;
			rand_hw_seed(&m);
			}
		if (!MD_Update(&m,local_md,MD_DIGEST_LENGTH))
			goto err;
		if (!MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c)))
			goto err;

#ifndef PURIFY /* purify complains */
		/* The following line uses the supplied buffer as a small
		 * source of entropy: since this buffer is often uninitialised
		 * it may cause programs such as purify or valgrind to
		 * complain. So for those builds it is not used: the removal
		 * of such a small source of entropy has negligible impact on
		 * security.
		 */
		if (!MD_Update(&m,buf,j))
			goto err;
#endif

		k=(st_idx+MD_DIGEST_LENGTH/2)-st_num;
		if (k > 0)
			{
			if (!MD_Update(&m,&(state[st_idx]),MD_DIGEST_LENGTH/2-k))
				goto err;
			if (!MD_Update(&m,&(state[0]),k))
				goto err;
			}
		else
			if (!MD_Update(&m,&(state[st_idx]),MD_DIGEST_LENGTH/2))
				goto err;
		if (!MD_Final(&m,local_md))
			goto err;

		for (i=0; i<MD_DIGEST_LENGTH/2; i++)
			{
			state[st_idx++]^=local_md[i]; /* may compete with other threads */
			if (st_idx >= st_num)
				st_idx=0;
			if (i < j)
				*(buf++)=local_md[i+MD_DIGEST_LENGTH/2];
			}
		}

	if (!MD_Init(&m)
		|| !MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c))
		|| !MD_Update(&m,local_md,MD_DIGEST_LENGTH))
		goto err;
	CRYPTO_w_lock(CRYPTO_LOCK_RAND);
	if (!MD_Update(&m,md,MD_DIGEST_LENGTH) || !MD_Final(&m,md))
		{
		CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
		goto err;
		}
	CRYPTO_w_unlock(CRYPTO_LOCK_RAND);

	EVP_MD_CTX_cleanup(&m);
	if (ok)
		return(1);
	else if (pseudo)
		return 0;
	else 
		{
		RANDerr(RAND_F_SSLEAY_RAND_BYTES,RAND_R_PRNG_NOT_SEEDED);
		ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
			"http://www.openssl.org/support/faq.html");
		return(0);
		}
	err:
	EVP_MD_CTX_cleanup(&m);
	RANDerr(RAND_F_SSLEAY_RAND_BYTES,ERR_R_EVP_LIB);
	return 0;

	}
예제 #3
0
void
__gnat_localtime_tzoff (const time_t *timer, long *off)
{
  union
  {
    FILETIME ft_time;
    unsigned long long ull_time;
  } utc_time, local_time;

  SYSTEMTIME utc_sys_time, local_sys_time;
  TIME_ZONE_INFORMATION tzi;

  BOOL  status = 1;
  DWORD tzi_status;

  (*Lock_Task) ();

#ifdef RTX

  tzi_status = GetTimeZoneInformation (&tzi);
  *off = tzi.Bias;
  if (tzi_status == TIME_ZONE_ID_STANDARD)
     /* The system is operating in the range covered by the StandardDate
        member. */
     *off = *off + tzi.StandardBias;
  else if (tzi_status == TIME_ZONE_ID_DAYLIGHT)
     /* The system is operating in the range covered by the DaylightDate
        member. */
     *off = *off + tzi.DaylightBias;
  *off = *off * -60;

#else

  /* First convert unix time_t structure to windows FILETIME format.  */
  utc_time.ull_time = ((unsigned long long) *timer + w32_epoch_offset)
                      * 10000000ULL;

  tzi_status = GetTimeZoneInformation (&tzi);

  /* If GetTimeZoneInformation does not return a value between 0 and 2 then
     it means that we were not able to retrieve timezone informations.
     Note that we cannot use here FileTimeToLocalFileTime as Windows will use
     in always in this case the current timezone setting. As suggested on
     MSDN we use the following three system calls to get the right information.
     Note also that starting with Windows Vista new functions are provided to
     get timezone settings that depend on the year. We cannot use them as we
     still support Windows XP and Windows 2003.  */
  status = (tzi_status >= 0 && tzi_status <= 2)
     && FileTimeToSystemTime (&utc_time.ft_time, &utc_sys_time)
     && SystemTimeToTzSpecificLocalTime (&tzi, &utc_sys_time, &local_sys_time)
     && SystemTimeToFileTime (&local_sys_time, &local_time.ft_time);

  if (!status)
     /* An error occurs so return invalid_tzoff.  */
     *off = __gnat_invalid_tzoff;
  else
     if (local_time.ull_time > utc_time.ull_time)
        *off = (long) ((local_time.ull_time - utc_time.ull_time) / 10000000ULL);
     else
        *off = - (long) ((utc_time.ull_time - local_time.ull_time) / 10000000ULL);

#endif

  (*Unlock_Task) ();
}
예제 #4
0
BOOL CSchedule_HTSPage::OnApply()
{
	SYSTEMTIME time;
	m_wndTime.GetTime (&time);

	if (IsDlgButtonChecked (IDC_ONCE) == BST_CHECKED)
	{
		SYSTEMTIME date;
		m_wndDate.GetTime (&date);

		date.wHour   = time.wHour;
		date.wMinute = time.wMinute;
		date.wSecond = time.wSecond;

		SystemTimeToFileTime (&date, &m_task->hts.next);
		m_task->hts.enType = HTS_ONCE;
	}
	else if (IsDlgButtonChecked (IDC_DAILY) == BST_CHECKED)
	{
		UINT nIDs [] = {IDC_SUN, IDC_MON, IDC_TUE, IDC_WED, IDC_THU, IDC_FRI, IDC_SAT};
		BOOL bOk = FALSE;
		for (int i = 0; i < 7; i++)
		{
			m_task->hts.aWeeklyDays [i] = IsDlgButtonChecked (nIDs [i]) == BST_CHECKED;
			bOk = bOk || m_task->hts.aWeeklyDays [i];
		}
		if (bOk == FALSE)
		{
			
			MessageBox (LS (L_ENTERDAYS), LS (L_INPERR), MB_ICONEXCLAMATION);
			return FALSE;
		}
		m_task->hts.enType = HTS_DAILY;
		SystemTimeToFileTime (&time, &m_task->hts.next);
		
	}
	else if (IsDlgButtonChecked (IDC_ONEVERY) == BST_CHECKED)
	{
		UINT u = GetDlgItemInt (IDC_EVERY);
		if (u == 0)
		{
			CString str; str.Format (LS (L_ENTERGREATER), 0);
			MessageBox (str, LS (L_ERR), MB_ICONEXCLAMATION);
			return FALSE;
		}

		int i = m_wndEveryDim.GetCurSel ();
		int mul [] = {1, 60, 60*24};	
		u *= mul [i];
		m_task->hts.interval = u;
		m_task->hts.enType = HTS_CONTINUOUSLY;
		SystemTimeToFileTime (&time, &m_task->hts.next);
	}
	else
	{
		m_task->hts.enType = (fsWhenToStartType) (HTS_WHENISTART + m_wndEvent.GetCurSel ());
		if (m_task->hts.enType == HTS_WHENSPEEDLOW)
		{
			m_task->hts.speedLow.uTimeInterval = GetDlgItemInt (IDC_DURING);
			m_task->hts.speedLow.uLowSpeed = GetDlgItemInt (IDC_LOWSPEED);
		}
		else if (m_task->hts.enType == HTS_NOTHINGRECEIVED || m_task->hts.enType == HTS_WHENDONE)
		{
			m_task->hts.uTimeNothingReceived = GetDlgItemInt (IDC_DURING);
		}
	}
	
	return CPropertyPage::OnApply();
}
예제 #5
0
파일: NFS3Prog.cpp 프로젝트: philr/winnfsd
nfsstat3 CNFS3Prog::ProcedureSETATTR(void)
{
    char *path;
    sattr3 new_attributes;
    sattrguard3 guard;
    wcc_data obj_wcc;
    nfsstat3 stat;
    int nMode;
    FILE *pFile;
    HANDLE hFile;
    FILETIME fileTime;
    SYSTEMTIME systemTime;

    PrintLog("SETATTR");
    path = GetPath();
    Read(&new_attributes);
    Read(&guard);
    stat = CheckFile(path);
    obj_wcc.before.attributes_follow = GetFileAttributesForNFS(path, &obj_wcc.before.attributes);

    if (stat == NFS3_OK) {
        if (new_attributes.mode.set_it) {
            nMode = 0;

            if ((new_attributes.mode.mode & 0x100) != 0) {
                nMode |= S_IREAD;
            }

            // Always set read and write permissions (deliberately implemented this way)
            // if ((new_attributes.mode.mode & 0x80) != 0) {
            nMode |= S_IWRITE;
            // }

            // S_IEXEC is not availabile on windows
            // if ((new_attributes.mode.mode & 0x40) != 0) {
            //     nMode |= S_IEXEC;
            // }

            if (_chmod(path, nMode) != 0) {
                stat = NFS3ERR_INVAL;
            } else {

            }
        }   

        // deliberately not implemented because we cannot reflect uid/gid on windows (easliy)
        if (new_attributes.uid.set_it){}
        if (new_attributes.gid.set_it){}

        // deliberately not implemented
        if (new_attributes.mtime.set_it == SET_TO_CLIENT_TIME){}
        if (new_attributes.atime.set_it == SET_TO_CLIENT_TIME){}

        if (new_attributes.mtime.set_it == SET_TO_SERVER_TIME || new_attributes.atime.set_it == SET_TO_SERVER_TIME){
            hFile = CreateFile(path, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
            if (hFile != INVALID_HANDLE_VALUE) {
                GetSystemTime(&systemTime);
                SystemTimeToFileTime(&systemTime, &fileTime);
                if (new_attributes.mtime.set_it == SET_TO_SERVER_TIME){
                    SetFileTime(hFile, NULL, NULL, &fileTime);
                }
                if (new_attributes.atime.set_it == SET_TO_SERVER_TIME){
                    SetFileTime(hFile, NULL, &fileTime, NULL);
                }
            }
            CloseHandle(hFile);
        }

        if (new_attributes.size.set_it){
            pFile = _fsopen(path, "r+b", _SH_DENYWR);
            int filedes = _fileno(pFile);
            _chsize_s(filedes, new_attributes.size.size);
            fclose(pFile);
        }
    }

    obj_wcc.after.attributes_follow = GetFileAttributesForNFS(path, &obj_wcc.after.attributes);

    Write(&stat);
    Write(&obj_wcc);

    return stat;
}
예제 #6
0
 /******************************************************************************
     TerEnableTracking:
     Enable or disable tracking of text changes.  This function returns the
     previous status.
 ******************************************************************************/
 BOOL WINAPI _export TerEnableTracking(HWND hWnd, bool enable, LPBYTE UName, BOOL UseDefaultClrStyle,
     DWORD InsStyle, COLORREF InsColor, DWORD DelStyle, COLORREF DelColor)
 {
     BYTE name[UNLEN+1];
     LPBYTE pName=null;
     int  i,len;
     SYSTEMTIME SysTime;
     FILETIME  FileTime;
     WORD DosDate,DosTime;
     bool NewUser=false;

     PTERWND w;

     if (NULL==(w=GetWindowPointer(hWnd))) return false;  // get the pointer to window data

     if (!TerArg.WordWrap) return false;

     if (TrackChanges == enable) return true;   // no status change requested

     TrackChanges=enable;

     if (enable) {
        if (UName && lstrlen(UName)>0) pName=UName;
        else {  // get system user name
          len=UNLEN;
          name[0]=0;
          GetUserName(name,&len);
          if (len>49) len=49;   // StrReviewer limit
          name[len]=0;
          pName=name;
        }

        // check if this reviewer exists
        for (i=1;i<TotalReviewers;i++) if (lstrcmpi(reviewer[i].name,pName)==0) break;

        if (i==TotalReviewers) {
           i=GetReviewerSlot(w);
           lstrncpy(reviewer[i].name,pName,49);  // copy name
           reviewer[i].name[49]=0;
           NewUser=true;

        }
        
        if (!UseDefaultClrStyle) {
           reviewer[i].InsStyle=InsStyle;
           reviewer[i].DelStyle=DelStyle;

           reviewer[i].InsColor=InsColor;
           reviewer[i].DelColor=DelColor;
           reviewer[i].FmtColor=InsColor;
        } 
        
        TrackRev=i;   // current reviewer id

        // get the current date/time as DWORD
        GetLocalTime(&SysTime);
        SystemTimeToFileTime(&SysTime,&FileTime);
        FileTimeToDosDateTime(&FileTime,&DosDate,&DosTime);
        TrackTime=(((DWORD)DosDate)<<16)+DosTime;

        InsertMode=true;              // insert mode always true when tracking

        if (!NewUser) {               // font/style might have changed, so recreate the fonts
           RecreateFonts(w,hTerDC);
           RequestPagination(w,true);
           PaintTer(w);
        }     
     } 
     else {
        TrackRev=0;
        TrackTime=0;
     } 
     return true;
 }
예제 #7
0
파일: Time.cpp 프로젝트: 0vermind/NeoLoader
void GetCurUtcFileTime(FILETIME &ft)
{
  SYSTEMTIME st;
  GetSystemTime(&st);
  SystemTimeToFileTime(&st, &ft);
}
예제 #8
0
// update an alarm so that the systemtime reflects the next time the alarm will go off, based on the last_check time
bool UpdateAlarm(SYSTEMTIME &time, Occurrence occ) {

	FILETIME ft_now, ft_then;
	ULARGE_INTEGER uli_then;

	switch(occ) {
	case OC_DAILY:
	case OC_WEEKDAYS:
	case OC_WEEKLY:
		time.wDay = last_check.wDay;
	case OC_MONTHLY:
		time.wMonth = last_check.wMonth;
	case OC_YEARLY:
		time.wYear = last_check.wYear;
	case OC_ONCE:
		break; // all fields valid
	};

	SystemTimeToFileTime(&last_check, &ft_now); // consider 'now' to be last check time
	SystemTimeToFileTime(&time, &ft_then);
	
	switch(occ) {
	case OC_ONCE:
		if (CompareFileTime(&ft_then, &ft_now) < 0)
			return false;
		break;
	case OC_YEARLY:
		while(CompareFileTime(&ft_then, &ft_now) < 0) {
			time.wYear++;
			SystemTimeToFileTime(&time, &ft_then);
		}
		break;
	case OC_MONTHLY:
		while(CompareFileTime(&ft_then, &ft_now) < 0) {
			if (time.wMonth == 12) {
				time.wMonth = 1;
				time.wYear++;
			} else
				time.wMonth++;
			SystemTimeToFileTime(&time, &ft_then);
		}
		break;
	case OC_WEEKLY:
		{
			SYSTEMTIME temp;
			uli_then.HighPart = ft_then.dwHighDateTime;
			uli_then.LowPart = ft_then.dwLowDateTime;
			FileTimeToSystemTime(&ft_then, &temp);
			do {
				if (temp.wDayOfWeek != time.wDayOfWeek || CompareFileTime(&ft_then, &ft_now) < 0) {
					uli_then.QuadPart += mult.QuadPart * (ULONGLONG)24 * (ULONGLONG)60;
					ft_then.dwHighDateTime = uli_then.HighPart;
					ft_then.dwLowDateTime = uli_then.LowPart;
					FileTimeToSystemTime(&ft_then, &temp);
				}
			} while(temp.wDayOfWeek != time.wDayOfWeek || CompareFileTime(&ft_then, &ft_now) < 0);
		}
		break;
	case OC_WEEKDAYS:
		{
			SYSTEMTIME temp;
			uli_then.HighPart = ft_then.dwHighDateTime;
			uli_then.LowPart = ft_then.dwLowDateTime;
			do {
				FileTimeToSystemTime(&ft_then, &temp);
				if (temp.wDayOfWeek == 0 || temp.wDayOfWeek == 6 || CompareFileTime(&ft_then, &ft_now) < 0) {
					uli_then.QuadPart += mult.QuadPart * (ULONGLONG)24 * (ULONGLONG)60;
					ft_then.dwHighDateTime = uli_then.HighPart;
					ft_then.dwLowDateTime = uli_then.LowPart;
				}
			} while(temp.wDayOfWeek == 0 || temp.wDayOfWeek == 6 || CompareFileTime(&ft_then, &ft_now) < 0);
		}
		break;
	case OC_DAILY:
		uli_then.HighPart = ft_then.dwHighDateTime;
		uli_then.LowPart = ft_then.dwLowDateTime;
		while(CompareFileTime(&ft_then, &ft_now) < 0) {
			uli_then.QuadPart += mult.QuadPart * (ULONGLONG)24 * (ULONGLONG)60;
			ft_then.dwHighDateTime = uli_then.HighPart;
			ft_then.dwLowDateTime = uli_then.LowPart;
		}
		break;
	}

	FileTimeToSystemTime(&ft_then, &time);
	return true;
}
예제 #9
0
NTSTATUS TextToFileTime(LPCTSTR szText, PFILETIME pFt)
{
    SYSTEMTIME st = {0};
    FILETIME ft;
    LPTSTR szEndChar = NULL;

    // Prepare the local variables to be filled by callbacks
    bDateConverted = FALSE;
    bTimeConverted = FALSE;
    szTempDateTime = szText;
    pTempSt = &st;

    // First of all, try to convert the filetime from human-readable form
    if(bDateConverted == FALSE)
        EnumDateFormats(EnumDateFormatsProc, LOCALE_USER_DEFAULT, DATE_SHORTDATE);
    if(bDateConverted == FALSE)
        EnumDateFormats(EnumDateFormatsProc, LOCALE_USER_DEFAULT, DATE_LONGDATE);
    if(bTimeConverted == FALSE)
        EnumTimeFormats(EnumTimeFormatsProc, LOCALE_USER_DEFAULT, 0);

    // If both date and time converted, we have succeeded
    if(bDateConverted && bTimeConverted)
    {
        if(!SystemTimeToFileTime(&st, &ft))
            return STATUS_INVALID_DATA_FORMAT;
        if(!LocalFileTimeToFileTime(&ft, pFt))
            return STATUS_INVALID_DATA_FORMAT;
        return STATUS_SUCCESS;
    }

    // Try to convert 64-bit value in the form of ################ or 0x################
    if(Text2Hex64(szText, (PLONGLONG)&ft) != ERROR_SUCCESS)
    {
        // Try to convert the 64-bit value in the form of ########-########
        ft.dwHighDateTime = StrToInt(szText, &szEndChar, 16);
        if(szEndChar == NULL || szEndChar[0] != _T('-'))
            return STATUS_INVALID_DATA_FORMAT;

        ft.dwLowDateTime = StrToInt(szEndChar+1, &szEndChar, 16);
        if(szEndChar[0] != 0 && szEndChar[0] != _T(' '))
            return STATUS_INVALID_DATA_FORMAT;
    }

    // We accept "FFFFFFFF-FFFFFFFF" as input
    if(ft.dwHighDateTime == 0xFFFFFFFF && ft.dwLowDateTime == 0xFFFFFFFF)
    {
        pFt->dwHighDateTime = ft.dwHighDateTime;
        pFt->dwLowDateTime = ft.dwLowDateTime;
        return STATUS_SUCCESS;
    }

    // We accept "00000000-00000000" as input
    if(ft.dwHighDateTime == 0 && ft.dwLowDateTime == 0)
    {
        pFt->dwHighDateTime = ft.dwHighDateTime;
        pFt->dwLowDateTime = ft.dwLowDateTime;
        return STATUS_SUCCESS;
    }

    // Convert from local time to file time
    if(LocalFileTimeToFileTime(&ft, pFt))
        return STATUS_SUCCESS;

    // Conversion failed
    return STATUS_INVALID_DATA_FORMAT;
}
예제 #10
0
/* Generate a temporary file name based on TMPL.  TMPL must match the
   rules for mk[s]temp (i.e. end in "XXXXXX").  The name constructed
   does not exist at the time of the call to mkstemp.  TMPL is
   overwritten with the result.  */
int
mkstemp (char *tmpl)
{
  int len;
  char *XXXXXX;
  static unsigned long long value;
  unsigned long long random_time_bits;
  unsigned int count;
  int fd = -1;
  int save_errno = errno;

  /* A lower bound on the number of temporary files to attempt to
     generate.  The maximum total number of temporary file names that
     can exist for a given template is 62**6.  It should never be
     necessary to try all these combinations.  Instead if a reasonable
     number of names is tried (we define reasonable as 62**3) fail to
     give the system administrator the chance to remove the problems.  */
#define ATTEMPTS_MIN (62 * 62 * 62)

  /* The number of times to attempt to generate a temporary file.  To
     conform to POSIX, this must be no smaller than TMP_MAX.  */
#if ATTEMPTS_MIN < TMP_MAX
  unsigned int attempts = TMP_MAX;
#else
  unsigned int attempts = ATTEMPTS_MIN;
#endif

  len = strlen (tmpl);
  if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
    {
      errno = EINVAL;
      return -1;
    }

/* This is where the Xs start.  */
  XXXXXX = &tmpl[len - 6];

  /* Get some more or less random data.  */
  {
    SYSTEMTIME      stNow;
    FILETIME ftNow;

    // get system time
    GetSystemTime(&stNow);
    stNow.wMilliseconds = 500;
    if (!SystemTimeToFileTime(&stNow, &ftNow))
    {
        errno = -1;
        return -1;
    }

    random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32)
                        | (unsigned long long)ftNow.dwLowDateTime);
  }
  value += random_time_bits ^ (unsigned long long)GetCurrentThreadId ();

  for (count = 0; count < attempts; value += 7777, ++count)
    {
      unsigned long long v = value;

      /* Fill in the random bits.  */
      XXXXXX[0] = letters[v % 62];
      v /= 62;
      XXXXXX[1] = letters[v % 62];
      v /= 62;
      XXXXXX[2] = letters[v % 62];
      v /= 62;
      XXXXXX[3] = letters[v % 62];
      v /= 62;
      XXXXXX[4] = letters[v % 62];
      v /= 62;
      XXXXXX[5] = letters[v % 62];

#define _O_EXCL         0x0400
#define O_EXCL          _O_EXCL
#ifndef O_BINARY
#define O_BINARY        0
#endif
#define _S_IREAD        0000400         /* read permission, owner */
#define _S_IWRITE       0000200         /* write permission, owner */

      fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, _S_IREAD | _S_IWRITE);
      if (fd >= 0)
    {
      errno = save_errno;
      return fd;
    }
      else if (errno != EEXIST)
    return -1;
    }

  /* We got out of the loop because we ran out of combinations to try.  */
  errno = EEXIST;
  return -1;
}
예제 #11
0
static void test_verifyRevocation(void)
{
    HMODULE hCryptNet = GetModuleHandleA("cryptnet.dll");
    BOOL ret;
    CERT_REVOCATION_STATUS status = { sizeof(status), 0 };
    PCCERT_CONTEXT certs[2];
    CERT_REVOCATION_PARA revPara = { sizeof(revPara), 0 };
    FILETIME time;

    pCertVerifyRevocation = (void *)GetProcAddress(hCryptNet,
     "CertDllVerifyRevocation");
    if (!pCertVerifyRevocation)
    {
        win_skip("no CertDllVerifyRevocation\n");
        return;
    }
    if (0)
    {
        /* Crash */
        pCertVerifyRevocation(0, 0, 0, NULL, 0, NULL, NULL);
    }
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(0, 0, 0, NULL, 0, NULL, &status);
    ok(!ret && GetLastError() == E_INVALIDARG,
     "expected E_INVALIDARG, got %08x\n", GetLastError());
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(X509_ASN_ENCODING, 0, 0, NULL, 0, NULL,
     &status);
    ok(!ret && GetLastError() == E_INVALIDARG,
     "expected E_INVALIDARG, got %08x\n", GetLastError());
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(0, CERT_CONTEXT_REVOCATION_TYPE, 0, NULL, 0,
     NULL, &status);
    ok(!ret && GetLastError() == E_INVALIDARG,
     "expected E_INVALIDARG, got %08x\n", GetLastError());
    certs[0] = CertCreateCertificateContext(X509_ASN_ENCODING, bigCert,
     sizeof(bigCert));
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(0, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)certs, 0, NULL, &status);
    ok(!ret && GetLastError() == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", GetLastError());
    ok(status.dwError == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", status.dwError);
    ok(status.dwIndex == 0, "expected index 0, got %d\n", status.dwIndex);
    CertFreeCertificateContext(certs[0]);
    certs[0] = CertCreateCertificateContext(X509_ASN_ENCODING,
     rootWithKeySignAndCRLSign, sizeof(rootWithKeySignAndCRLSign));
    certs[1] = CertCreateCertificateContext(X509_ASN_ENCODING,
     revokedCert, sizeof(revokedCert));
    /* The root cert itself can't be checked for revocation */
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(0, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)certs, 0, NULL, &status);
    ok(!ret && GetLastError() == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", GetLastError());
    ok(status.dwError == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", status.dwError);
    ok(status.dwIndex == 0, "expected index 0, got %d\n", status.dwIndex);
    /* Neither can the end cert */
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(0, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, NULL, &status);
    ok(!ret && GetLastError() == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", GetLastError());
    ok(status.dwError == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", status.dwError);
    ok(status.dwIndex == 0, "expected index 0, got %d\n", status.dwIndex);
    /* Both certs together can't, either (they're not CRLs) */
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(0, CERT_CONTEXT_REVOCATION_TYPE,
     2, (void **)certs, 0, NULL, &status);
    ok(!ret && GetLastError() == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", GetLastError());
    ok(status.dwError == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", status.dwError);
    ok(status.dwIndex == 0, "expected index 0, got %d\n", status.dwIndex);
    /* Now add a CRL to the hCrlStore */
    revPara.hCrlStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
     CERT_STORE_CREATE_NEW_FLAG, NULL);
    CertAddEncodedCRLToStore(revPara.hCrlStore, X509_ASN_ENCODING,
     rootSignedCRLWithBadAKI, sizeof(rootSignedCRLWithBadAKI),
     CERT_STORE_ADD_ALWAYS, NULL);
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(0, CERT_CONTEXT_REVOCATION_TYPE,
     2, (void **)certs, 0, &revPara, &status);
    ok(!ret && GetLastError() == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", GetLastError());
    ok(status.dwError == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", status.dwError);
    ok(status.dwIndex == 0, "expected index 0, got %d\n", status.dwIndex);
    /* Specifying CERT_VERIFY_REV_CHAIN_FLAG doesn't change things either */
    SetLastError(0xdeadbeef);
    ret = pCertVerifyRevocation(0, CERT_CONTEXT_REVOCATION_TYPE,
     2, (void **)certs, CERT_VERIFY_REV_CHAIN_FLAG, &revPara, &status);
    ok(!ret && GetLastError() == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", GetLastError());
    ok(status.dwError == CRYPT_E_NO_REVOCATION_CHECK,
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", status.dwError);
    ok(status.dwIndex == 0, "expected index 0, got %d\n", status.dwIndex);
    /* Again, specifying the issuer cert: no change */
    revPara.pIssuerCert = certs[0];
    SetLastError(0xdeadbeef);
    ret = CertVerifyRevocation(X509_ASN_ENCODING, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, &revPara, &status);
    /* Win2k thinks the cert is revoked, and it is, except the CRL contains a
     * bad authority key ID extension and can't be matched with the issuer
     * cert, hence the revocation status should be unknown.
     */
    if (!ret && GetLastError() == ERROR_FILE_NOT_FOUND)
    {
        win_skip("CERT_CONTEXT_REVOCATION_TYPE unsupported, skipping\n");
        return;
    }
    ok(!ret && (GetLastError() == CRYPT_E_NO_REVOCATION_CHECK ||
     broken(GetLastError() == CRYPT_E_REVOKED /* Win2k */)),
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", GetLastError());
    ok(status.dwError == CRYPT_E_NO_REVOCATION_CHECK ||
     broken(status.dwError == CRYPT_E_REVOKED /* Win2k */),
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", status.dwError);
    ok(status.dwIndex == 0, "expected index 0, got %d\n", status.dwIndex);
    /* Specifying the time to check: still no change */
    SystemTimeToFileTime(&oct2007, &time);
    revPara.pftTimeToUse = &time;
    ret = pCertVerifyRevocation(X509_ASN_ENCODING, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, &revPara, &status);
    ok(!ret, "Expected failure\n");
    ok(GetLastError() == CRYPT_E_NO_REVOCATION_CHECK ||
     broken(GetLastError() == CRYPT_E_REVOKED), /* W2K SP3/SP4 */
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", GetLastError());
    ok(status.dwError == CRYPT_E_NO_REVOCATION_CHECK ||
     broken(GetLastError() == CRYPT_E_REVOKED), /* W2K SP3/SP4 */
     "expected CRYPT_E_NO_REVOCATION_CHECK, got %08x\n", status.dwError);
    ok(status.dwIndex == 0, "expected index 0, got %d\n", status.dwIndex);
    CertCloseStore(revPara.hCrlStore, 0);
    /* Test again with a valid CRL.  This time, the cert should be revoked when
     * the time is after the validity period of the CRL, or considered
     * "revocation offline" when the checked time precedes the validity
     * period of the CRL.
     */
    revPara.hCrlStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
     CERT_STORE_CREATE_NEW_FLAG, NULL);
    ret = CertAddEncodedCRLToStore(revPara.hCrlStore, X509_ASN_ENCODING,
     rootSignedCRL, sizeof(rootSignedCRL), CERT_STORE_ADD_ALWAYS, NULL);
    ok(ret, "CertAddEncodedCRLToStore failed: %08x\n", GetLastError());
    revPara.pftTimeToUse = NULL;
    SetLastError(0xdeadbeef);
    ret = CertVerifyRevocation(X509_ASN_ENCODING, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, &revPara, &status);
    ok(!ret && (GetLastError() == CRYPT_E_REVOKED ||
     broken(GetLastError() == CRYPT_E_NO_REVOCATION_CHECK /* NT4 */)),
     "expected CRYPT_E_REVOKED, got %08x\n", GetLastError());
    revPara.pftTimeToUse = &time;
    SetLastError(0xdeadbeef);
    ret = CertVerifyRevocation(X509_ASN_ENCODING, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, &revPara, &status);
    ok(!ret && (GetLastError() == CRYPT_E_REVOKED ||
     broken(GetLastError() == CRYPT_E_NO_REVOCATION_CHECK /* NT4 */)),
     "expected CRYPT_E_REVOKED, got %08x\n", GetLastError());
    SystemTimeToFileTime(&may2007, &time);
    SetLastError(0xdeadbeef);
    ret = CertVerifyRevocation(X509_ASN_ENCODING, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, &revPara, &status);
    ok(!ret && (GetLastError() == CRYPT_E_REVOCATION_OFFLINE ||
     broken(GetLastError() == CRYPT_E_NO_REVOCATION_CHECK /* NT4 */)),
     "expected CRYPT_E_REVOCATION_OFFLINE, got %08x\n", GetLastError());
    CertFreeCertificateContext(certs[1]);
    /* Test again with a valid CRL and an un-revoked cert.  No matter the
     * time checked, it's reported as revocation offline.
     */
    certs[1] = CertCreateCertificateContext(X509_ASN_ENCODING,
     unRevokedCert, sizeof(unRevokedCert));
    ok(certs[1] != NULL, "CertCreateCertificateContext failed: %08x\n",
     GetLastError());
    revPara.pftTimeToUse = NULL;
    SetLastError(0xdeadbeef);
    ret = CertVerifyRevocation(X509_ASN_ENCODING, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, &revPara, &status);
    ok(!ret && (GetLastError() == CRYPT_E_REVOCATION_OFFLINE ||
     broken(GetLastError() == CRYPT_E_NO_REVOCATION_CHECK /* NT4 */)),
     "expected CRYPT_E_REVOCATION_OFFLINE, got %08x\n", GetLastError());
    revPara.pftTimeToUse = &time;
    SetLastError(0xdeadbeef);
    ret = CertVerifyRevocation(X509_ASN_ENCODING, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, &revPara, &status);
    ok(!ret && (GetLastError() == CRYPT_E_REVOCATION_OFFLINE ||
     broken(GetLastError() == CRYPT_E_NO_REVOCATION_CHECK /* NT4 */)),
     "expected CRYPT_E_REVOCATION_OFFLINE, got %08x\n", GetLastError());
    SystemTimeToFileTime(&may2007, &time);
    SetLastError(0xdeadbeef);
    ret = CertVerifyRevocation(X509_ASN_ENCODING, CERT_CONTEXT_REVOCATION_TYPE,
     1, (void **)&certs[1], 0, &revPara, &status);
    ok(!ret && (GetLastError() == CRYPT_E_REVOCATION_OFFLINE ||
     broken(GetLastError() == CRYPT_E_NO_REVOCATION_CHECK /* NT4 */)),
     "expected CRYPT_E_REVOCATION_OFFLINE, got %08x\n", GetLastError());
    CertCloseStore(revPara.hCrlStore, 0);
    CertFreeCertificateContext(certs[1]);
    CertFreeCertificateContext(certs[0]);
}
예제 #12
0
void Creds_OnUpdate (HWND hDlg)
{
   LPTSTR pszCell = (LPTSTR)GetWindowLongPtr (hDlg, DWLP_USER);
   if (!pszCell || !*pszCell)
      {
      BOOL fRunning = IsServiceRunning();
      ShowWindow (GetDlgItem (hDlg, IDC_RUNNING), fRunning);
      ShowWindow (GetDlgItem (hDlg, IDC_STOPPED), !fRunning);
      ShowWindow (GetDlgItem (hDlg, IDC_CREDS_OBTAIN), fRunning);
      return;
      }

   lock_ObtainMutex(&g.credsLock);
   size_t iCreds;
   for (iCreds = 0; iCreds < g.cCreds; ++iCreds)
      {
      if (!lstrcmpi (g.aCreds[ iCreds ].szCell, pszCell))
         break;
      }

   TCHAR szGateway[cchRESOURCE] = TEXT("");
   if (!g.fIsWinNT)
      GetGatewayName (szGateway);

   if (!szGateway[0])
      {
      SetDlgItemText (hDlg, IDC_CREDS_CELL, pszCell);
      }
   else
      {
      TCHAR szCell[ cchRESOURCE ];
      TCHAR szFormat[ cchRESOURCE ];
      GetString (szFormat, IDS_CELL_GATEWAY);
      wsprintf (szCell, szFormat, pszCell, szGateway);
      SetDlgItemText (hDlg, IDC_CREDS_CELL, szCell);
      }

   if (iCreds == g.cCreds)
      {
      TCHAR szText[cchRESOURCE];
      GetString (szText, IDS_NO_CREDS);
      SetDlgItemText (hDlg, IDC_CREDS_INFO, szText);
      }
   else
      {
      // FormatString(%t) expects a date in GMT, not the local time zone...
      //
      FILETIME ftLocal;
      SystemTimeToFileTime (&g.aCreds[ iCreds ].stExpires, &ftLocal);

      FILETIME ftGMT;
      LocalFileTimeToFileTime (&ftLocal, &ftGMT);

      SYSTEMTIME stGMT;
      FileTimeToSystemTime (&ftGMT, &stGMT);

      SYSTEMTIME stNow;
      GetLocalTime (&stNow);

      FILETIME ftNow;
      SystemTimeToFileTime (&stNow, &ftNow);

      LONGLONG llNow = (((LONGLONG)ftNow.dwHighDateTime) << 32) + (LONGLONG)(ftNow.dwLowDateTime);
      LONGLONG llExpires = (((LONGLONG)ftLocal.dwHighDateTime) << 32) + (LONGLONG)(ftLocal.dwLowDateTime);

      llNow /= c100ns1SECOND;
      llExpires /= c100ns1SECOND;

      LPTSTR pszCreds = NULL;
      if (llExpires <= (llNow + (LONGLONG)cminREMIND_WARN * csec1MINUTE))
          pszCreds = FormatString (IDS_CREDS_EXPIRED, TEXT("%s"), g.aCreds[ iCreds ].szUser);

      if (!pszCreds || !pszCreds[0])
          pszCreds = FormatString (IDS_CREDS, TEXT("%s%t"), g.aCreds[ iCreds ].szUser, &stGMT);
      SetDlgItemText (hDlg, IDC_CREDS_INFO, pszCreds);
      FreeString (pszCreds);
      }

   lock_ReleaseMutex(&g.credsLock);
   CheckDlgButton (hDlg, IDC_CREDS_REMIND, (iCreds == g.cCreds) ? FALSE : g.aCreds[iCreds].fRemind);

   EnableWindow (GetDlgItem (hDlg, IDC_CREDS_OBTAIN), IsServiceRunning());
   EnableWindow (GetDlgItem (hDlg, IDC_CREDS_REMIND), (iCreds != g.cCreds));
   EnableWindow (GetDlgItem (hDlg, IDC_CREDS_DESTROY), (iCreds != g.cCreds));
}
예제 #13
0
파일: copy.c 프로젝트: hoangduit/reactos
INT
copy(TCHAR source[MAX_PATH],
     TCHAR dest[MAX_PATH],
     INT append,
     DWORD lpdwFlags,
     BOOL bTouch)
{
    FILETIME srctime,NewFileTime;
    HANDLE hFileSrc;
    HANDLE hFileDest;
    LPBYTE buffer;
    DWORD  dwAttrib;
    DWORD  dwRead;
    DWORD  dwWritten;
    BOOL   bEof = FALSE;
    TCHAR TrueDest[MAX_PATH];
    TCHAR TempSrc[MAX_PATH];
    TCHAR * FileName;
    SYSTEMTIME CurrentTime;

    /* Check Breaker */
    if (CheckCtrlBreak(BREAK_INPUT))
        return 0;

    TRACE ("checking mode\n");

    if (bTouch)
    {
        hFileSrc = CreateFile (source, GENERIC_WRITE, FILE_SHARE_READ,
            NULL, OPEN_EXISTING, 0, NULL);
        if (hFileSrc == INVALID_HANDLE_VALUE)
        {
            ConOutResPrintf(STRING_COPY_ERROR1, source);
            nErrorLevel = 1;
            return 0;
        }

        GetSystemTime(&CurrentTime);
        SystemTimeToFileTime(&CurrentTime, &NewFileTime);
        if (SetFileTime(hFileSrc,(LPFILETIME) NULL, (LPFILETIME) NULL, &NewFileTime))
        {
            CloseHandle(hFileSrc);
            nErrorLevel = 1;
            return 1;

        }
        else
        {
            CloseHandle(hFileSrc);
            return 0;
        }
    }

    dwAttrib = GetFileAttributes (source);

    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        nErrorLevel = 1;
        return 0;
    }

    TRACE ("getting time\n");

    GetFileTime (hFileSrc, &srctime, NULL, NULL);

    TRACE ("copy: flags has %s\n",
        lpdwFlags & COPY_ASCII ? "ASCII" : "BINARY");

    /* Check to see if /D or /Z are true, if so we need a middle
       man to copy the file too to allow us to use CopyFileEx later */
    if (lpdwFlags & COPY_DECRYPT)
    {
        GetEnvironmentVariable(_T("TEMP"),TempSrc,MAX_PATH);
        _tcscat(TempSrc,_T("\\"));
        FileName = _tcsrchr(source,_T('\\'));
        FileName++;
        _tcscat(TempSrc,FileName);
        /* This is needed to be on the end to prevent an error
           if the user did "copy /D /Z foo bar then it would be copied
           too %TEMP%\foo here and when %TEMP%\foo when it sets it up
           for COPY_RESTART, this would mean it is copying to itself
           which would error when it tried to open the handles for ReadFile
           and WriteFile */
        _tcscat(TempSrc,_T(".decrypt"));
        if (!CopyFileEx(source, TempSrc, NULL, NULL, FALSE, COPY_FILE_ALLOW_DECRYPTED_DESTINATION))
        {
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
        _tcscpy(source, TempSrc);
    }


    if (lpdwFlags & COPY_RESTART)
    {
        _tcscpy(TrueDest, dest);
        GetEnvironmentVariable(_T("TEMP"),dest,MAX_PATH);
        _tcscat(dest,_T("\\"));
        FileName = _tcsrchr(TrueDest,_T('\\'));
        FileName++;
        _tcscat(dest,FileName);
    }


    if (!IsExistingFile (dest))
    {
        TRACE ("opening/creating\n");
        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else if (!append)
    {
        TRACE ("SetFileAttributes (%s, FILE_ATTRIBUTE_NORMAL);\n", debugstr_aw(dest));
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        TRACE ("DeleteFile (%s);\n", debugstr_aw(dest));
        DeleteFile (dest);

        hFileDest =	CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else
    {
        LONG lFilePosHigh = 0;

        if (!_tcscmp (dest, source))
        {
            CloseHandle (hFileSrc);
            return 0;
        }

        TRACE ("opening/appending\n");
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

        /* Move to end of file to start writing */
        SetFilePointer (hFileDest, 0, &lFilePosHigh,FILE_END);
    }


    if (hFileDest == INVALID_HANDLE_VALUE)
    {
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_PATH_NOT_FOUND);
        nErrorLevel = 1;
        return 0;
    }

    /* A page-aligned buffer usually give more speed */
    buffer = VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
    if (buffer == NULL)
    {
        CloseHandle (hFileDest);
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_OUT_OF_MEMORY);
        nErrorLevel = 1;
        return 0;
    }

    do
    {
        ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);
        if (lpdwFlags & COPY_ASCII)
        {
            LPBYTE pEof = memchr(buffer, 0x1A, dwRead);
            if (pEof != NULL)
            {
                bEof = TRUE;
                dwRead = pEof-buffer+1;
                break;
            }
        }

        if (dwRead == 0)
            break;

        WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);
        if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
        {
            ConOutResPuts(STRING_COPY_ERROR3);

            VirtualFree (buffer, 0, MEM_RELEASE);
            CloseHandle (hFileDest);
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
    }
    while (!bEof);

    TRACE ("setting time\n");
    SetFileTime (hFileDest, &srctime, NULL, NULL);

    if ((lpdwFlags & COPY_ASCII) && !bEof)
    {
        /* we're dealing with ASCII files! */
        buffer[0] = 0x1A;
        TRACE ("appending ^Z\n");
        WriteFile (hFileDest, buffer, sizeof(CHAR), &dwWritten, NULL);
    }

    VirtualFree (buffer, 0, MEM_RELEASE);
    CloseHandle (hFileDest);
    CloseHandle (hFileSrc);

    TRACE ("setting mode\n");
    SetFileAttributes (dest, dwAttrib);

    /* Now finish off the copy if needed with CopyFileEx */
    if (lpdwFlags & COPY_RESTART)
    {
        if (!CopyFileEx(dest, TrueDest, NULL, NULL, FALSE, COPY_FILE_RESTARTABLE))
        {
            nErrorLevel = 1;
            DeleteFile(dest);
            return 0;
        }
        /* Take care of file in the temp folder */
        DeleteFile(dest);

    }

    if (lpdwFlags & COPY_DECRYPT)
        DeleteFile(TempSrc);

    return 1;
}
예제 #14
0
/* A wrapper for gettimeofday so that it can be used on Windows platforms. */
int libhaggle_gettimeofday(struct timeval *tv, void *tz)
{
#ifdef WINCE
    DWORD tickcount, tickcount_diff; // In milliseconds
    /* In Windows CE, GetSystemTime() returns a time accurate only to the second.
    For higher performance timers we need to use something better. */

    // This holds the base time, i.e. the estimated time of boot. This value plus
    // the value the high-performance timer/GetTickCount() provides gives us the
    // right time.
    static struct timeval base_time = { 0, 0};
    static DWORD base_tickcount = 0;

    if (!tv)
        return (-1);

    /* The hardware does not implement a high performance timer.
    Note, the tick counter will wrap around after 49.7 days.
    GetTickCount() returns number of milliseconds since device start.
    */
    tickcount = GetTickCount();

    // Should we determine the base time?
    if (base_tickcount == 0) {
        FILETIME  ft;
        SYSTEMTIME st;
        LARGE_INTEGER date, adjust;

        // Save tickcount
        base_tickcount = tickcount;

        // Find the system time:
        GetSystemTime(&st);
        // Convert it into "file time":
        SystemTimeToFileTime(&st, &ft);

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

        // 11644473600000 is the timestamp of January 1, 1601 (UTC), when
        // FILETIME started.
        // 100-nanoseconds = milliseconds * 10000
        adjust.QuadPart = 11644473600000 * 10000;

        // removes the diff between 1970 and 1601
        date.QuadPart -= adjust.QuadPart;

        // converts back from 100-nanoseconds to seconds and microseconds
        base_time.tv_sec =  (long)(date.QuadPart / 10000000);
        adjust.QuadPart = base_time.tv_sec;

        // convert seconds to 100-nanoseconds
        adjust.QuadPart *= 10000000;

        // Remove the whole seconds
        date.QuadPart -= adjust.QuadPart;

        // Convert the remaining 100-nanoseconds to microseconds
        date.QuadPart /= 10;

        base_time.tv_usec = (long)date.QuadPart;

        printf("base_time: sec:%ld usec:%ld\n", base_time.tv_sec, base_time.tv_usec);
        printf("base_tickcount: %lu\n", tickcount);
    }

    tickcount_diff = tickcount - base_tickcount;
    tv->tv_sec = base_time.tv_sec;
    tv->tv_usec = base_time.tv_usec;

    // Add tickcount to seconds
    while (tickcount_diff >= 1000) {
        tv->tv_sec++;
        tickcount_diff -= 1000;
    }

    // Add remainding milliseconds to the microseconds part
    tv->tv_usec += (tickcount_diff * 1000);

    // If the milliseconds part is larger then 1 sec, adjust
    while (tv->tv_usec >= 1000000) {
        tv->tv_sec++;
        tv->tv_usec -= 1000000;
    }
#else
    FILETIME  ft;
    SYSTEMTIME st;
    LARGE_INTEGER date, adjust;

    if (!tv)
        return (-1);

    GetSystemTime(&st);
    SystemTimeToFileTime(&st, &ft);

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

    // 11644473600000 is the timestamp of January 1, 1601 (UTC), when
    // FILETIME started.
    // 100-nanoseconds = milliseconds * 10000
    adjust.QuadPart = 11644473600000 * 10000;

    // removes the diff between 1970 and 1601
    date.QuadPart -= adjust.QuadPart;

    // converts back from 100-nanoseconds to seconds and microseconds
    tv->tv_sec =  (long)(date.QuadPart / 10000000);
    adjust.QuadPart = tv->tv_sec;

    // convert seconds to 100-nanoseconds
    adjust.QuadPart *= 10000000;

    // Remove the whole seconds
    date.QuadPart -= adjust.QuadPart;

    // Convert the remaining 100-nanoseconds to microseconds
    date.QuadPart /= 10;

    tv->tv_usec = (long)date.QuadPart;
#endif
    return 0;
}
예제 #15
0
/* Creates a file system
 * Make sure the value file_system is referencing, is set to NULL
 * Returns 1 if successful or -1 on error
 */
int mount_file_system_initialize(
     mount_file_system_t **file_system,
     libcerror_error_t **error )
{
#if defined( WINAPI )
	FILETIME filetime;
	SYSTEMTIME systemtime;

#elif defined( HAVE_CLOCK_GETTIME )
	struct timespec time_structure;
#endif

	static char *function = "mount_file_system_initialize";

#if defined( WINAPI )
	DWORD error_code      = 0;
#else
	int64_t timestamp     = 0;
#endif

	if( file_system == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid file system.",
		 function );

		return( -1 );
	}
	if( *file_system != NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET,
		 "%s: invalid file system value already set.",
		 function );

		return( -1 );
	}
	*file_system = memory_allocate_structure(
	                mount_file_system_t );

	if( *file_system == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
		 "%s: unable to create file system.",
		 function );

		goto on_error;
	}
	if( memory_set(
	     *file_system,
	     0,
	     sizeof( mount_file_system_t ) ) == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_SET_FAILED,
		 "%s: unable to clear file system.",
		 function );

		memory_free(
		 *file_system );

		*file_system = NULL;

		return( -1 );
	}
	if( libcdata_array_initialize(
	     &( ( *file_system )->stores_array ),
	     0,
	     error ) != 1 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
		 "%s: unable to initialize stores array.",
		 function );

		goto on_error;
	}
#if defined( WINAPI )
	if( memory_set(
	     &systemtime,
	     0,
	     sizeof( SYSTEMTIME ) ) == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_SET_FAILED,
		 "%s: unable to clear systemtime.",
		 function );

		goto on_error;
	}
	GetSystemTime(
	 &systemtime );

	if( SystemTimeToFileTime(
	     &systemtime,
	     &filetime ) == 0 )
	{
		error_code = GetLastError();

		libcerror_system_set_error(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
		 error_code,
		 "%s: unable to retrieve FILETIME of current time.",
		 function );

		goto on_error;
	}
	( *file_system )->mounted_timestamp = ( (uint64_t) filetime.dwHighDateTime << 32 ) | filetime.dwLowDateTime;

#elif defined( HAVE_CLOCK_GETTIME )
	if( clock_gettime(
	     CLOCK_REALTIME,
	     &time_structure ) != 0 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
		 "%s: unable to retrieve current time structure.",
		 function );

		goto on_error;
	}
	timestamp = ( (int64_t) time_structure.tv_sec * 1000000000 ) + time_structure.tv_nsec;

	( *file_system )->mounted_timestamp = (uint64_t) timestamp;

#else
	timestamp = (int64_t) time( NULL );

	if( timestamp == -1 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
		 "%s: unable to retrieve current time.",
		 function );

		goto on_error;
	}
	timestamp *= 1000000000;

	( *file_system )->mounted_timestamp = (uint64_t) timestamp;

#endif /* defined( HAVE_CLOCK_GETTIME ) */

	return( 1 );

on_error:
	if( *file_system != NULL )
	{
		memory_free(
		 *file_system );

		*file_system = NULL;
	}
	return( -1 );
}
예제 #16
0
void enumerateTasksForFolder(std::string path, QueryData& results) {
  void* vpService = nullptr;
  auto ret = CoCreateInstance(CLSID_TaskScheduler,
                              nullptr,
                              CLSCTX_INPROC_SERVER,
                              IID_ITaskService,
                              &vpService);
  if (FAILED(ret)) {
    VLOG(1) << "Failed to create COM instance " << ret;
    return;
  }

  auto pService = static_cast<ITaskService*>(vpService);
  ret =
      pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());
  if (FAILED(ret)) {
    VLOG(1) << "Failed to connect to TaskService " << ret;
    pService->Release();
    return;
  }

  ITaskFolder* pRootFolder = nullptr;
  auto widePath = stringToWstring(path.c_str());
  ret = pService->GetFolder(BSTR(widePath.c_str()), &pRootFolder);
  pService->Release();
  if (FAILED(ret)) {
    VLOG(1) << "Failed to get root task folder " << ret;
    return;
  }

  IRegisteredTaskCollection* pTaskCollection = nullptr;
  ret = pRootFolder->GetTasks(TASK_ENUM_HIDDEN, &pTaskCollection);
  pRootFolder->Release();
  if (FAILED(ret)) {
    VLOG(1) << "Failed to get task collection for root folder " << ret;
    return;
  }

  long numTasks = 0;
  pTaskCollection->get_Count(&numTasks);
  for (size_t i = 0; i < numTasks; i++) {
    IRegisteredTask* pRegisteredTask = nullptr;
    // Collections are 1-based lists
    ret = pTaskCollection->get_Item(_variant_t(i + 1), &pRegisteredTask);
    if (FAILED(ret)) {
      VLOG(1) << "Failed to process task";
      continue;
    }

    Row r;
    BSTR taskName;
    ret = pRegisteredTask->get_Name(&taskName);
    std::wstring wTaskName(taskName, SysStringLen(taskName));
    r["name"] = ret == S_OK ? SQL_TEXT(wstringToString(wTaskName.c_str())) : "";

    VARIANT_BOOL enabled = false;
    pRegisteredTask->get_Enabled(&enabled);
    r["enabled"] = enabled ? INTEGER(1) : INTEGER(0);

    TASK_STATE taskState;
    pRegisteredTask->get_State(&taskState);
    r["state"] = kStateMap.count(taskState) > 0
                     ? kStateMap.at(taskState)
                     : kStateMap.at(TASK_STATE_UNKNOWN);

    BSTR taskPath;
    ret = pRegisteredTask->get_Path(&taskPath);
    std::wstring wTaskPath(taskPath, SysStringLen(taskPath));
    r["path"] = ret == S_OK ? SQL_TEXT(wstringToString(wTaskPath.c_str())) : "";

    VARIANT_BOOL hidden = false;
    pRegisteredTask->get_Enabled(&hidden);
    r["hidden"] = hidden ? INTEGER(1) : INTEGER(0);

    HRESULT lastTaskRun = E_FAIL;
    pRegisteredTask->get_LastTaskResult(&lastTaskRun);
    _com_error err(lastTaskRun);
    r["last_run_message"] = err.ErrorMessage();
    r["last_run_code"] = INTEGER(lastTaskRun);

    // We conver the COM Date type to a unix epoch timestamp
    DATE dRunTime;
    SYSTEMTIME st;
    FILETIME ft;
    FILETIME locFt;

    pRegisteredTask->get_LastRunTime(&dRunTime);
    VariantTimeToSystemTime(dRunTime, &st);
    SystemTimeToFileTime(&st, &ft);
    LocalFileTimeToFileTime(&ft, &locFt);
    r["last_run_time"] = INTEGER(filetimeToUnixtime(locFt));

    pRegisteredTask->get_NextRunTime(&dRunTime);
    VariantTimeToSystemTime(dRunTime, &st);
    SystemTimeToFileTime(&st, &ft);
    LocalFileTimeToFileTime(&ft, &locFt);
    r["next_run_time"] = INTEGER(filetimeToUnixtime(locFt));

    results.push_back(r);
    pRegisteredTask->Release();
  }
  pTaskCollection->Release();
}
예제 #17
0
int ndisk_dir(Dictionary *dict, const NDiskEntry *entry, NDisk *disk, const wchar_t *path) {
    WIN32_FIND_DATAW fData;
    char *tmp = NULL, *sTmp = NULL;
    wchar_t *pTmp = NULL;
    unsigned long size = 0;
    int i = 0;
    SYSTEMTIME time;
    lua_reset();
    lua_getglobal(script, "entries");
    tmp = wtoc(entry->name);
    lua_getfield(script, -1, tmp);
    free(tmp);
    tmp = NULL;
    i = lua_gettop(script);
    if(lua_pcall(script, 0, 0, 0)) {
        OutputDebugStringA("Error Msg is: ");
        OutputDebugStringA(lua_tostring(script, -1));
    }
    lua_pop(script, 1);
    lua_getglobal(script, "dir");
    if(!lua_isfunction(script, -1)) {
        RequestProcW(PluginNumber, RT_MsgOK, L"ÅäÖôíÎó", L"ÍøÅ̽ű¾´íÎó, ²»ÄܶÁÈ¡µ±Ç°Ä¿Â¼µÄÄÚÈÝ. ", NULL, 0);
        return NDISK_FATAL;
    }
    if(ndisk_lua_push(script, disk) == NDISK_FATAL) {
        lua_settop(script, 0);
        return NDISK_FATAL;
    }
    tmp = wtoc(path);
    lua_pushstring(script, tmp);
    free(tmp);
    tmp = NULL;
    lua_setfield(script, -2, "path");
    if(lua_pcall(script, 1, 1, 0)) {
        OutputDebugStringA("Error Msg is: ");
        OutputDebugStringA(lua_tostring(script, -1));
    }

    if(lua_istable(script, -1)) {
        lua_pushnil(script);
        while (lua_next(script, -2)) {
            if(lua_istable(script, -1)) {
                memset(&fData, 0, sizeof(WIN32_FIND_DATAW));
                lua_pushnil(script);
                while(lua_next(script, -2)) {
                    tmp = (char *)lua_tostring(script, -2);
                    if(strcmp(tmp, "attribute") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        if(strcmp(sTmp, "file") == 0) {
                            fData.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
                        }
                        if(strcmp(sTmp, "directory") == 0) {
                            fData.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
                        }
                    }
                    if(strcmp(tmp, "filename") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        pTmp = ctow(sTmp);
                        wcslcpy(fData.cFileName, pTmp, PATH_MAX);
                        free(pTmp);
                        pTmp = NULL;
                    }
                    if(strcmp(tmp, "size") == 0) {
                        size = (unsigned long)lua_tonumber(script, -1);
                        fData.nFileSizeHigh = HIWORD(size);
                        fData.nFileSizeLow = LOWORD(size);
                    }
                    if(strcmp(tmp, "create") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        pTmp = ctow(sTmp);
                        memset(&time, 0, sizeof(SYSTEMTIME));
                        if(strtotime(pTmp, &time)) {
                            SystemTimeToFileTime(&time, &fData.ftCreationTime);
                        }
                        free(pTmp);
                        pTmp = NULL;
                    }
                    if(strcmp(tmp, "access") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        pTmp = ctow(sTmp);
                        memset(&time, 0, sizeof(SYSTEMTIME));
                        if(strtotime(pTmp, &time)) {
                            SystemTimeToFileTime(&time, &fData.ftLastAccessTime);
                        }
                        free(pTmp);
                        pTmp = NULL;
                    }
                    if(strcmp(tmp, "write") == 0) {
                        sTmp = (char *)lua_tostring(script, -1);
                        pTmp = ctow(sTmp);
                        memset(&time, 0, sizeof(SYSTEMTIME));
                        if(strtotime(pTmp, &time)) {
                            SystemTimeToFileTime(&time, &fData.ftLastWriteTime);
                        }
                        free(pTmp);
                        pTmp = NULL;
                    }
                    lua_pop(script, 1);
                }
                if(fData.cFileName) {
                    dict_set_element(dict, fData.cFileName, &fData, sizeof(WIN32_FIND_DATAW));
                }
            }
            lua_pop(script, 1);
        }
    }
    lua_pop(script, 1);
    return NDISK_OK;
}
예제 #18
0
파일: jobs.c 프로젝트: reactos/reactos
static DWORD
_LocalGetJobLevel2(PLOCAL_PRINTER_HANDLE pPrinterHandle, PLOCAL_JOB pJob, PBYTE* ppStart, PBYTE* ppEnd, DWORD cbBuf, PDWORD pcbNeeded)
{
    DWORD cbDatatype = (wcslen(pJob->pwszDatatype) + 1) * sizeof(WCHAR);
    DWORD cbDevMode = pJob->pDevMode->dmSize + pJob->pDevMode->dmDriverExtra;
    DWORD cbDocumentName = 0;
    DWORD cbDriverName = (wcslen(pJob->pPrinter->pwszPrinterDriver) + 1) * sizeof(WCHAR);
    DWORD cbMachineName = (wcslen(pJob->pwszMachineName) + 1) * sizeof(WCHAR);
    DWORD cbNotifyName = 0;
    DWORD cbPrinterName = (wcslen(pJob->pPrinter->pwszPrinterName) + 1) * sizeof(WCHAR);
    DWORD cbPrintProcessor = (wcslen(pJob->pPrintProcessor->pwszName) + 1) * sizeof(WCHAR);
    DWORD cbPrintProcessorParameters = 0;
    DWORD cbStatus = 0;
    DWORD cbUserName = 0;
    DWORD dwErrorCode;
    FILETIME ftNow;
    FILETIME ftSubmitted;
    JOB_INFO_2W JobInfo2 = { 0 };
    ULARGE_INTEGER uliNow;
    ULARGE_INTEGER uliSubmitted;

    // Calculate the lengths of the optional values.
    if (pJob->pwszDocumentName)
        cbDocumentName = (wcslen(pJob->pwszDocumentName) + 1) * sizeof(WCHAR);

    if (pJob->pwszNotifyName)
        cbNotifyName = (wcslen(pJob->pwszNotifyName) + 1) * sizeof(WCHAR);

    if (pJob->pwszPrintProcessorParameters)
        cbPrintProcessorParameters = (wcslen(pJob->pwszPrintProcessorParameters) + 1) * sizeof(WCHAR);

    if (pJob->pwszStatus)
        cbStatus = (wcslen(pJob->pwszStatus) + 1) * sizeof(WCHAR);

    if (pJob->pwszUserName)
        cbUserName = (wcslen(pJob->pwszUserName) + 1) * sizeof(WCHAR);

    // Check if the supplied buffer is large enough.
    *pcbNeeded += sizeof(JOB_INFO_2W) + cbDatatype + cbDevMode + cbDocumentName + cbDriverName + cbMachineName + cbNotifyName + cbPrinterName + cbPrintProcessor + cbPrintProcessorParameters + cbStatus + cbUserName;
    if (cbBuf < *pcbNeeded)
    {
        dwErrorCode = ERROR_INSUFFICIENT_BUFFER;
        goto Cleanup;
    }

    // Put the strings at the end of the buffer.
    *ppEnd -= cbDatatype;
    JobInfo2.pDatatype = (PWSTR)*ppEnd;
    CopyMemory(*ppEnd, pJob->pwszDatatype, cbDatatype);

    *ppEnd -= cbDevMode;
    JobInfo2.pDevMode = (PDEVMODEW)*ppEnd;
    CopyMemory(*ppEnd, pJob->pDevMode, cbDevMode);

    *ppEnd -= cbDriverName;
    JobInfo2.pDriverName = (PWSTR)*ppEnd;
    CopyMemory(*ppEnd, pJob->pPrinter->pwszPrinterDriver, cbDriverName);

    *ppEnd -= cbMachineName;
    JobInfo2.pMachineName = (PWSTR)*ppEnd;
    CopyMemory(*ppEnd, pJob->pwszMachineName, cbMachineName);

    *ppEnd -= cbPrinterName;
    JobInfo2.pPrinterName = (PWSTR)*ppEnd;
    CopyMemory(*ppEnd, pJob->pPrinter->pwszPrinterName, cbPrinterName);

    *ppEnd -= cbPrintProcessor;
    JobInfo2.pPrintProcessor = (PWSTR)*ppEnd;
    CopyMemory(*ppEnd, pJob->pPrintProcessor->pwszName, cbPrintProcessor);

    // Copy the optional values.
    if (cbDocumentName)
    {
        *ppEnd -= cbDocumentName;
        JobInfo2.pDocument = (PWSTR)*ppEnd;
        CopyMemory(*ppEnd, pJob->pwszDocumentName, cbDocumentName);
    }

    if (cbNotifyName)
    {
        *ppEnd -= cbNotifyName;
        JobInfo2.pNotifyName = (PWSTR)*ppEnd;
        CopyMemory(*ppEnd, pJob->pwszNotifyName, cbNotifyName);
    }

    if (cbPrintProcessorParameters)
    {
        *ppEnd -= cbPrintProcessorParameters;
        JobInfo2.pParameters = (PWSTR)*ppEnd;
        CopyMemory(*ppEnd, pJob->pwszPrintProcessorParameters, cbPrintProcessorParameters);
    }

    if (cbStatus)
    {
        *ppEnd -= cbStatus;
        JobInfo2.pStatus = (PWSTR)*ppEnd;
        CopyMemory(*ppEnd, pJob->pwszStatus, cbStatus);
    }

    if (cbUserName)
    {
        *ppEnd -= cbUserName;
        JobInfo2.pUserName = (PWSTR)*ppEnd;
        CopyMemory(*ppEnd, pJob->pwszUserName, cbUserName);
    }

    // Time in JOB_INFO_2W is the number of milliseconds elapsed since the job was submitted. Calculate this time.
    if (!SystemTimeToFileTime(&pJob->stSubmitted, &ftSubmitted))
    {
        ERR("SystemTimeToFileTime failed with error %lu!\n", GetLastError());
        return FALSE;
    }

    GetSystemTimeAsFileTime(&ftNow);
    uliSubmitted.LowPart = ftSubmitted.dwLowDateTime;
    uliSubmitted.HighPart = ftSubmitted.dwHighDateTime;
    uliNow.LowPart = ftNow.dwLowDateTime;
    uliNow.HighPart = ftNow.dwHighDateTime;
    JobInfo2.Time = (DWORD)((uliNow.QuadPart - uliSubmitted.QuadPart) / 10000);

    // Position in JOB_INFO_2W is the 1-based index of the job in the processing queue.
    // Retrieve this through the element index of the job in the Printer's Job List.
    if (!LookupElementSkiplist(&pJob->pPrinter->JobList, pJob, &JobInfo2.Position))
    {
        dwErrorCode = ERROR_NOT_ENOUGH_MEMORY;
        ERR("pJob could not be located in the Printer's Job List!\n");
        goto Cleanup;
    }

    // Make the index 1-based.
    ++JobInfo2.Position;

    // Fill the rest of the structure.
    JobInfo2.JobId = pJob->dwJobID;
    JobInfo2.PagesPrinted = pJob->dwPagesPrinted;
    JobInfo2.Priority = pJob->dwPriority;
    JobInfo2.StartTime = pJob->dwStartTime;
    JobInfo2.Status = pJob->dwStatus;
    JobInfo2.TotalPages = pJob->dwTotalPages;
    JobInfo2.UntilTime = pJob->dwUntilTime;
    CopyMemory(&JobInfo2.Submitted, &pJob->stSubmitted, sizeof(SYSTEMTIME));

    // Finally copy the structure to the output pointer.
    CopyMemory(*ppStart, &JobInfo2, sizeof(JOB_INFO_2W));
    *ppStart += sizeof(JOB_INFO_2W);
    dwErrorCode = ERROR_SUCCESS;

Cleanup:
    return dwErrorCode;
}
예제 #19
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;
	}
예제 #20
0
void NaClTimeInternalInit(struct NaClTimeState *ntsp) {
  TIMECAPS    tc;
  SYSTEMTIME  st;
  FILETIME    ft;
  LARGE_INTEGER qpc_freq;

  /*
   * Maximize timer/Sleep resolution.
   */
  timeGetDevCaps(&tc, sizeof tc);

  if (ntsp->allow_low_resolution) {
    /* Set resolution to max so we don't over-promise. */
    ntsp->wPeriodMin = tc.wPeriodMax;
  } else {
    ntsp->wPeriodMin = tc.wPeriodMin;
    timeBeginPeriod(ntsp->wPeriodMin);
    NaClLog(4, "NaClTimeInternalInit: timeBeginPeriod(%u)\n", ntsp->wPeriodMin);
  }
  ntsp->time_resolution_ns = ntsp->wPeriodMin * NACL_NANOS_PER_MILLI;

  /*
   * Compute Unix epoch start; calibrate high resolution clock.
   */
  st.wYear = 1970;
  st.wMonth = 1;
  st.wDay = 1;
  st.wHour = 0;
  st.wMinute = 0;
  st.wSecond = 0;
  st.wMilliseconds = 0;
  SystemTimeToFileTime(&st, &ft);
  ntsp->epoch_start_ms = NaClFileTimeToMs(&ft);
  NaClLog(4, "Unix epoch start is  %"NACL_PRIu64"ms in Windows epoch time\n",
          ntsp->epoch_start_ms);

  NaClMutexCtor(&ntsp->mu);

  /*
   * We don't actually grab the lock, since the module initializer
   * should be called before going threaded.
   */
  ntsp->can_use_qpc = 0;
  if (!ntsp->allow_low_resolution) {
    ntsp->can_use_qpc = QueryPerformanceFrequency(&qpc_freq);
    /*
     * On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is
     * unreliable.  Fallback to low-res clock.
     */
    if (strstr(CPU_GetBrandString(), "AuthenticAMD") && (CPU_GetFamily() == 15))
        ntsp->can_use_qpc = 0;

    NaClLog(4,
            "CPU_GetBrandString->[%s] ntsp->can_use_qpc=%d\n",
            CPU_GetBrandString(),
            ntsp->can_use_qpc);

    if (ntsp->can_use_qpc) {
      ntsp->qpc_frequency = qpc_freq.QuadPart;
      NaClLog(4, "qpc_frequency = %"NACL_PRId64" (counts/s)\n",
              ntsp->qpc_frequency);
      if (!NaClCalibrateWindowsClockQpc(ntsp))
        ntsp->can_use_qpc = 0;
    }
    if (!ntsp->can_use_qpc)
      NaClCalibrateWindowsClockMu(ntsp);
  }
}
예제 #21
0
파일: main.cpp 프로젝트: Joker-vD/sntlm
int wmain (int argc, wchar_t **argv) {
	win32_exception::setCodePage(CP_OEMCP);
	try {
		WS32 _______;

		std::wstring domain(L"TMG"), hostname(L"PC0048");

		TcpClientSocket socket("10.12.0.60", 8080);
		ntlm_request_t request(narrow(domain), narrow(hostname));

		std::stringstream temp;
		temp << request;
		std::string temps = temp.str();

		std::string http_request_start = 
			"GET http://www.yandex.ru/ HTTP/1.1\r\n"
			"Host: www.yandex.ru\r\n"
			//"Connection: close\r\n"
			;

		std::string proxy_auth = "Proxy-Authorization: NTLM ";

		std::string http_request;
		http_request 
			= http_request_start 
			+ proxy_auth 
			+ base64_encode(std::begin(temps), std::end(temps)) 
			+ "\r\n\r\n";

		std::cout << http_request << "======END OF REQUEST======" << std::endl;

		socket.send(std::begin(http_request), std::end(http_request));

		//		std::vector<BYTE> response(8 * 1024, 0);
		//		auto last = std::end(response);
		//		for (auto it = std::begin(response), eit = std::end(response); it != last; last = it, it = socket.recv_upto(it, eit));
		HttpResponse response(socket);

		print_response(response, socket);

		auto headers = response.getHeaders();

		auto proxyauth = headers.find("Proxy-Authenticate");
		if (std::end(headers) == proxyauth) {
			std::cout << "Expected a Proxy-Authenticate header in response" << std::endl;
			return 1;
		}
		if (proxyauth->second.size() > 1) {
			std::cout << "Multiple Proxy-Authenticate headers are not allowed" << std::endl;
			return 2;
		}
		if (proxyauth->second.begin()->substr(0, 5) != "NTLM ") {
			std::cout << "Expected NTLM token in Proxy-Authenticate header" << std::endl;
			return 3;
		}

		std::string tmp = proxyauth->second.begin()->substr(5);
		std::vector<BYTE> challenge = base64_decode(std::begin(tmp), std::end(tmp));

		size_t challen = challenge.size();
		if (challen <= 48) {
			std::cout << "NTLM challenge message is too short" << std::endl;
			return 4;
		}

		unsigned short tbofs, tpos, ttype = 0, tblen = 0;

		tbofs = tpos = challenge[44] | (challenge[45] << 8);
		while (tpos + 4 <= challen && (ttype = challenge[tpos] | (challenge[tpos + 1] << 8))) {
			unsigned short tlen = challenge[tpos + 2] | (challenge[tpos + 3] << 8);
			if (tpos + 4 + tlen > challen)
				break;

			tpos += 4 + tlen;
			tblen += 4 + tlen;
		}

		if (tblen && ttype == 0)
			tblen += 4;

		CryptoProvider provider;

		std::string username, password;


		std::cout << "Enter the username: "******"Enter the password: "******"NTLMSSP\0", 8);
		*(DWORD*)&ntlm_resp[8] = 3;

		*(WORD*)&ntlm_resp[12] = lmhash.size();
		*(WORD*)&ntlm_resp[14] = lmhash.size();
		*(DWORD*)&ntlm_resp[16] = 64 + dlen + ulen + hlen;

		*(WORD*)&ntlm_resp[20] = nthash.size();
		*(WORD*)&ntlm_resp[22] = nthash.size();
		*(DWORD*)&ntlm_resp[24] = 64 + dlen + ulen + hlen + lmhash.size();

		*(WORD*)&ntlm_resp[28] = dlen;
		*(WORD*)&ntlm_resp[30] = dlen;
		*(DWORD*)&ntlm_resp[32] = 64;

		*(WORD*)&ntlm_resp[36] = ulen;
		*(WORD*)&ntlm_resp[38] = ulen;
		*(DWORD*)&ntlm_resp[40] = 64 + dlen;

		*(WORD*)&ntlm_resp[44] = hlen;
		*(WORD*)&ntlm_resp[46] = hlen;
		*(WORD*)&ntlm_resp[48] = 64 + dlen + ulen;

		/* Session */
		*(WORD*)&ntlm_resp[52] = 0;
		*(WORD*)&ntlm_resp[54] = 0;
		*(DWORD*)&ntlm_resp[56] = 64 + dlen + ulen + hlen + lmhash.size() + nthash.size();

		/* Flags */
		*(DWORD*)&ntlm_resp[60] = *(DWORD*)&challenge[20];

		memcpy(&ntlm_resp[64], domain.data(), dlen);
		memcpy(&ntlm_resp[64 + dlen], wusername.data(), ulen);
		memcpy(&ntlm_resp[64 + dlen + ulen], hostname.data(), hlen);
		memcpy(&ntlm_resp[64 + dlen + ulen + hlen], lmhash.data(), lmhash.size());
		memcpy(&ntlm_resp[64 + dlen + ulen + hlen + lmhash.size()], nthash.data(), nthash.size());

		std::string z = base64_encode(ntlm_resp.begin(), ntlm_resp.end());

		http_request 
			= http_request_start 
			+ proxy_auth 
			+ z + "\r\n\r\n";

		std::cout << http_request << "======END OF REQUEST======" << std::endl;

		socket.send(http_request.begin(), http_request.end());

		HttpResponse second_resp(socket);
		print_response(second_resp, socket);

		{
			http_request = "GET http://mail.ru/ HTTP/1.1\r\nHost: mail.ru\r\n\r\n";
			socket.send(http_request.begin(), http_request.end());
			HttpResponse r(socket);
			print_response(r, socket);
		}
	}
	catch (std::exception& e) {
		std::cout << e.what() << std::endl;
	}

	return 0;
}
BOOL CSpiderAddPageDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();

	if (m_pUiWindow)
		m_pUiWindow->setWindow (m_hWnd);

	
	
	
	
	
	m_schScheduleParam.schTask.hts.enType = HTS_ONCE;
	m_schScheduleParam.schTask.hts.last.dwHighDateTime = m_schScheduleParam.schTask.hts.last.dwLowDateTime = UINT_MAX;
	m_schScheduleParam.schTask.dwFlags = SCHEDULE_ENABLED;
	SYSTEMTIME time;
	GetLocalTime (&time);
	if (++time.wHour > 23)
		time.wHour = 0;
	time.wMinute = 0;
	SystemTimeToFileTime (&time, &m_schScheduleParam.schTask.hts.next);
	m_schScheduleParam.schTask.uWaitForConfirmation = 0;

	m_btnChooseFolder.SetIcon (SICO (IDI_CHOOSEFOLDER));
	m_btnCreateGroup.SetIcon (SICO (IDI_CREATEGROUP));
	m_btnSetTime.SetIcon (SICO (IDI_SETTIME));
	m_btnOutFolderSetDefault.SetIcon (SICO (IDI_SETFOLDERDEFAULT));

	m_wndGroups.Fill ();
	m_wndGroups.SelectGroupById (_App.CreateDld_IdOfLastGrpSelected ());

	CheckDlgButton (IDC_KEEP, _App.Spider_Flags () & WPDF_KEEPFOLDERSTRUCTURE ? 
						BST_CHECKED : BST_UNCHECKED);

	CheckDlgButton (IDC_DONTSTOREPAGES, _App.Spider_Flags () & WPDF_DONTSTOREPAGES ? 
						BST_CHECKED : BST_UNCHECKED);

	CheckDlgButton (IDC_DELCOMPLETED, _App.Spider_Flags () & WPDF_DELCOMPLETEDDLDS ?
						BST_CHECKED : BST_UNCHECKED);

	CComboBox *pUrls = (CComboBox*) GetDlgItem (IDC_URL);
	int i = 0;
	for (i = 0; i < _LastUrlFiles.GetRecordCount (); i++)
		pUrls->AddString (_LastUrlFiles.GetRecord (i));

	if (m_strStartUrl.GetLength () == 0)
	{
		LPCSTR pszUrl = _ClipbrdMgr.Text ();
		if (pszUrl)
		{
			fsURL url;
			if (url.Crack (pszUrl) == IR_SUCCESS)
				m_strUrl = pszUrl;
		}
		
		if (m_strUrl.GetLength () == 0)
			m_strUrl = "http://";
	}
	else
		m_strUrl = m_strStartUrl;

	pUrls->SetWindowText (m_strUrl);

	CComboBox *pDirs = (CComboBox*) GetDlgItem (IDC_OUTFOLDER);
	for (i = 0; i < _LastFolders.GetRecordCount (); i++)
		pDirs->AddString (_LastFolders.GetRecord (i));

	GetDlgItem (IDC_URL)->SetFocus ();

	m_bOutFolderChanged = m_bGroupChanged = FALSE;

	ReadAutostart ();
	ApplyLanguage ();

	if (m_bReqTopMost)
	{
		fsSetForegroundWindow (m_hWnd);
        mfcSetTopmostWindow (this);
	}

	m_wndDepthSpin.SetRange (0, UD_MAXVAL);
	SetDlgItemInt (IDC_DEPTH, m_wpd->GetWDPS ()->iDepth);

	if (m_wndGroups.SelectGroupById (_App.NewDL_GroupId ()))
		m_bGroupChanged = TRUE;

	OnChangeGroups ();

	BuildOutFolder ();

	UpdateEnabled ();

	return TRUE;  
	              
}
예제 #23
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 defined( PLATFORM_XBOX) || defined( PLATFORM_WIN32) || defined( PLATFORM_POCKETPC)
    /*
    * 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 practice, 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 // !(defined( PLATFORM_WIN32) || defined( PLATFORM_POCKETPC))
    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) + ((tv.tv_usec)/1000) / 1000.0;
#endif // !(defined( PLATFORM_WIN32) || defined( PLATFORM_POCKETPC))
}
예제 #24
0
파일: timefn.cpp 프로젝트: Armada651/mpc-hc
void RarTime::GetLocal(RarLocalTime *lt)
{
#ifdef _WIN_ALL
  FILETIME ft;
  GetWin32(&ft);
  FILETIME lft;

  if (WinNT() < WNT_VISTA)
  {
    // SystemTimeToTzSpecificLocalTime based code produces 1 hour error on XP.
    FileTimeToLocalFileTime(&ft,&lft);
  }
  else
  {
    // We use these functions instead of FileTimeToLocalFileTime according to
    // MSDN recommendation: "To account for daylight saving time
    // when converting a file time to a local time ..."
    SYSTEMTIME st1,st2;
    FileTimeToSystemTime(&ft,&st1);
    SystemTimeToTzSpecificLocalTime(NULL,&st1,&st2);
    SystemTimeToFileTime(&st2,&lft);

    // Correct precision loss (low 4 decimal digits) in FileTimeToSystemTime.
    FILETIME rft;
    SystemTimeToFileTime(&st1,&rft);
    int64 Corrected=INT32TO64(ft.dwHighDateTime,ft.dwLowDateTime)-
                    INT32TO64(rft.dwHighDateTime,rft.dwLowDateTime)+
                    INT32TO64(lft.dwHighDateTime,lft.dwLowDateTime);
    lft.dwLowDateTime=(DWORD)Corrected;
    lft.dwHighDateTime=(DWORD)(Corrected>>32);
  }

  SYSTEMTIME st;
  FileTimeToSystemTime(&lft,&st);
  lt->Year=st.wYear;
  lt->Month=st.wMonth;
  lt->Day=st.wDay;
  lt->Hour=st.wHour;
  lt->Minute=st.wMinute;
  lt->Second=st.wSecond;
  lt->wDay=st.wDayOfWeek;
  lt->yDay=lt->Day-1;

  static int mdays[12]={31,28,31,30,31,30,31,31,30,31,30,31};
  for (uint I=1;I<lt->Month && I<=ASIZE(mdays);I++)
    lt->yDay+=mdays[I-1];

  if (lt->Month>2 && IsLeapYear(lt->Year))
    lt->yDay++;

  st.wMilliseconds=0;
  FILETIME zft;
  SystemTimeToFileTime(&st,&zft);

  // Calculate the time reminder, which is the part of time smaller
  // than 1 second, represented in 100-nanosecond intervals.
  lt->Reminder=INT32TO64(lft.dwHighDateTime,lft.dwLowDateTime)-
               INT32TO64(zft.dwHighDateTime,zft.dwLowDateTime);
#else
  time_t ut=GetUnix();
  struct tm *t;
  t=localtime(&ut);

  lt->Year=t->tm_year+1900;
  lt->Month=t->tm_mon+1;
  lt->Day=t->tm_mday;
  lt->Hour=t->tm_hour;
  lt->Minute=t->tm_min;
  lt->Second=t->tm_sec;
  lt->Reminder=itime % 10000000;
  lt->wDay=t->tm_wday;
  lt->yDay=t->tm_yday;
#endif
}
예제 #25
0
파일: net.c 프로젝트: DataIsGold/rufus
/*
 * Background thread to check for updates
 */
static DWORD WINAPI CheckForUpdatesThread(LPVOID param)
{
	BOOL releases_only, found_new_version = FALSE;
	int status = 0;
	const char* server_url = RUFUS_URL "/";
	int i, j, k, verbose = 0, verpos[4];
	static const char* archname[] = {"win_x86", "win_x64"};
	static const char* channel[] = {"release", "beta"};		// release channel
	const char* accept_types[] = {"*/*\0", NULL};
	DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus;
	char* buf = NULL;
	char agent[64], hostname[64], urlpath[128], mime[32];
	OSVERSIONINFOA os_version = {sizeof(OSVERSIONINFOA), 0, 0, 0, 0, ""};
	HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL;
	URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0,
		hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1};
	SYSTEMTIME ServerTime, LocalTime;
	FILETIME FileTime;
	int64_t local_time = 0, reg_time, server_time, update_interval;

	update_check_in_progress = TRUE;
	verbose = ReadRegistryKey32(REGKEY_HKCU, REGKEY_VERBOSE_UPDATES);
	// Unless the update was forced, wait a while before performing the update check
	if (!force_update_check) {
		// TODO: Also check on inactivity
		// It would of course be a lot nicer to use a timer and wake the thread, but my
		// development time is limited and this is FASTER to implement.
		do {
			for (i=0; (i<30) && (!force_update_check); i++)
				Sleep(500);
		} while ((!force_update_check) && ((iso_op_in_progress || format_op_in_progress || (dialog_showing>0))));
		if (!force_update_check) {
			if ((ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL) == -1)) {
				vuprintf("Check for updates disabled, as per registry settings.\n");
				goto out;
			}
			reg_time = ReadRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE);
			update_interval = (int64_t)ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL);
			if (update_interval == 0) {
				WriteRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL);
				update_interval = DEFAULT_UPDATE_INTERVAL;
			}
			GetSystemTime(&LocalTime);
			if (!SystemTimeToFileTime(&LocalTime, &FileTime))
				goto out;
			local_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000;
			vvuprintf("Local time: %" PRId64 "\n", local_time);
			if (local_time < reg_time + update_interval) {
				vuprintf("Next update check in %" PRId64 " seconds.\n", reg_time + update_interval - local_time);
				goto out;
			}
		}
	}

	PrintStatus(3000, TRUE, MSG_243);
	status++;	// 1

	if (!GetVersionExA(&os_version)) {
		uprintf("Could not read Windows version - Check for updates cancelled.\n");
		goto out;
	}

	if ((!InternetCrackUrlA(server_url, (DWORD)safe_strlen(server_url), 0, &UrlParts)) || (!InternetGetConnectedState(&dwFlags, 0)))
		goto out;
	hostname[sizeof(hostname)-1] = 0;

	safe_sprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d.%d", rufus_version[0], rufus_version[1], rufus_version[2], rufus_version[3]);
	hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hSession == NULL)
		goto out;
	hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL);
	if (hConnection == NULL)
		goto out;

	status++;	// 2
	releases_only = !GetRegistryKeyBool(REGKEY_HKCU, REGKEY_INCLUDE_BETAS);

	for (k=0; (k<(releases_only?1:(int)ARRAYSIZE(channel))) && (!found_new_version); k++) {
		uprintf("Checking %s channel...\n", channel[k]);
		// At this stage we can query the server for various update version files.
		// We first try to lookup for "<appname>_<os_arch>_<os_version_major>_<os_version_minor>.ver"
		// and then remove each each of the <os_> components until we find our match. For instance, we may first
		// look for rufus_win_x64_6.2.ver (Win8 x64) but only get a match for rufus_win_x64_6.ver (Vista x64 or later)
		// This allows sunsetting OS versions (eg XP) or providing different downloads for different archs/groups.
		safe_sprintf(urlpath, sizeof(urlpath), "%s%s%s_%s_%d.%d.ver", APPLICATION_NAME, (k==0)?"":"_",
			(k==0)?"":channel[k], archname[is_x64()?1:0], os_version.dwMajorVersion, os_version.dwMinorVersion);
		vuprintf("Base update check: %s\n", urlpath);
		for (i=0, j=(int)safe_strlen(urlpath)-5; (j>0)&&(i<ARRAYSIZE(verpos)); j--) {
			if ((urlpath[j] == '.') || (urlpath[j] == '_')) {
				verpos[i++] = j;
			}
		}
		if (i != ARRAYSIZE(verpos)) {
			uprintf("Broken code in CheckForUpdatesThread()!\n");
			goto out;
		}

		UrlParts.lpszUrlPath = urlpath;
		UrlParts.dwUrlPathLength = sizeof(urlpath);
		for (i=0; i<ARRAYSIZE(verpos); i++) {
			vvuprintf("Trying %s\n", UrlParts.lpszUrlPath);
			hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, accept_types,
				INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|INTERNET_FLAG_NO_COOKIES|
				INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL);
			if ((hRequest == NULL) || (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)))
				goto out;

			// Ensure that we get a text file
			dwSize = sizeof(dwStatus);
			dwStatus = 404;
			HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwSize, NULL);
			if (dwStatus == 200) 
				break;
			InternetCloseHandle(hRequest);
			hRequest = NULL;
			safe_strcpy(&urlpath[verpos[i]], 5, ".ver");
		}
		if (dwStatus != 200) {
			vuprintf("Could not find a %s version file on server %s", channel[k], server_url);
			if ((releases_only) || (k+1 >= ARRAYSIZE(channel)))
				goto out;
			continue;
		}
		vuprintf("Found match for %s on server %s", urlpath, server_url);

		dwSize = sizeof(mime);
		HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_TYPE, (LPVOID)&mime, &dwSize, NULL);
		if (strcmp(mime, "text/plain") != 0)
			goto out;

		// We also get a date from Apache, which we'll use to avoid out of sync check,
		// in case some set their clock way into the future and back.
		// On the other hand, if local clock is set way back in the past, we will never check.
		dwSize = sizeof(ServerTime);
		// If we can't get a date we can trust, don't bother...
		if ( (!HttpQueryInfoA(hRequest, HTTP_QUERY_DATE|HTTP_QUERY_FLAG_SYSTEMTIME, (LPVOID)&ServerTime, &dwSize, NULL))
			|| (!SystemTimeToFileTime(&ServerTime, &FileTime)) )
			goto out;
		server_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000;
		vvuprintf("Server time: %" PRId64 "\n", server_time);
		// Always store the server response time - the only clock we trust!
		WriteRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE, server_time);
		// Might as well let the user know
		if (!force_update_check) {
			if ((local_time > server_time + 600) || (local_time < server_time - 600)) {
				uprintf("IMPORTANT: Your local clock is more than 10 minutes in the %s. Unless you fix this, " APPLICATION_NAME " may not be able to check for updates...", 
					(local_time > server_time + 600)?"future":"past");
			}
		}

		dwSize = sizeof(dwTotalSize);
		if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL))
			goto out;

		safe_free(buf);
		// Make sure the file is NUL terminated
		buf = (char*)calloc(dwTotalSize+1, 1);
		if (buf == NULL) goto out;
		// This is a version file - we should be able to gulp it down in one go
		if (!InternetReadFile(hRequest, buf, dwTotalSize, &dwDownloaded) || (dwDownloaded != dwTotalSize))
			goto out;

		status++;
		vuprintf("Successfully downloaded version file (%d bytes)\n", dwTotalSize);

		parse_update(buf, dwTotalSize+1);

		vuprintf("UPDATE DATA:\n");
		vuprintf("  version: %d.%d.%d.%d (%s)\n", update.version[0], update.version[1], 
			update.version[2], update.version[3], channel[k]);
		vuprintf("  platform_min: %d.%d\n", update.platform_min[0], update.platform_min[1]);
		vuprintf("  url: %s\n", update.download_url);

		found_new_version = ((to_uint64_t(update.version) > to_uint64_t(rufus_version)) || (force_update))
			&& ( (os_version.dwMajorVersion > update.platform_min[0])
			  || ( (os_version.dwMajorVersion == update.platform_min[0]) && (os_version.dwMinorVersion >= update.platform_min[1])) );
		uprintf("N%sew %s version found%c\n", found_new_version?"":"o n", channel[k], found_new_version?'!':'.');
	}

out:
	safe_free(buf);
	if (hRequest) InternetCloseHandle(hRequest);
	if (hConnection) InternetCloseHandle(hConnection);
	if (hSession) InternetCloseHandle(hSession);
	switch(status) {
	case 1:
		PrintStatus(3000, TRUE, MSG_244);
		break;
	case 2:
		PrintStatus(3000, TRUE, MSG_245);
		break;
	case 3:
	case 4:
		PrintStatus(3000, FALSE, found_new_version?MSG_246:MSG_247);
	default:
		break;
	}
	// Start the new download after cleanup
	if (found_new_version) {
		// User may have started an operation while we were checking
		while ((!force_update_check) && (iso_op_in_progress || format_op_in_progress || (dialog_showing>0))) {
			Sleep(15000);
		}
		DownloadNewVersion();
	}
	force_update_check = FALSE;
	update_check_in_progress = FALSE;
	ExitThread(0);
}
예제 #26
0
/*
========================
idSaveGameThread::Enumerate
========================
*/
int idSaveGameThread::Enumerate()
{
	idSaveLoadParms* callback = data.saveLoadParms;
	idStr saveFolder = "savegame";
	
	callback->detailList.Clear();
	
	int ret = ERROR_SUCCESS;
	if( fileSystem->IsFolder( saveFolder, "fs_savePath" ) == FOLDER_YES )
	{
		idFileList* files = fileSystem->ListFilesTree( saveFolder, SAVEGAME_DETAILS_FILENAME );
		const idStrList& fileList = files->GetList();
		
		for( int i = 0; i < fileList.Num() && !callback->cancelled; i++ )
		{
			idSaveGameDetails* details = callback->detailList.Alloc();
			// We have more folders on disk than we have room in our save detail list, stop trying to read them in and continue with what we have
			if( details == NULL )
			{
				break;
			}
			idStr directory = fileList[i];
			
			idFile* file = fileSystem->OpenFileRead( directory.c_str() );
			
			if( file != NULL )
			{
				// Read the DETAIL file for the enumerated data
				if( callback->mode & SAVEGAME_MBF_READ_DETAILS )
				{
					if( !SavegameReadDetailsFromFile( file, *details ) )
					{
						details->damaged = true;
						ret = -1;
					}
				}
#ifdef _WIN32 // DG: unification of win32 and posix savagame code
				// Use the date from the directory
				WIN32_FILE_ATTRIBUTE_DATA attrData;
				BOOL attrRet = GetFileAttributesEx( file->GetFullPath(), GetFileExInfoStandard, &attrData );
				delete file;
				if( attrRet == TRUE )
				{
					FILETIME		lastWriteTime = attrData.ftLastWriteTime;
					const ULONGLONG second = 10000000L; // One second = 10,000,000 * 100 nsec
					SYSTEMTIME		base_st = { 1970, 1, 0, 1, 0, 0, 0, 0 };
					ULARGE_INTEGER	itime;
					FILETIME		base_ft;
					BOOL			success = SystemTimeToFileTime( &base_st, &base_ft );
					
					itime.QuadPart = ( ( ULARGE_INTEGER* )&lastWriteTime )->QuadPart;
					if( success )
					{
						itime.QuadPart -= ( ( ULARGE_INTEGER* )&base_ft )->QuadPart;
					}
					else
					{
						// Hard coded number of 100-nanosecond units from 1/1/1601 to 1/1/1970
						itime.QuadPart -= 116444736000000000LL;
					}
					itime.QuadPart /= second;
					details->date = itime.QuadPart;
				}
#else
				// DG: just use the idFile object's timestamp - the windows code gets file attributes and
				//  other complicated stuff like that.. I'm wonderin what that was good for.. this seems to work.
				details->date = file->Timestamp();
#endif // DG end
			}
			else
			{
				details->damaged = true;
			}
			
			// populate the game details struct
			directory = directory.StripFilename();
			details->slotName = directory.c_str() + saveFolder.Length() + 1; // Strip off the prefix too
// JDC: I hit this all the time			assert( fileSystem->IsFolder( directory.c_str(), "fs_savePath" ) == FOLDER_YES );
		}
		fileSystem->FreeFileList( files );
	}
	else
	{
		callback->errorCode = SAVEGAME_E_FOLDER_NOT_FOUND;
		ret = -3;
	}
	
	if( data.saveLoadParms->cancelled )
	{
		data.saveLoadParms->errorCode = SAVEGAME_E_CANCELLED;
	}
	
	return ret;
}
예제 #27
0
/* Finish the initialisation by checking the result of the separate thread for TLS.
   The `misc` parameter is a pointer to the thread's  data structure that contains the
   LDAP struct. The initialised LDAP struct is passed to the `ld` parameter. */
int
_ldap_finish_init_thread(char async, XTHREAD thread, int *timeout, void *misc, LDAP **ld) {
    int rc = -1;
    int retval = 0;
    SYSTEMTIME st;
    FILETIME ft;
    ULONGLONG start_time;
    ULONGLONG end_time;
    ldapInitThreadData *val = (ldapInitThreadData *)misc;

    GetSystemTime(&st);
    SystemTimeToFileTime(&st, &ft);
    /* Current time in 100-nanosec. */
    start_time = (((ULONGLONG)ft.dwHighDateTime) << 32) + ft.dwLowDateTime;

    /* Sanity check. */
    if (val == NULL || thread == NULL) return -1;

    DEBUG("_ldap_finish_init_thread (async:%d, thread:%p, timeout:%d, misc:%p)",
        async, thread, *timeout, misc);
    if (async) {
        rc = WaitForSingleObject(thread, 10);
    } else {
        rc = WaitForSingleObject(thread, *timeout);
    }

    switch (rc) {
    case WAIT_TIMEOUT:
        if (async == 0) {
            TerminateThread(thread, -1);
            CloseHandle(thread);
            set_exception(NULL, LDAP_TIMEOUT);
            retval = -1;
            goto end;
        }
        return 0;
    case WAIT_OBJECT_0:
        if (async == 0 && *timeout != -1) {
            GetSystemTime(&st);
            SystemTimeToFileTime(&st, &ft);
            /* Current time in 100-nanosec. */
            end_time = (((ULONGLONG)ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
            /* Deduct the passed time from the overall timeout. */
            *timeout -= (int)((end_time - start_time) / 10000);
            if (*timeout < 0) *timeout = 0;
        }
        if (val->retval != LDAP_SUCCESS) {
            /* The ldap_connect is failed. Set a Python error. */
            set_exception(NULL, val->retval);
            retval = -1;
            goto end;
        }
        /* Set the new LDAP struct. */
        *ld = val->ld;
        retval = 1;
        goto end;
    default:
        /* The thread is failed. */
        PyErr_BadInternalCall();
        retval = -1;
        goto end;
    }
end:
    /* Clean up the mess. */
    CloseHandle(thread);
    free(val->url);
    free(val);
    return retval;
}
예제 #28
0
파일: mzip.c 프로젝트: ggargano/hbtest2
static int hb_unzipExtractCurrentFile( unzFile hUnzip, const char * szFileName, const char * szPassword )
{
   char          szName[ HB_PATH_MAX ];
   HB_SIZE       nPos, nLen;
   char          cSep, * pString;
   unz_file_info ufi;
   int        iResult;
   HB_FHANDLE hFile;

   iResult = unzGetCurrentFileInfo( hUnzip, &ufi, szName, HB_PATH_MAX - 1,
                                    NULL, 0, NULL, 0 );
   if( iResult != UNZ_OK )
      return iResult;

   iResult = unzOpenCurrentFilePassword( hUnzip, szPassword );

   if( iResult != UNZ_OK )
      return iResult;

   if( szFileName )
      hb_strncpy( szName, szFileName, sizeof( szName ) - 1 );

   nLen = strlen( szName );

   /* Test shows that files in subfolders can be stored to zip file without
      explicitly adding folder. So, let's create a required path */

   nPos = 1;
   while( nPos < nLen )
   {
      cSep = szName[ nPos ];

      /* allow both path separators, ignore terminating path separator */
      if( ( cSep == '\\' || cSep == '/' ) && nPos < nLen - 1 )
      {
         szName[ nPos ] = '\0';
         hb_fsMkDir( szName );
         szName[ nPos ] = cSep;
      }
      nPos++;
   }

   if( ufi.external_fa & 0x40000000 ) /* DIRECTORY */
   {
      hb_fsMkDir( szName );
      iResult = UNZ_OK;
   }
   else
   {
      hFile = hb_fsCreate( szName, FC_NORMAL );

      if( hFile != FS_ERROR )
      {
         pString = ( char * ) hb_xgrab( HB_Z_IOBUF_SIZE );

         while( ( iResult = unzReadCurrentFile( hUnzip, pString, HB_Z_IOBUF_SIZE ) ) > 0 )
            hb_fsWriteLarge( hFile, pString, ( HB_SIZE ) iResult );

         hb_xfree( pString );

#if defined( HB_OS_WIN )
         {
            FILETIME   ftutc, ft;
            SYSTEMTIME st;

            st.wSecond       = ( WORD ) ufi.tmu_date.tm_sec;
            st.wMinute       = ( WORD ) ufi.tmu_date.tm_min;
            st.wHour         = ( WORD ) ufi.tmu_date.tm_hour;
            st.wDay          = ( WORD ) ufi.tmu_date.tm_mday;
            st.wMonth        = ( WORD ) ufi.tmu_date.tm_mon + 1;
            st.wYear         = ( WORD ) ufi.tmu_date.tm_year;
            st.wMilliseconds = 0;

            if( SystemTimeToFileTime( &st, &ft ) &&
                LocalFileTimeToFileTime( &ft, &ftutc ) )
            {
               SetFileTime( ( HANDLE ) hb_fsGetOsHandle( hFile ), &ftutc, &ftutc, &ftutc );
            }
         }
#endif

         hb_fsClose( hFile );
      }
      else
         iResult = -200 - hb_fsError();
   }
   unzCloseCurrentFile( hUnzip );

#if defined( HB_OS_WIN )
   {
      LPTSTR  lpFileNameFree;
      LPCTSTR lpFileName = HB_FSNAMECONV( szName, &lpFileNameFree );

      SetFileAttributes( ( LPCTSTR ) lpFileName, ufi.external_fa & 0xFF );

      if( lpFileNameFree )
         hb_xfree( lpFileNameFree );
   }
#elif defined( HB_OS_UNIX ) || defined( __DJGPP__ )
   {
      struct utimbuf utim;
      struct tm      st;
      time_t         tim;

      char *       pszFree;
      const char * szNameOS = hb_fsNameConv( szName, &pszFree );

#  if defined( __DJGPP__ )
      _chmod( szNameOS, 1, ufi.external_fa & 0xFF );
#  else
      HB_FATTR ulAttr = ufi.external_fa;

      if( ( ulAttr & 0xFFFF0000 ) == 0 )
         ulAttr = hb_translateExtAttr( szName, ulAttr );

      chmod( szNameOS,
             ( ( ulAttr & 0x00010000 ) ? S_IXOTH : 0 ) |
             ( ( ulAttr & 0x00020000 ) ? S_IWOTH : 0 ) |
             ( ( ulAttr & 0x00040000 ) ? S_IROTH : 0 ) |
             ( ( ulAttr & 0x00080000 ) ? S_IXGRP : 0 ) |
             ( ( ulAttr & 0x00100000 ) ? S_IWGRP : 0 ) |
             ( ( ulAttr & 0x00200000 ) ? S_IRGRP : 0 ) |
             ( ( ulAttr & 0x00400000 ) ? S_IXUSR : 0 ) |
             ( ( ulAttr & 0x00800000 ) ? S_IWUSR : 0 ) |
             ( ( ulAttr & 0x01000000 ) ? S_IRUSR : 0 ) );
#  endif
      memset( &st, 0, sizeof( st ) );

      st.tm_sec  = ufi.tmu_date.tm_sec;
      st.tm_min  = ufi.tmu_date.tm_min;
      st.tm_hour = ufi.tmu_date.tm_hour;
      st.tm_mday = ufi.tmu_date.tm_mday;
      st.tm_mon  = ufi.tmu_date.tm_mon;
      st.tm_year = ufi.tmu_date.tm_year - 1900;

      tim = mktime( &st );
#  if defined( HB_HAS_LOCALTIME_R )
      gmtime_r( &tim, &st );
#  else
      st = *gmtime( &tim );
#  endif
      utim.actime = utim.modtime = mktime( &st );

      utime( szNameOS, &utim );

      if( pszFree )
         hb_xfree( pszFree );
   }
#elif defined( HB_OS_DOS )
   {
#  if defined( __RSX32__ ) || defined( __GNUC__ )
      char * pszFree;

      _chmod( hb_fsNameConv( szName, &pszFree ), 1, ufi.external_fa & 0xFF );

      if( pszFree )
         hb_xfree( pszFree );
#  else
      hb_fsSetAttr( szName, ufi.external_fa & 0xFF );
#  endif
   }

#elif defined( HB_OS_OS2 )
   {
      FILESTATUS3 fs3;
      APIRET      ulrc;
      HB_FATTR    ulAttr = FILE_NORMAL;
      int         iAttr  = ufi.external_fa & 0xFF;

      char *       pszFree;
      const char * szNameOS = hb_fsNameConv( szName, &pszFree );

      if( iAttr & HB_FA_READONLY )
         ulAttr |= FILE_READONLY;
      if( iAttr & HB_FA_HIDDEN )
         ulAttr |= FILE_HIDDEN;
      if( iAttr & HB_FA_SYSTEM )
         ulAttr |= FILE_SYSTEM;
      if( iAttr & HB_FA_ARCHIVE )
         ulAttr |= FILE_ARCHIVED;

      ulrc = DosQueryPathInfo( ( PCSZ ) szNameOS, FIL_STANDARD, &fs3, sizeof( fs3 ) );

      if( ulrc == NO_ERROR )
      {
         FDATE fdate;
         FTIME ftime;

         fdate.year    = ufi.tmu_date.tm_year - 1980;
         fdate.month   = ufi.tmu_date.tm_mon;
         fdate.day     = ufi.tmu_date.tm_mday;
         ftime.hours   = ufi.tmu_date.tm_hour;
         ftime.minutes = ufi.tmu_date.tm_min;
         ftime.twosecs = ufi.tmu_date.tm_sec / 2;

         fs3.attrFile = ulAttr;

         fs3.fdateCreation = fs3.fdateLastAccess = fs3.fdateLastWrite = fdate;
         fs3.ftimeCreation = fs3.ftimeLastAccess = fs3.ftimeLastWrite = ftime;
         ulrc = DosSetPathInfo( ( PCSZ ) szNameOS, FIL_STANDARD,
                                &fs3, sizeof( fs3 ), DSPI_WRTTHRU );
      }

      if( pszFree )
         hb_xfree( pszFree );
   }
#else
   {
      hb_fsSetAttr( szName, ufi.external_fa );
   }
#endif

   return iResult;
}
예제 #29
0
파일: time.c 프로젝트: DeadZen/qse
int qse_timegm (const qse_btime_t* bt, qse_ntime_t* nt)
{
#if 0
#if defined(_WIN32)
	/* TODO: verify qse_timegm for WIN32 */
	SYSTEMTIME st;
	FILETIME ft;

	st.wYear = bt->tm_year + QSE_EPOCH_YEAR;
	st.wMonth = bt->tm_mon + WIN_EPOCH_MON;
	st.wDayOfWeek = bt->tm_wday;
	st.wDay = bt->tm_mday;
	st.wHour = bt->tm_hour;
	st.wMinute = bt->tm_min;
	st.mSecond = bt->tm_sec;
	st.mMilliseconds = bt->tm_msec;

	if (SystemTimeToFileTime (&st, &ft) == FALSE) return -1;
	*nt = ((qse_ntime_t)(*((qse_int64_t*)&ft)) / (10 * 1000));
	*nt -= EPOCH_DIFF_MSECS;
	
	return 0;
#elif defined(__OS2__)
#	error NOT IMPLEMENTED YET
#elif defined(__DOS__)
#	error NOT IMPLEMENTED YET
#else

	/* TODO: qse_timegm - remove dependency on timegm */
	struct tm tm;

	tm.tm_sec = bt->sec;
	tm.tm_min = bt->min;
	tm.tm_hour = bt->hour;
	tm.tm_mday = bt->mday;
	tm.tm_mon = bt->mon;
	tm.tm_year = bt->year;
	tm.tm_wday = bt->wday;
	tm.tm_yday = bt->yday;
	tm.tm_isdst = bt->isdst;

#if defined(HAVE_TIMEGM)
	*nt = ((qse_ntime_t)timegm(&tm)*QSE_MSECS_PER_SEC) + bt->msec;
	return 0;
#else
	#warning #### timegm() is not available on this platform ####
	return -1;
#endif

#endif
#endif

	qse_long_t n = 0;
	int y = bt->year + QSE_BTIME_YEAR_BASE;
	int midx = QSE_IS_LEAPYEAR(y)? 1: 0;

	QSE_ASSERT (bt->mon >= 0 && bt->mon < QSE_MONS_PER_YEAR);

	if (y < QSE_EPOCH_YEAR)
	{
		/*int x;

		for (x = y; x < QSE_EPOCH_YEAR - 1; x++)
			n += QSE_DAYS_PER_YEAR(x);*/
		n = QSE_DAYS_PER_NORMYEAR * (QSE_EPOCH_YEAR - 1 - y) + 
		    get_leap_days (y, QSE_EPOCH_YEAR - 1);

		/*for (x = bt->mon + 1; x < QSE_MONS_PER_YEAR; x++)
			n += mdays[midx][x];*/
		n += mdays_rtot[midx][bt->mon];

		n += mdays[midx][bt->mon] - bt->mday;
		if (midx == 1) n -= 1;
		n *= QSE_HOURS_PER_DAY;

		n = (n + QSE_HOURS_PER_DAY - bt->hour - 1) * QSE_MINS_PER_HOUR;
		n = (n + QSE_MINS_PER_HOUR - bt->min - 1) * QSE_SECS_PER_MIN;
		n = (n + QSE_SECS_PER_MIN - bt->sec); /* * QSE_MSECS_PER_SEC;

		if (bt->msec > 0) n += QSE_MSECS_PER_SEC - bt->msec;
		*nt = -n; */

		nt->sec = -n;
		nt->nsec = 0;
	} 
	else
	{
		/*int x;

		for (x = QSE_EPOCH_YEAR; x < y; x++) 
			n += QSE_DAYS_PER_YEAR(x);*/
		n = QSE_DAYS_PER_NORMYEAR * (y - QSE_EPOCH_YEAR) + 
		    get_leap_days (QSE_EPOCH_YEAR, y);

		/*for (x = 0; x < bt->mon; x++) n += mdays[midx][x];*/
		n += mdays_tot[midx][bt->mon];

		n = (n + bt->mday - 1) * QSE_HOURS_PER_DAY;
		n = (n + bt->hour) * QSE_MINS_PER_HOUR;
		n = (n + bt->min) * QSE_SECS_PER_MIN;
		n = (n + bt->sec); /* QSE_MSECS_PER_SEC;

		*nt = n + bt->msec;*/

		nt->sec = n;
		nt->nsec = 0;		
	}

	return 0;
}
void CCreateNewDatabase::RunEx()
{
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);

	// reset values
	m_strQueryCreateItem = "";
	m_iCreateItem = 0;
	
	m_strQueryUpdateItem = "";
	m_iUpdateItem = 0;

	m_strQueryNoUpdateItem = "";
	m_iNoUpdateItem = 0;

	// calculate last run time
	// Scheduler
	SallyAPI::Scheduler::CSchedulerManager* schedulerManager = SallyAPI::Scheduler::CSchedulerManager::GetInstance();
	SYSTEMTIME lastRun = schedulerManager->GetLastSchedulerRun(m_pWindow, "dbcreator");

	//Convert both to FILETIMEs
	m_ftLastRun.dwHighDateTime = 0;
	m_ftLastRun.dwLowDateTime = 0;
	SystemTimeToFileTime(&lastRun, &m_ftLastRun);

	std::string mediaDB = m_strMediaDirectory;
	mediaDB.append("image.db");

	bool bFileExists = SallyAPI::File::FileHelper::FileExistsAndNotEmpty(mediaDB);

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

	dbconn->LockDatabase();
	if (bFileExists == false)
	{
		// Create
		std::string queryCreate;
		queryCreate.append("CREATE TABLE image ( \
						   Filename     TEXT UNIQUE, \
						   DeleteFlag	INTEGER, \
						   Rating		INTEGER, \
						   CreateYear	INTEGER, \
						   CreateMonth	INTEGER \
						   );");
		try
		{
			SallyAPI::Database::CStatement* stmtCreate = dbconn->CreateStatement();
			stmtCreate->Execute(queryCreate.c_str());
		}
		catch (SallyAPI::Database::CSQLException* e)
		{
			SallyAPI::System::CLogger* logger = SallyAPI::Core::CGame::GetLogger();
			logger->Error(e->GetMessage());
		}
	}
	dbconn->ReleaseDatabase();

	// Set Delete Flag
	std::string querySetDelete = "UPDATE image SET DeleteFlag = 1;";

	dbconn->LockDatabase();

	try
	{
		SallyAPI::Database::CStatement* stmtSetDelete = dbconn->CreateStatement();
		stmtSetDelete->Execute(querySetDelete.c_str());
	}
	catch (SallyAPI::Database::CSQLException* e)
	{
		SallyAPI::System::CLogger* logger = SallyAPI::Core::CGame::GetLogger();
		logger->Error(e->GetMessage());
	}

	dbconn->ReleaseDatabase();

	std::vector<std::string>::iterator iter;

	// Collect Information
	for (iter = m_vFolders.begin(); iter != m_vFolders.end(); iter++)
	{
		std::string folder = *iter;
		CollectInformation(folder);

		if (m_bPleaseStop)
		{
			SallyAPI::Database::CDatabaseConnection::Close(mediaDB);
			return;
		}
	}
	m_pProcessbar->SetMaxPosition(m_iFileCount);

	// Create Database
	for (iter = m_vFolders.begin(); iter != m_vFolders.end(); iter++)
	{
		std::string folder = *iter;
		AddFolder(dbconn, folder);

		if (m_bPleaseStop)
		{
			SallyAPI::Database::CDatabaseConnection::Close(mediaDB);
			return;
		}
	}
	// execute rest of the create item statements
	ExecuteCreateItem(dbconn);
	ExecuteUpdateItem(dbconn);
	ExecuteNoUpdateItem(dbconn);

	// Set Delete Flag
	std::string queryDelete;
	queryDelete.append("DELETE FROM image WHERE DeleteFlag = 1;");

	dbconn->LockDatabase();

	try
	{
		SallyAPI::Database::CStatement* stmtDelete = dbconn->CreateStatement();
		stmtDelete->Execute(queryDelete.c_str());
	}
	catch (SallyAPI::Database::CSQLException* e)
	{
		SallyAPI::System::CLogger* logger = SallyAPI::Core::CGame::GetLogger();
		logger->Error(e->GetMessage());
	}

	dbconn->ReleaseDatabase();

	SallyAPI::Database::CDatabaseConnection::Close(mediaDB);

	m_pWindow->SendMessageToParent(0, 0, m_iMessageId);
}