Exemple #1
0
/*! \fn float Sonar::DisplayMeasurement()
 * 	\brief Calculate the distance measurement from the time of flight.
 * 	\return The distance calculated.
 */
float Sonar::DisplayMeasurement()
{
    if (TimeDiff().tv_sec == 0)
    {
        float time = TimeDiff().tv_nsec/1000000000.f;
        float dist = 340.29*(time/2);
        if (dist < 3.f && dist > 0)
        {
            if (dist < _minDist)
            {
                _minDist = dist;
            }
            if (dist > _maxDist)
            {
                _maxDist = dist;
            }
#if 0
            // no longer want to print out the message.
            printf("Time taken is: %fs\n", time);
            printf("Dist is: %fm\t minDist: %fm\t maxDist: %fm\n", dist, _minDist, _maxDist);
            fflush(stdout);
#endif
            return dist;
        }
    }
    return 0.f;
}
Exemple #2
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
	HWND hwnd;
	MSG msg;
	WNDCLASSEX wndclass;

	wndclass.cbSize = sizeof(wndclass);
	wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wndclass.lpfnWndProc = WndProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = hInstance;
	wndclass.hIcon = LoadIcon (hInstance, "PROGICON");
	wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
	wndclass.lpszMenuName = NULL;
	wndclass.lpszClassName = APPNAME;
	wndclass.hIconSm = LoadIcon (hInstance, "PROGICON");

	RegisterClassEx (&wndclass);

	hwnd = CreateWindow(APPNAME, APPNAME,
						WS_OVERLAPPEDWINDOW,
						CW_USEDEFAULT, CW_USEDEFAULT,
						400, 300,
						NULL, NULL, hInstance, NULL);
	
	ShowWindow (hwnd, iCmdShow);
	UpdateWindow (hwnd);

   TimeDiff(); // init TimeDiff function

   // init AV environment
   g_Env.Init();

   // ** MAIN LOOP **
	while (1)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
		{
			if (!GetMessage (&msg, NULL, 0, 0)) return msg.wParam;
			TranslateMessage (&msg);
			DispatchMessage (&msg);
      }

      // change AV state
	  float td = (float) TimeDiff();
	  if (td != 0) { g_Env.SetFPS(1/td); }
      g_Env.DrawBuffer(td);
      g_Env.PlaceCamera();
      SwapBuffers(g_hDC);
	}

	return msg.wParam;
}
Exemple #3
0
float CEnvironment::TimeWeight(float val, float min_t, float max_t)
{
	float weight	= 0.f;
	float length	= TimeDiff(min_t,max_t);
	if (!fis_zero(length,EPS)){
		if (min_t>max_t){
			if ((val>=min_t)||(val<=max_t))	weight = TimeDiff(min_t,val)/length;
		}else{
			if ((val>=min_t)&&(val<=max_t))	weight = TimeDiff(min_t,val)/length;
		}
		clamp		(weight,0.f,1.f);
	}
	return			weight;
}
Exemple #4
0
		int handle() {
			const int maxFPS = tLXOptions ? tLXOptions->nMaxFPS : 100;
			TimeDiff max_frame_time = TimeDiff(MAX(0.01f, (maxFPS > 0) ? 1.0f/(float)maxFPS : 0.0f));
			AbsTime lastTime = GetTime();
			
			while(!sharedData->quitSignal) {
				NLsocket s;
				NLint ret = nlPollGroup(sharedData->nlGroup, pollType, &s, /* amount of sockets */ 1, /* timeout */ (NLint)max_frame_time.milliseconds());
				// if no error, ret is amount of sockets which triggered the event
				
				if(ret > 0) {
					switch(pollType) {
						case NL_READ_STATUS: if(!pushNewDataEvent()) return -1; break;
						case NL_ERROR_STATUS: if(!pushErrorEvent()) return -1; break;
					}
				}
				
				AbsTime curTime = GetTime();
				if(curTime - lastTime < max_frame_time) {
					SDL_Delay( (Uint32)( ( max_frame_time - (curTime - lastTime) ).milliseconds() ) );
				}
				lastTime = curTime;
			}
			
			return 0;
		}
Exemple #5
0
void CEnvironment::SetGameTime(float game_time, float time_factor)
{ 
	if (bWFX)
		wfx_time			-= TimeDiff(fGameTime,game_time);
	fGameTime				= game_time;  
	fTimeFactor				= time_factor;	
}
void display(void)
{
    float td = TimeDiff();
    g_Env.DrawBuffer(td);
    if (td != 0) { g_Env.SetFPS(1/td); }
    g_Env.PlaceCamera();
    glutSwapBuffers();
}
void CGBLStorageManagerTestBBBase::StopAndShowTimeMeasure(ofstream &_trace, float &totalTime)
{
    float executionTime = TimeDiff();
	totalTime += executionTime;
	XString disp = "";
	disp << executionTime;
	_trace << "Execution time: " << disp.Str() << " seconds" <<endl;
}
Exemple #8
0
END_TEST

START_TEST(TIMEDIFF4)
{
	std::ostringstream oss;
	oss << TimeDiff (0.005, false);

	ck_assert_str_eq (oss.str ().c_str (), "5ms");
}
Exemple #9
0
bool CEnvironment::SetWeatherFX(shared_str name)
{
	if (bWFX)				return false;
	if (name.size()){
		EnvsMapIt it		= WeatherFXs.find(name);
		R_ASSERT3			(it!=WeatherFXs.end(),"Invalid weather effect name.",*name);
		EnvVec* PrevWeather = CurrentWeather; VERIFY(PrevWeather);
		CurrentWeather		= &it->second;
		CurrentWeatherName	= it->first;

		float rewind_tm		= WFX_TRANS_TIME*fTimeFactor;
		float start_tm		= fGameTime+rewind_tm;
		float current_length;
		float current_weight;
		if (Current[0]->exec_time>Current[1]->exec_time){
			float x			= fGameTime>Current[0]->exec_time?fGameTime-Current[0]->exec_time:(DAY_LENGTH-Current[0]->exec_time)+fGameTime;
			current_length	= (DAY_LENGTH-Current[0]->exec_time)+Current[1]->exec_time;
			current_weight	= x/current_length; 
		}else{
			current_length	= Current[1]->exec_time-Current[0]->exec_time;
			current_weight	= (fGameTime-Current[0]->exec_time)/current_length; 
		}
		clamp				(current_weight,0.f,1.f);

		std::sort			(CurrentWeather->begin(),CurrentWeather->end(),sort_env_etl_pred);
		CEnvDescriptor* C0	= CurrentWeather->at(0);
		CEnvDescriptor* C1	= CurrentWeather->at(1);
		CEnvDescriptor* CE	= CurrentWeather->at(CurrentWeather->size()-2);
		CEnvDescriptor* CT	= CurrentWeather->at(CurrentWeather->size()-1);
		C0->copy			(*Current[0]);	C0->exec_time = NormalizeTime(fGameTime-((rewind_tm/(Current[1]->exec_time-fGameTime))*current_length-rewind_tm));
		C1->copy			(*Current[1]);	C1->exec_time = NormalizeTime(start_tm);
		for (EnvIt t_it=CurrentWeather->begin()+2; t_it!=CurrentWeather->end()-1; t_it++)
			(*t_it)->exec_time= NormalizeTime(start_tm+(*t_it)->exec_time_loaded);
		SelectEnv			(PrevWeather,WFX_end_desc[0],CE->exec_time);
		SelectEnv			(PrevWeather,WFX_end_desc[1],WFX_end_desc[0]->exec_time+0.5f);
		CT->copy			(*WFX_end_desc[0]);CT->exec_time = NormalizeTime(CE->exec_time+rewind_tm);
		wfx_time			= TimeDiff(fGameTime,CT->exec_time);
		bWFX				= true;

		// sort wfx envs
		std::sort			(CurrentWeather->begin(),CurrentWeather->end(),sort_env_pred);

		Current[0]			= C0;
		Current[1]			= C1;
#ifdef WEATHER_LOGGING
		Msg					("Starting WFX: '%s' - %3.2f sec",*name,wfx_time);
		for (EnvIt l_it=CurrentWeather->begin(); l_it!=CurrentWeather->end(); l_it++)
			Msg				(". Env: '%s' Tm: %3.2f",*(*l_it)->sect_name,(*l_it)->exec_time);
#endif
	}else{
#ifndef _EDITOR
		FATAL				("! Empty weather effect name");
#endif
	}
	return true;
}
void CGBLStorageManagerTestBBBase::StopAndOutputTimeMeasure( CKContext *ctx )
{
    float executionTime = TimeDiff();
	totalExecutionTime += executionTime;

	XString disp;
    disp << "Execution time: " << executionTime << " seconds";

    OutputTestText( ctx, disp );
}
		bool DynamicTimeout::Expired()
		{
			auto timedout = TimeDiff(begin, millis()) > timeout;
			if (timedout)
			{
				timeout += timeoutBase;
				if (timeout > timeoutMax) timeout = timeoutBase;
				begin = millis();
			}
			return timedout;
		}
Exemple #12
0
//-----------------------------------------------------------------------------
// Filter test
void TestFilter() {
    double phase = 0.0;
    double maxPhase = 2.0 * M_PI;
    double frequency = 30;
    double rate = frequency * 5;
    double phaseStep;
    double time = 0.0;
    double timeStep;
    int value;
    //int max = 100; // Amplitude
    int i;
    int total;
    int filtered;
    Signal signal(rate);
    Filter filter(rate, 30);
    int ret;
    timespec start;
    timespec end;
    double length = 1.0;
    int diff;
    double sec;

    signal.Init();
    filter.Init();

    phaseStep = maxPhase * frequency / rate;
    timeStep = 1 / rate;
    total = rate * length;
    clock_gettime(CLOCK_REALTIME, &start);

    for(i = 0; i < total; i++) {
        time += timeStep;
        value = RandomInt(1, 9);//5 + sin(phase) * max;

        ret = filter.Get(value, filtered);
        if(!ret)
            signal.Add(filtered);
        else
            signal.Add(-777);

        phase += phaseStep;
        if(phase >= maxPhase)
            phase -= maxPhase;

        printf("%5.2f %4d, avg=%4d\n", time, value, filter._average);
    }

    clock_gettime(CLOCK_REALTIME, &end);
    diff = TimeDiff(start, end);
    sec = (double)diff / 1e6;
    printf("Load=%0.6f, time=%0.3f sec\n", sec / length, sec);

    //signal.Show();
}
Exemple #13
0
inline void Sleep(unsigned long usec) {
  if (usec == 0) goto done;
  struct timeval sleepstart;
  gettimeofday(&sleepstart,NULL);
  while(TimeDiff(&sleepstart,NULL) <= usec) {
    //CheckHallState();
    usleep(SLEEP_GRAIN);
  }
done:
  (void)0;
  //CheckHallState();
}
Exemple #14
0
void CapFPS() {
	const TimeDiff fMaxFrameTime = TimeDiff( (tLXOptions->nMaxFPS > 0) ? (1.0f / (float)tLXOptions->nMaxFPS) : 0.0f );
	const AbsTime currentTime = GetTime();
	// tLX->currentTime is old time

	// Cap the FPS
	if(currentTime - tLX->currentTime < fMaxFrameTime)
		SDL_Delay((Uint32)(fMaxFrameTime - (currentTime - tLX->currentTime)).milliseconds());
	else
		// do at least one small break, else it's possible that we never receive signals from our OS
		SDL_Delay(1);
}
Exemple #15
0
void CEnvironment::SetGameTime(float game_time, float time_factor)
{
#ifndef _EDITOR
	if (m_paused) {
		g_pGameLevel->SetEnvironmentGameTimeFactor	(iFloor(fGameTime*1000.f), fTimeFactor);
		return;
	}
#endif
	if (bWFX)
		wfx_time			-= TimeDiff(fGameTime,game_time);
	fGameTime				= game_time;  
	fTimeFactor				= time_factor;	
}
Exemple #16
0
__declspec(dllexport) int HEIWriteIOEx
	(
	HEIDevice *apDevice[], 
	BYTE *apData[], 
	WORD aSizeofData[], 
	BYTE *apReturnData[], 
	WORD aSizeofReturnData[], 
	int aErrorCode[], 
	int DeviceCount, 
	DWORD Timeout
	)
	{
	DWORD StartTime = HEIIGetCounter();
	int idx = 0;
	BOOL Done = FALSE;
	BOOL OldPP = FALSE;

	for(idx = 0; idx < DeviceCount; idx++)
		{
		/* Handle NULL device */
		if(!apDevice[idx])
			continue;

		/* Force parallel packet mode */
		OldPP = apDevice[idx]->ParallelPackets;
		apDevice[idx]->ParallelPackets = TRUE;

		/* Init error code */
		aErrorCode[idx] = HEIE_NO_RESPONSE;

		/* Send request */
		HEIWriteIO(apDevice[idx], apData[idx], aSizeofData[idx], apReturnData[idx], &aSizeofReturnData[idx]);

		/* Check for response */
		GetResponseEx(apDevice, apReturnData, aSizeofReturnData, aErrorCode, idx+1);

		/* Restore parallel packet mode */
		apDevice[idx]->ParallelPackets = OldPP;
		}

	/* Spin on GetResponseEx waiting for timeout */
	while(!Done)
		{
		Done = GetResponseEx(apDevice, apReturnData, aSizeofReturnData, aErrorCode, idx);
		if(TimeDiff(StartTime, HEIIGetCounter()) >= Timeout)
			return HEIE_TIMEOUT;
		}

	return 0;
	}
Exemple #17
0
void display(void)
{
    static int numCalls = 10;
    static float lastTD = 0.02;
    
    if (numCalls++ >= 10) // calculate new TimeDiff value every ten frames (smoother on MacOS)
    {
    	float td = TimeDiff() / 10;
    	lastTD = td;
    	numCalls = 0;
    }
    g_Env.DrawBuffer(lastTD);
    if (lastTD != 0) { g_Env.SetFPS(1/lastTD); }
    g_Env.PlaceCamera();
    glutSwapBuffers();
}
Exemple #18
0
//-----------------------------------------------------------------------------
// Data received
// socket - the socket
void TestThread::OnSocketRead(Socket* socket) {
    int read; // Number of bytes read
    int ret;
    timespec curr;
    int diff;

    // Read socket data until there is nothing more to read
    do {
        ret = socket->Receive(_data, DATA_SIZE - 1, read);
        if(ret) {
            printf("Can't read from the socket\n");
            return;
        }

        if(!read)  // Sometimes we can get a read signal with nothing to read
            break;

        _data[read] = 0;

        if(_mode == 's') { // Server
            if(_connection == 's') { // Don't send back in multicast mode
                ret = socket->Send(_data, read); // Send the data back to the client
                if(ret)
                    printf("Can't send back: %s\n", socket->_errorDescr);
            }
        } else { // Client
            clock_gettime(CLOCK_REALTIME, &curr); // Get current time
            diff = TimeDiff(_sendTime, curr) / 2; // Save the one-way time, not round-trip
            _times->Add(diff);

            // Send more
            _count--;
            if(!_count) {
                printf("One-way times (microseconds):\n");
                _times->Get();
                exit(0);
            } else {
                clock_gettime(CLOCK_REALTIME, &_sendTime); // Get current time
                _client->Send("Test", 5);
            }
        }

    } while(read > 0);
}
//-----------------------------------------------------------------------------
// Data received from a queue
// data - queue data
void QueueThread::OnQueueData(Queue::Data* data) {
    timespec curr;
    int diff;

    if(_send) { // Sending thread
        clock_gettime(CLOCK_REALTIME, &curr); // Get current time
        diff = TimeDiff(_sendTime, curr) / 2; // Save the one-way time, not round-trip
        _times->Add(diff);
        free(data->_data); // This is the buffer we allocated here in OnTimer

        // Send more
        _count--;
        if(!_count) {
            printf("One-way times (microseconds):\n");
            _times->Get();
            exit(0);
        } else
            Send();
    } else { // Replying queue
        _queue->Send(Queue::TYPE_MEMORY, data->_data, data->_size);
        //printf("Received %d bytes: %s\n", data->_size, (char*)data->_data);
    }
}
Exemple #20
0
static int reply_lanman1(char *inbuf, char *outbuf)
{
    int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
    int secword=0;
    time_t t = time(NULL);

    global_encrypted_passwords_negotiated = lp_encrypted_passwords();

    if (lp_security()>=SEC_USER)
        secword |= NEGOTIATE_SECURITY_USER_LEVEL;
    if (global_encrypted_passwords_negotiated)
        secword |= NEGOTIATE_SECURITY_CHALLENGE_RESPONSE;

    set_message(outbuf,13,global_encrypted_passwords_negotiated?8:0,True);
    SSVAL(outbuf,smb_vwv1,secword);
    /* Create a token value and add it to the outgoing packet. */
    if (global_encrypted_passwords_negotiated) {
        get_challenge(smb_buf(outbuf));
        SSVAL(outbuf,smb_vwv11, 8);
    }

    Protocol = PROTOCOL_LANMAN1;

    /* Reply, SMBlockread, SMBwritelock supported. */
    SCVAL(outbuf,smb_flg,FLAG_REPLY|FLAG_SUPPORT_LOCKREAD);
    SSVAL(outbuf,smb_vwv2,max_recv);
    SSVAL(outbuf,smb_vwv3,lp_maxmux()); /* maxmux */
    SSVAL(outbuf,smb_vwv4,1);
    SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
		readbraw writebraw (possibly) */
    SIVAL(outbuf,smb_vwv6,sys_getpid());
    SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);

    put_dos_date(outbuf,smb_vwv8,t);

    return (smb_len(outbuf)+4);
}
Timestamp Timestamp::fromUtcTime(UtcTimeVal val)
{
    val -= (TimeDiff(0x01b21dd2) << 32) + 0x13814000;
    val /= 10;
    return Timestamp(val);
}
Exemple #22
0
void *rtos_msg_wait(uint16_t id, uint16_t timeout)
{

    // check if there was a timeout configured
    if (timeout != 0)
    {
        // elements to parse the timed thread list
        struct thread_c *next;
        struct thread_c *prev;
        // get the current time
        uint32_t now = TimeGet();
        // compute the delay in number of RTC cycles
        int32_t delay = timeout * 32;
        // compute the expiration date
        uint32_t expiration = now + delay;


        // compute the new expiration date
        rtos_env.threads[rtos_env.thread_cur].timeout.date = expiration;

        // add the timeout in the list of timed threads
        prev = rtos_env.timed;
        if ((prev == NULL) || (TimeDiff(prev->timeout.date, now) > delay))
        {
            rtos_env.timed = &(rtos_env.threads[rtos_env.thread_cur]);
            rtos_env.timed->timeout.next = prev;
        }
        else
        {
            do
            {
                // find the next thread in the list
                next = prev->timeout.next;

                // if the next one is NULL, then exit (end of the list)
                if (next == NULL)
                    break;
                // check if the next one should expire after the new one
                if (delay < TimeDiff(next->timeout.date, now))
                    break;

                // move to the next one in the list
                prev = next;
            } while (1);

            // insert the new item between the prev and the next
            rtos_env.threads[rtos_env.thread_cur].timeout.next = next;
            prev->timeout.next = &(rtos_env.threads[rtos_env.thread_cur]);
        }
    }

    // wait for the expected message
    do
    {
        void *msg;
        uint8_t msg_src;
        uint16_t msg_id;

        // wait for the next message
        msg = rtos_msg_get(&msg_src, &msg_id);

        // check if this is the expected message
        if (msg_id == id)
        {
            return msg;
        }
        // otherwise, save the message
        rtos_msg_store(msg);
    } while (1);
}
Exemple #23
0
TimeStamp::UtcTimeVal TimeStamp::UtcTime() const
{
		return m_ts*10 + (TimeDiff(0x01b21dd2) << 32) + 0x13814000;
}
Exemple #24
0
Timespan& Timespan::assign(long seconds, long microSeconds)
{
	_span = TimeDiff(seconds)*SECONDS + TimeDiff(microSeconds);
	return *this;
}
Exemple #25
0
BOOL cli_negprot(struct cli_state *cli)
{
	char *p;
	int numprots;
	int plength;

	memset(cli->outbuf,'\0',smb_size);

	/* setup the protocol strings */
	for (plength=0,numprots=0;
	     prots[numprots].name && prots[numprots].prot<=cli->protocol;
	     numprots++)
		plength += strlen(prots[numprots].name)+2;
    
	set_message(cli->outbuf,0,plength,True);

	p = smb_buf(cli->outbuf);
	for (numprots=0;
	     prots[numprots].name && prots[numprots].prot<=cli->protocol;
	     numprots++) {
		*p++ = 2;
		p += clistr_push(cli, p, prots[numprots].name, -1, STR_CONVERT|STR_TERMINATE);
	}

	SCVAL(cli->outbuf,smb_com,SMBnegprot);
	cli_setup_packet(cli);

	SCVAL(smb_buf(cli->outbuf),0,2);

	cli_send_smb(cli);
	if (!cli_receive_smb(cli))
		return False;

	show_msg(cli->inbuf);

	if (cli_is_error(cli) ||
	    ((int)SVAL(cli->inbuf,smb_vwv0) >= numprots)) {
		return(False);
	}

	cli->protocol = prots[SVAL(cli->inbuf,smb_vwv0)].prot;

	if (cli->protocol >= PROTOCOL_NT1) {    
		/* NT protocol */
		cli->sec_mode = CVAL(cli->inbuf,smb_vwv1);
		cli->max_mux = SVAL(cli->inbuf, smb_vwv1+1);
		cli->max_xmit = IVAL(cli->inbuf,smb_vwv3+1);
		cli->sesskey = IVAL(cli->inbuf,smb_vwv7+1);
		cli->serverzone = SVALS(cli->inbuf,smb_vwv15+1);
		cli->serverzone *= 60;
		/* this time arrives in real GMT */
		cli->servertime = interpret_long_date(cli->inbuf+smb_vwv11+1);
		memcpy(cli->cryptkey,smb_buf(cli->inbuf),8);
		cli->capabilities = IVAL(cli->inbuf,smb_vwv9+1);
		if (cli->capabilities & CAP_RAW_MODE) {
			cli->readbraw_supported = True;
			cli->writebraw_supported = True;      
		}
		/* work out if they sent us a workgroup */
		if (smb_buflen(cli->inbuf) > 8) {
			clistr_pull(cli, cli->server_domain, 
				    smb_buf(cli->inbuf)+8, sizeof(cli->server_domain),
				    smb_buflen(cli->inbuf)-8, STR_UNICODE|STR_NOALIGN);
		}
	} else if (cli->protocol >= PROTOCOL_LANMAN1) {
		cli->sec_mode = SVAL(cli->inbuf,smb_vwv1);
		cli->max_xmit = SVAL(cli->inbuf,smb_vwv2);
		cli->sesskey = IVAL(cli->inbuf,smb_vwv6);
		cli->serverzone = SVALS(cli->inbuf,smb_vwv10);
		cli->serverzone *= 60;
		/* this time is converted to GMT by make_unix_date */
		cli->servertime = make_unix_date(cli->inbuf+smb_vwv8);
		cli->readbraw_supported = ((SVAL(cli->inbuf,smb_vwv5) & 0x1) != 0);
		cli->writebraw_supported = ((SVAL(cli->inbuf,smb_vwv5) & 0x2) != 0);
		memcpy(cli->cryptkey,smb_buf(cli->inbuf),8);
	} else {
		/* the old core protocol */
		cli->sec_mode = 0;
		cli->serverzone = TimeDiff(time(NULL));
	}

	cli->max_xmit = MIN(cli->max_xmit, CLI_BUFFER_SIZE);

	/* a way to force ascii SMB */
	if (getenv("CLI_FORCE_ASCII")) {
		cli->capabilities &= ~CAP_UNICODE;
	}

	return True;
}
Exemple #26
0
Timespan& Timespan::assign(int days, int hours, int minutes, int seconds, int microSeconds)
{
	_span = TimeDiff(microSeconds) + TimeDiff(seconds)*SECONDS + TimeDiff(minutes)*MINUTES + TimeDiff(hours)*HOURS + TimeDiff(days)*DAYS;
	return *this;
}
Exemple #27
0
Timespan::Timespan(int days, int hours, int minutes, int seconds, int microSeconds):
	_span(TimeDiff(microSeconds) + TimeDiff(seconds)*SECONDS + TimeDiff(minutes)*MINUTES + TimeDiff(hours)*HOURS + TimeDiff(days)*DAYS)
{
}
Exemple #28
0
Timespan::Timespan(long seconds, long microSeconds):
	_span(TimeDiff(seconds)*SECONDS + microSeconds)
{
}
Exemple #29
0
/****************************************************************************
send a negprot command
****************************************************************************/
BOOL cli_negprot(struct cli_state *cli)
{
	Q_NEGPROT qw;
	R_NEGPROT rw;
	Q_NEGPROT_D qd;
	R_NEGPROT_D rd;
	Q_NEGPROT_D_0 *q0 = &qd.ctr.d0;

	ZERO_STRUCT(qw);
	ZERO_STRUCT(rw);
	ZERO_STRUCT(qd);
	ZERO_STRUCT(rd);

	qd.wcount = 0;
	q0->protocol = prot_buf;
	qw.wcount = 0;

	cli->nterr = cli_SMBnegprot(cli->hnd, &qw, &rw, &qd, &rd, NULL, NULL);
	if (cli->nterr != 0)
		return False;

	if (rw.wcount == 17)
	{
		R_NEGPROT_17 *np = &rw.ctr.r17;
		R_NEGPROT_D_13 *nd = &rd.ctr.d17;

		smb_set_protocol(cli->hnd, prots[np->DialectIndex].prot);

		if (prots[np->DialectIndex].prot >= PROTOCOL_NT1)
		{
			/* NT protocol */
			cli->sec_mode = np->SecurityMode;
			cli->max_mux = np->MaxMpxCount;
			cli->max_xmit = np->MaxBufferSize;
			cli->sesskey = np->SessionKey;
			cli->serverzone = np->ServerTimeZone;
			cli->serverzone *= 60;
			/* this time arrives in real GMT */
			cli->servertime =
				interpret_long_date(&np->SystemTime);
			memcpy(cli->cryptkey, nd->SecurityBlob, 8);
			cli->capabilities = np->Capabilities;
			if (cli->capabilities & 1)
			{
				cli->readbraw_supported = True;
				cli->writebraw_supported = True;
			}
		}
	}
	else if (rw.wcount == 13)
	{
		R_NEGPROT_13 *np = &rw.ctr.r13;
		R_NEGPROT_D_13 *nd = &rd.ctr.d13;

		smb_set_protocol(cli->hnd, prots[np->DialectIndex].prot);

		if (prots[np->DialectIndex].prot >= PROTOCOL_LANMAN1)
		{
			cli->sec_mode = np->SecurityMode;
			cli->max_xmit = np->MaxBufferSize;
			cli->sesskey = np->SessionKey;
			cli->serverzone = np->ServerTimeZone;
			cli->serverzone *= 60;
			/* this time is converted to GMT by make_unix_date */
			cli->servertime = make_unix_date(&np->ServerTimeDate);
			cli->readbraw_supported = (np->RawMode & 0x1) != 0;
			cli->writebraw_supported = (np->RawMode & 0x2) != 0;
			memcpy(cli->cryptkey, nd->SecurityBlob, 8);
		}
	}
	else
	{
		/* the old core protocol */
		cli->sec_mode = 0;
		cli->serverzone = TimeDiff(time(NULL));
	}

	cli->max_xmit = MIN(cli->max_xmit, CLI_BUFFER_SIZE);

	return True;
}
Exemple #30
0
static int reply_nt1(char *inbuf, char *outbuf)
{
    /* dual names + lock_and_read + nt SMBs + remote API calls */
    int capabilities = CAP_NT_FIND|CAP_LOCK_AND_READ|
                       CAP_LEVEL_II_OPLOCKS;

    int secword=0;
    time_t t = time(NULL);
    char *p, *q;
    BOOL negotiate_spnego = False;

    global_encrypted_passwords_negotiated = lp_encrypted_passwords();

    /* do spnego in user level security if the client
       supports it and we can do encrypted passwords */

    if (global_encrypted_passwords_negotiated &&
            (lp_security() != SEC_SHARE) &&
            lp_use_spnego() &&
            (SVAL(inbuf, smb_flg2) & FLAGS2_EXTENDED_SECURITY)) {
        negotiate_spnego = True;
        capabilities |= CAP_EXTENDED_SECURITY;
        add_to_common_flags2(FLAGS2_EXTENDED_SECURITY);
        /* Ensure FLAGS2_EXTENDED_SECURITY gets set in this reply (already
        	partially constructed. */
        SSVAL(outbuf,smb_flg2, SVAL(outbuf,smb_flg2) | FLAGS2_EXTENDED_SECURITY);
    }

    capabilities |= CAP_NT_SMBS|CAP_RPC_REMOTE_APIS|CAP_UNICODE;

    if (lp_unix_extensions()) {
        capabilities |= CAP_UNIX;
    }

    if (lp_large_readwrite() && (SMB_OFF_T_BITS == 64))
        capabilities |= CAP_LARGE_READX|CAP_LARGE_WRITEX|CAP_W2K_SMBS;

    if (SMB_OFF_T_BITS == 64)
        capabilities |= CAP_LARGE_FILES;

    if (lp_readraw() && lp_writeraw())
        capabilities |= CAP_RAW_MODE;

    if (lp_nt_status_support())
        capabilities |= CAP_STATUS32;

    if (lp_host_msdfs())
        capabilities |= CAP_DFS;

    if (lp_security() >= SEC_USER)
        secword |= NEGOTIATE_SECURITY_USER_LEVEL;
    if (global_encrypted_passwords_negotiated)
        secword |= NEGOTIATE_SECURITY_CHALLENGE_RESPONSE;

    if (lp_server_signing()) {
        if (lp_security() >= SEC_USER) {
            secword |= NEGOTIATE_SECURITY_SIGNATURES_ENABLED;
            /* No raw mode with smb signing. */
            capabilities &= ~CAP_RAW_MODE;
            if (lp_server_signing() == Required)
                secword |=NEGOTIATE_SECURITY_SIGNATURES_REQUIRED;
            srv_set_signing_negotiated();
        } else {
            DEBUG(0,("reply_nt1: smb signing is incompatible with share level security !\n"));
            if (lp_server_signing() == Required) {
                exit_server("reply_nt1: smb signing required and share level security selected.");
            }
        }
    }

    set_message(outbuf,17,0,True);

    SCVAL(outbuf,smb_vwv1,secword);

    Protocol = PROTOCOL_NT1;

    SSVAL(outbuf,smb_vwv1+1,lp_maxmux()); /* maxmpx */
    SSVAL(outbuf,smb_vwv2+1,1); /* num vcs */
    SIVAL(outbuf,smb_vwv3+1,max_recv); /* max buffer. LOTS! */
    SIVAL(outbuf,smb_vwv5+1,0x10000); /* raw size. full 64k */
    SIVAL(outbuf,smb_vwv7+1,sys_getpid()); /* session key */
    SIVAL(outbuf,smb_vwv9+1,capabilities); /* capabilities */
    put_long_date(outbuf+smb_vwv11+1,t);
    SSVALS(outbuf,smb_vwv15+1,TimeDiff(t)/60);

    p = q = smb_buf(outbuf);
    if (!negotiate_spnego) {
        /* Create a token value and add it to the outgoing packet. */
        if (global_encrypted_passwords_negotiated) {
            /* note that we do not send a challenge at all if
               we are using plaintext */
            get_challenge(p);
            SSVALS(outbuf,smb_vwv16+1,8);
            p += 8;
        }
        p += srvstr_push(outbuf, p, lp_workgroup(), -1,
                         STR_UNICODE|STR_TERMINATE|STR_NOALIGN);
        DEBUG(3,("not using SPNEGO\n"));
    } else {
        int len = negprot_spnego(p);

        SSVALS(outbuf,smb_vwv16+1,len);
        p += len;
        DEBUG(3,("using SPNEGO\n"));
    }

    SSVAL(outbuf,smb_vwv17, p - q); /* length of challenge+domain strings */
    set_message_end(outbuf, p);

    return (smb_len(outbuf)+4);
}