void CDevice::Process()
{
  if (m_output.empty())
    Log("%s: starting", m_name.c_str());
  else
    Log("%s: starting with output \"%s\"", m_name.c_str(), m_output.c_str());
  
  if (m_setpriority)
  {
    sched_param param = {};
    param.sched_priority = m_threadpriority;
    int returnv = pthread_setschedparam(m_thread, SCHED_FIFO, &param);
    if (returnv == 0)
      Log("%s: successfully set thread priority to %i", m_name.c_str(), m_threadpriority);
    else
      LogError("%s: error setting thread priority to %i: %s", m_name.c_str(), m_threadpriority, GetErrno(returnv).c_str());
  }

  int64_t setuptime;

  while(!m_stop)
  {
    //keep trying to set up the device every 10 seconds
    while(!m_stop)
    {
      Log("%s: setting up", m_name.c_str());

      setuptime = GetTimeUs();
      if (!SetupDevice())
      {
        CloseDevice();
	LogError("%s: setting up failed, retrying in 10 seconds", m_name.c_str());
        USleep(10000000LL, &m_stop);
      }
      else
      {
	Log("%s: setup succeeded", m_name.c_str());
        break;
      }
    }

    //keep calling writeoutput until we're asked to stop or writeoutput fails
    while(!m_stop)
    {
      if (!WriteOutput())
      {
        //make sure to wait at least one second before trying to set up again
        Log("%s: io operation failed, retry to setup", m_name.c_str());
        USleep(Max(1000000LL - (GetTimeUs() - setuptime), 0));
        break;
      }
    }

    CloseDevice();

    Log("%s: closed", m_name.c_str());
  }

  Log("%s: stopped", m_name.c_str());
}
Example #2
0
void CDevice::Process()
{
  if (m_output.empty())
    Log("%s: starting", m_name.c_str());
  else
    Log("%s: starting with output \"%s\"", m_name.c_str(), m_output.c_str());
      
  int64_t setuptime;

  while(!m_stop)
  {
    //keep trying to set up the device every 10 seconds
    while(!m_stop)
    {
      Log("%s: setting up", m_name.c_str());

      setuptime = GetTimeUs();
      if (!SetupDevice())
      {
        CloseDevice();
	LogError("%s: setting up failed, retrying in 10 seconds", m_name.c_str());
        USleep(10000000LL, &m_stop);
      }
      else
      {
	Log("%s: setup succeeded", m_name.c_str());
        break;
      }
    }

    //keep calling writeoutput until we're asked to stop or writeoutput fails
    while(!m_stop)
    {
      if (!WriteOutput())
      {
        //make sure to wait at least one second before trying to set up again
        USleep(Max(1000000LL - (GetTimeUs() - setuptime), 0));
        break;
      }
    }

    CloseDevice();

    Log("%s: closed", m_name.c_str());
  }

  Log("%s: stopped", m_name.c_str());
}
Example #3
0
static void local_await(long *p, long value)
/*
  Wait for (*p == value)
*/
{
  long pval;
  long nspin = 0;
#ifdef NOSPIN
  long spinlim = 100;
  long waittim = 10000;
#else
  long spinlim = 100000000;
  long waittim = 100000;
#endif  
  extern void flush_send_q(void);

  while ((pval = local_flag(p)) != value) {

    if (pval && (pval != value)) {
      fprintf(stdout,"%2ld: invalid value=%ld, local_flag=%lx %ld\n", 
              TCGMSG_nodeid, value, (unsigned long)p, pval);
      fflush(stdout);
      exit(1);
    }
    nspin++;
    if((nspin&7)==0)flush_send_q();
    if (nspin < spinlim)
      Busy(100);
    else 
      USleep(waittim);
  }
}
Example #4
0
static
enum ReturnCode RunCmd(struct UserDataItem* pData)
{
    Trace(pData, "RunCmd");

    if (pData->m_magic != CMagic) return retErr;
    if (GModParTraceOn) printk("CMagic Ok\n");

    // validate addr range
    if (pData->m_addr < CPhysStart && pData->m_addr >= CPhysEnd) return retErrRange;

    // pa --> va
    //unsigned long addr = pData->addr + GJumpToVa;
    //unsigned long addr = pData->addr + 0x754f8000;  // ok
    //unsigned long addr = phys_to_virt(pData->addr);
    unsigned long addr = pData->m_addr + (S3C64XX_VA_GPIO - S3C64XX_PA_GPIO); // ok

    if (pData->m_cmd == cmdRead)
    {
        if (!GModParDisableRead) pData->m_value = __raw_readl(addr);
    }
    else
        RunWrite(addr, pData->m_value, pData->m_mask);        

    if (pData->m_usleep != 0) USleep(pData->m_usleep);

    return retOk;
}
//_________________________________________________________________________________
TWANControler::~TWANControler ()
{
	Disconnect ();
	USleep ();
	fServer->Close ();
	fTCPRemote.RemoveAll();
}
Example #6
0
int tls_write_all(rdpTls* tls, const BYTE* data, int length)
{
	int status;
	int offset = 0;
	BIO* bio = tls->bio;

	while (offset < length)
	{
		status = BIO_write(bio, &data[offset], length - offset);

		if (status > 0)
		{
			offset += status;
		}
		else
		{
			if (!BIO_should_retry(bio))
				return -1;

			if (BIO_write_blocked(bio))
				status = BIO_wait_write(bio, 100);
			else if (BIO_read_blocked(bio))
				status = BIO_wait_read(bio, 100);
			else
				USleep(100);

			if (status < 0)
				return -1;
		}
	}

	return length;
}
Example #7
0
int transport_write(rdpTransport* transport, STREAM* s)
{
	int status = -1;
	int length;

	length = stream_get_length(s);
	stream_set_pos(s, 0);

#ifdef WITH_DEBUG_TRANSPORT
	if (length > 0)
	{
		printf("Local > Remote\n");
		winpr_HexDump(s->data, length);
	}
#endif

	while (length > 0)
	{
		if (transport->layer == TRANSPORT_LAYER_TLS)
			status = tls_write(transport->TlsOut, stream_get_tail(s), length);
		else if (transport->layer == TRANSPORT_LAYER_TCP)
			status = tcp_write(transport->TcpOut, stream_get_tail(s), length);
		else if (transport->layer == TRANSPORT_LAYER_TSG)
			status = tsg_write(transport->tsg, stream_get_tail(s), length);

		if (status < 0)
			break; /* error occurred */

		if (status == 0)
		{
			/* when sending is blocked in nonblocking mode, the receiving buffer should be checked */
			if (!transport->blocking)
			{
				/* and in case we do have buffered some data, we set the event so next loop will get it */
				if (transport_read_nonblocking(transport) > 0)
					SetEvent(transport->ReceiveEvent);
			}

			if (transport->layer == TRANSPORT_LAYER_TLS)
				tls_wait_write(transport->TlsOut);
			else if (transport->layer == TRANSPORT_LAYER_TCP)
				tcp_wait_write(transport->TcpOut);
			else
				USleep(transport->SleepInterval);
		}

		length -= status;
		stream_seek(s, status);
	}

	if (status < 0)
	{
		/* A write error indicates that the peer has dropped the connection */
		transport->layer = TRANSPORT_LAYER_CLOSED;
	}

	return status;
}
Example #8
0
static void* tsmf_stream_playback_func(void* arg)
{
	TSMF_SAMPLE* sample;
	TSMF_STREAM* stream = (TSMF_STREAM*) arg;
	TSMF_PRESENTATION* presentation = stream->presentation;

	DEBUG_DVC("in %d", stream->stream_id);

	if (stream->major_type == TSMF_MAJOR_TYPE_AUDIO &&
		stream->sample_rate && stream->channels && stream->bits_per_sample)
	{
		if (stream->decoder)
		{
			if (stream->decoder->GetDecodedData)
			{
				stream->audio = tsmf_load_audio_device(
					presentation->audio_name && presentation->audio_name[0] ? presentation->audio_name : NULL,
					presentation->audio_device && presentation->audio_device[0] ? presentation->audio_device : NULL);
				if (stream->audio)
				{
					stream->audio->SetFormat(stream->audio,
						stream->sample_rate, stream->channels, stream->bits_per_sample);
				}
			}
		}
	}

	while (!(WaitForSingleObject(stream->stopEvent, 0) == WAIT_OBJECT_0))
	{
		tsmf_stream_process_ack(stream);
		sample = tsmf_stream_pop_sample(stream, 1);

		if (sample)
			tsmf_sample_playback(sample);
		else
			USleep(5000);
	}

	if (stream->eos || presentation->eos)
	{
		while ((sample = tsmf_stream_pop_sample(stream, 1)) != NULL)
			tsmf_sample_playback(sample);
	}

	if (stream->audio)
	{
		stream->audio->Free(stream->audio);
		stream->audio = NULL;
	}

	SetEvent(stream->stopEvent);

	DEBUG_DVC("out %d", stream->stream_id);

	return NULL;
}
Example #9
0
static int transport_wait_for_read(rdpTransport* transport)
{
	rdpTcp *tcpIn = transport->TcpIn;

	if (tcpIn->readBlocked)
	{
		return tcp_wait_read(tcpIn, 10);
	}
	else if (tcpIn->writeBlocked)
	{
		return tcp_wait_write(tcpIn, 10);
	}

	USleep(1000);
	return 0;
}
Example #10
0
static int transport_wait_for_write(rdpTransport* transport)
{
	rdpTcp *tcpOut;

	tcpOut = transport->SplitInputOutput ? transport->TcpOut : transport->TcpIn;
	if (tcpOut->writeBlocked)
	{
		return tcp_wait_write(tcpOut, 10);
	}
	else if (tcpOut->readBlocked)
	{
		return tcp_wait_read(tcpOut, 10);
	}

	USleep(1000);
	return 0;
}
Example #11
0
int transport_read_layer(rdpTransport* transport, BYTE* data, int bytes)
{
	int read = 0;
	int status = -1;

	while (read < bytes)
	{
		if (transport->layer == TRANSPORT_LAYER_TLS)
			status = tls_read(transport->TlsIn, data + read, bytes - read);
		else if (transport->layer == TRANSPORT_LAYER_TCP)
			status = tcp_read(transport->TcpIn, data + read, bytes - read);
		else if (transport->layer == TRANSPORT_LAYER_TSG)
			status = tsg_read(transport->tsg, data + read, bytes - read);
		else if (transport->layer == TRANSPORT_LAYER_TSG_TLS) {
			status = tls_read(transport->TsgTls, data + read, bytes - read);
		}

		/* blocking means that we can't continue until this is read */

		if (!transport->blocking)
			return status;

		if (status < 0)
		{
			/* A read error indicates that the peer has dropped the connection */
			transport->layer = TRANSPORT_LAYER_CLOSED;
			return status;
		}

		read += status;

		if (status == 0)
		{
			/*
			 * instead of sleeping, we should wait timeout on the
			 * socket but this only happens on initial connection
			 */
			USleep(transport->SleepInterval);
		}
	}

	return read;
}
Example #12
0
static BOOL test_sleep_tsdiff(UINT32* old_sec, UINT32* old_usec, UINT32 new_sec,
                              UINT32 new_usec)
{
	INT32 sec, usec;

	if ((*old_sec == 0) && (*old_usec == 0))
	{
		*old_sec = new_sec;
		*old_usec = new_usec;
		return TRUE;
	}

	sec = new_sec - *old_sec;
	usec = new_usec - *old_usec;

	if ((sec < 0) || ((sec == 0) && (usec < 0)))
	{
		WLog_ERR(TAG, "Invalid time stamp detected.");
		return FALSE;
	}

	*old_sec = new_sec;
	*old_usec = new_usec;

	while (usec < 0)
	{
		usec += 1000000;
		sec--;
	}

	if (sec > 0)
		Sleep(sec * 1000);

	if (usec > 0)
		USleep(usec);

	return TRUE;
}
Example #13
0
static BOOL test_sleep_tsdiff(UINT32 *old_sec, UINT32 *old_usec, UINT32 new_sec, UINT32 new_usec)
{
	INT32 sec, usec;

	if (*old_sec==0 && *old_usec==0)
	{
		*old_sec = new_sec;
		*old_usec = new_usec;
		return TRUE;
	}

	sec = new_sec - *old_sec;
	usec = new_usec - *old_usec;

	if (sec<0 || (sec==0 && usec<0))
	{
		printf("Invalid time stamp detected.\n");
		return FALSE;
	}

	*old_sec = new_sec;
	*old_usec = new_usec;
	
	while (usec < 0) 
	{
		usec += 1000000;
		sec--;
	}
	
	if (sec > 0)
		Sleep(sec * 1000);
	
	if (usec > 0)
		USleep(usec);
	
	return TRUE;
}
Example #14
0
HttpResponse* http_response_recv(rdpTls* tls)
{
	wStream* s;
	int size;
	int count;
	int status;
	int position;
	char* line;
	char* buffer;
	char* header;
	char* payload;
	int bodyLength;
	int payloadOffset;
	HttpResponse* response;

	size = 1024;
	payload = NULL;
	payloadOffset = 0;

	s = Stream_New(NULL, size);

	if (!s)
		goto out_free;

	buffer = (char*) Stream_Buffer(s);

	response = http_response_new();

	if (!response)
		goto out_free;

	response->ContentLength = 0;

	while (TRUE)
	{
		while (!payloadOffset)
		{
			status = BIO_read(tls->bio, Stream_Pointer(s), Stream_Capacity(s) - Stream_GetPosition(s));

			if (status <= 0)
			{
				if (!BIO_should_retry(tls->bio))
					goto out_error;

				USleep(100);
				continue;
			}

#ifdef HAVE_VALGRIND_MEMCHECK_H
			VALGRIND_MAKE_MEM_DEFINED(Stream_Pointer(s), status);
#endif

			Stream_Seek(s, status);

			if (Stream_GetRemainingLength(s) < 1024)
			{
				Stream_EnsureRemainingCapacity(s, 1024);
				buffer = (char*) Stream_Buffer(s);
				payload = &buffer[payloadOffset];
			}

			position = Stream_GetPosition(s);

			if (position >= 4)
			{
				line = string_strnstr(buffer, "\r\n\r\n", position);

				if (line)
				{
					payloadOffset = (line - buffer) + 4;
					payload = &buffer[payloadOffset];
				}
			}
		}

		if (payloadOffset)
		{
			count = 0;
			line = buffer;

			position = Stream_GetPosition(s);

			while ((line = string_strnstr(line, "\r\n", payloadOffset - (line - buffer) - 2)))
			{
				line += 2;
				count++;
			}

			response->count = count;

			if (count)
			{
				response->lines = (char**) calloc(response->count, sizeof(char*));

				if (!response->lines)
					goto out_error;
			}

			header = (char*) malloc(payloadOffset);

			if (!header)
				goto out_error;

			CopyMemory(header, buffer, payloadOffset);
			header[payloadOffset - 1] = '\0';
			header[payloadOffset - 2] = '\0';

			count = 0;
			line = strtok(header, "\r\n");

			while (line && response->lines)
			{
				response->lines[count] = _strdup(line);

				if (!response->lines[count])
					goto out_error;

				line = strtok(NULL, "\r\n");
				count++;
			}

			free(header);

			if (!http_response_parse_header(response))
				goto out_error;

			response->BodyLength = Stream_GetPosition(s) - payloadOffset;

			if (response->BodyLength > 0)
			{
				response->BodyContent = (BYTE*) malloc(response->BodyLength);

				if (!response->BodyContent)
					goto out_error;

				CopyMemory(response->BodyContent, payload, response->BodyLength);
			}

			bodyLength = 0; /* expected body length */

			if (response->ContentType)
			{
				if (_stricmp(response->ContentType, "text/plain") == 0)
				{
					bodyLength = response->ContentLength;
				}
			}

			if (bodyLength != response->BodyLength)
			{
				WLog_WARN(TAG, "http_response_recv: %s unexpected body length: actual: %d, expected: %d",
						response->ContentType, response->ContentLength, response->BodyLength);
			}

			break;
		}

		if (Stream_GetRemainingLength(s) < 1024)
		{
			Stream_EnsureRemainingCapacity(s, 1024);
			buffer = (char*) Stream_Buffer(s);
			payload = &buffer[payloadOffset];
		}
	}

	Stream_Free(s, TRUE);
	return response;
out_error:
	http_response_free(response);
out_free:
	Stream_Free(s, TRUE);
	return NULL;
}
Example #15
0
HttpResponse* http_response_recv(rdpTls* tls)
{
    BYTE* p;
    int nbytes;
    int length;
    int status;
    BYTE* buffer;
    char* content;
    char* header_end;
    HttpResponse* http_response;
    nbytes = 0;
    length = 10000;
    content = NULL;

    buffer = calloc(length, 1);

    if (!buffer)
        return NULL;

    http_response = http_response_new();

    if (!http_response)
        goto out_free;

    p = buffer;
    http_response->ContentLength = 0;

    while (TRUE)
    {
        while (nbytes < 5)
        {
            status = BIO_read(tls->bio, p, length - nbytes);

            if (status <= 0)
            {
                if (!BIO_should_retry(tls->bio))
                    goto out_error;

                USleep(100);
                continue;
            }

#ifdef HAVE_VALGRIND_MEMCHECK_H
            VALGRIND_MAKE_MEM_DEFINED(p, status);
#endif
            nbytes += status;
            p = (BYTE*) &buffer[nbytes];
        }

        header_end = strstr((char*) buffer, "\r\n\r\n");

        if (!header_end)
        {
            WLog_ERR(TAG, "invalid response:");
            winpr_HexDump(TAG, WLOG_ERROR, buffer, status);
            goto out_error;
        }

        header_end += 2;

        if (header_end != NULL)
        {
            int count;
            char* line;
            header_end[0] = '\0';
            header_end[1] = '\0';
            content = header_end + 2;
            count = 0;
            line = (char*) buffer;

            while ((line = strstr(line, "\r\n")) != NULL)
            {
                line++;
                count++;
            }

            http_response->count = count;

            if (count)
            {
                http_response->lines = (char**) calloc(http_response->count, sizeof(char*));

                if (!http_response->lines)
                    goto out_error;
            }

            count = 0;
            line = strtok((char*) buffer, "\r\n");

            while ((line != NULL) && http_response->lines)
            {
                http_response->lines[count] = _strdup(line);

                if (!http_response->lines[count])
                    goto out_error;

                line = strtok(NULL, "\r\n");
                count++;
            }

            if (!http_response_parse_header(http_response))
                goto out_error;

            http_response->bodyLen = nbytes - (content - (char*)buffer);

            if (http_response->bodyLen > 0)
            {
                http_response->BodyContent = (BYTE*) malloc(http_response->bodyLen);

                if (!http_response->BodyContent)
                    goto out_error;

                CopyMemory(http_response->BodyContent, content, http_response->bodyLen);
            }

            break;
        }

        if ((length - nbytes) <= 0)
        {
            length *= 2;
            buffer = realloc(buffer, length);
            p = (BYTE*) &buffer[nbytes];
        }
    }

    free(buffer);
    return http_response;
out_error:
    http_response_free(http_response);
out_free:
    free(buffer);
    return NULL;
}
Example #16
0
static void* tsmf_stream_playback_func(void *arg)
{
	HANDLE hdl[2];
	TSMF_SAMPLE* sample = NULL;
	TSMF_STREAM* stream = (TSMF_STREAM *) arg;
	TSMF_PRESENTATION* presentation = stream->presentation;
	UINT error = CHANNEL_RC_OK;
	DWORD status;

	DEBUG_TSMF("in %d", stream->stream_id);

	if (stream->major_type == TSMF_MAJOR_TYPE_AUDIO &&
			stream->sample_rate && stream->channels && stream->bits_per_sample)
	{
		if (stream->decoder)
		{
			if (stream->decoder->GetDecodedData)
			{
				stream->audio = tsmf_load_audio_device(
					presentation->audio_name && presentation->audio_name[0] ? presentation->audio_name : NULL,
					presentation->audio_device && presentation->audio_device[0] ? presentation->audio_device : NULL);

				if (stream->audio)
				{
					stream->audio->SetFormat(stream->audio, stream->sample_rate, stream->channels, stream->bits_per_sample);
				}
			}
		}
	}

	hdl[0] = stream->stopEvent;
	hdl[1] = Queue_Event(stream->sample_list);

	while (1)
	{
		status = WaitForMultipleObjects(2, hdl, FALSE, 1000);

		if (status == WAIT_FAILED)
		{
			error = GetLastError();
			WLog_ERR(TAG, "WaitForMultipleObjects failed with error %lu!", error);
			break;
		}

		status = WaitForSingleObject(stream->stopEvent, 0);

		if (status == WAIT_FAILED)
		{
			error = GetLastError();
			WLog_ERR(TAG, "WaitForSingleObject failed with error %lu!", error);
			break;
		}

		if (status == WAIT_OBJECT_0)
			break;

		if (stream->decoder)
			if (stream->decoder->BufferLevel)
				stream->currentBufferLevel = stream->decoder->BufferLevel(stream->decoder);

		sample = tsmf_stream_pop_sample(stream, 0);

		if (sample && !tsmf_sample_playback(sample))
		{
			WLog_ERR(TAG, "error playing sample");
			error = ERROR_INTERNAL_ERROR;
			break;
		}

		if (stream->currentBufferLevel > stream->minBufferLevel)
			USleep(1000);
	}


	if (stream->audio)
	{
		stream->audio->Free(stream->audio);
		stream->audio = NULL;
	}

	if (error && stream->rdpcontext)
		setChannelError(stream->rdpcontext, error, "tsmf_stream_playback_func reported an error");

	DEBUG_TSMF("out %d", stream->stream_id);
	ExitThread(0);
	return NULL;
}
Example #17
0
static void* tsmf_stream_ack_func(void *arg)
{
	HANDLE hdl[2];
	TSMF_STREAM* stream = (TSMF_STREAM*) arg;
	UINT error = CHANNEL_RC_OK;
	DEBUG_TSMF("in %d", stream->stream_id);

	hdl[0] = stream->stopEvent;
	hdl[1] = Queue_Event(stream->sample_ack_list);

	while (1)
	{
		DWORD ev = WaitForMultipleObjects(2, hdl, FALSE, 1000);

		if (ev == WAIT_FAILED)
		{
			error = GetLastError();
			WLog_ERR(TAG, "WaitForMultipleObjects failed with error %lu!", error);
			break;
		}

		if (stream->decoder)
			if (stream->decoder->BufferLevel)
				stream->currentBufferLevel = stream->decoder->BufferLevel(stream->decoder);

		if (stream->eos)
		{
			while ((stream->currentBufferLevel > 0) || !(tsmf_stream_process_ack(stream, TRUE)))
			{
				DEBUG_TSMF("END OF STREAM PROCESSING!");
				if (stream->decoder->BufferLevel)
					stream->currentBufferLevel = stream->decoder->BufferLevel(stream->decoder);
				else
					stream->currentBufferLevel = 1;

				USleep(1000);
			}

			tsmf_send_eos_response(stream->eos_channel_callback, stream->eos_message_id);
			stream->eos = 0;

			if (stream->delayed_stop)
			{
				DEBUG_TSMF("Finishing delayed stream stop, now that eos has processed.");
				tsmf_stream_flush(stream);

				if (stream->decoder->Control)
					stream->decoder->Control(stream->decoder, Control_Stop, NULL);
			}
		}

		/* Stream stopped force all of the acks to happen */
		if (ev == WAIT_OBJECT_0)
		{
			DEBUG_TSMF("ack: Stream stopped!");
			while(1)
			{
				if (tsmf_stream_process_ack(stream, TRUE))
					break;
				USleep(1000);
			}
			break;
		}

		if (tsmf_stream_process_ack(stream, FALSE))
			continue;

		if (stream->currentBufferLevel > stream->minBufferLevel)
			USleep(1000);
	}

	if (error && stream->rdpcontext)
		setChannelError(stream->rdpcontext, error, "tsmf_stream_ack_func reported an error");

	DEBUG_TSMF("out %d", stream->stream_id);
	ExitThread(0);
	return NULL;
}
Example #18
0
static BOOL tsmf_sample_playback_video(TSMF_SAMPLE* sample)
{
	UINT64 t;
	TSMF_VIDEO_FRAME_EVENT event;
	TSMF_STREAM* stream = sample->stream;
	TSMF_PRESENTATION* presentation = stream->presentation;
	TSMF_CHANNEL_CALLBACK* callback = (TSMF_CHANNEL_CALLBACK*) sample->channel_callback;
	TsmfClientContext* tsmf = (TsmfClientContext*) callback->plugin->pInterface;

	DEBUG_TSMF("MessageId %d EndTime %d data_size %d consumed.",
			   sample->sample_id, (int) sample->end_time, sample->data_size);

	if (sample->data)
	{
		t = get_current_time();

		/* Start time is more reliable than end time as some stream types seem to have incorrect
		 * end times from the server
		 */
		if (stream->next_start_time > t &&
				((sample->start_time >= presentation->audio_start_time) ||
				((sample->start_time < stream->last_start_time) && (!sample->invalidTimestamps))))
		{
			USleep((stream->next_start_time - t) / 10);
		}

		stream->next_start_time = t + sample->duration - 50000;

		ZeroMemory(&event, sizeof(TSMF_VIDEO_FRAME_EVENT));

		event.frameData = sample->data;
		event.frameSize = sample->decoded_size;
		event.framePixFmt = sample->pixfmt;
		event.frameWidth = sample->stream->width;
		event.frameHeight = sample->stream->height;

#if 0
		/* Dump a .ppm image for every 30 frames. Assuming the frame is in YUV format, we
		   extract the Y values to create a grayscale image. */
		static int frame_id = 0;
		char buf[100];
		FILE *fp;

		if ((frame_id % 30) == 0)
		{
			sprintf_s(buf, sizeof(buf), "/tmp/FreeRDP_Frame_%d.ppm", frame_id);
			fp = fopen(buf, "wb");
			fwrite("P5\n", 1, 3, fp);
			sprintf_s(buf, sizeof(buf), "%d %d\n", sample->stream->width, sample->stream->height);
			fwrite(buf, 1, strlen(buf), fp);
			fwrite("255\n", 1, 4, fp);
			fwrite(sample->data, 1, sample->stream->width * sample->stream->height, fp);
			fflush(fp);
			fclose(fp);
		}

		frame_id++;
#endif

		/* The frame data ownership is passed to the event object, and is freed after the event is processed. */
		sample->data = NULL;
		sample->decoded_size = 0;

		if (tsmf->FrameEvent)
			tsmf->FrameEvent(tsmf, &event);

		free(event.frameData);

		if(event.visibleRects != NULL)
			free(event.visibleRects);
	}
	return TRUE;
}
Example #19
0
// --------------------------------------------------------------------------
int main(int argc, char *argv[]) {

    BoxLib::Initialize(argc,argv);

    // A flag you need for broadcasting across MPI groups. We always broadcast
    // the data to the sidecar group from the IOProcessor on the compute group.
    int MPI_IntraGroup_Broadcast_Rank;
    int myProcAll(ParallelDescriptor::MyProcAll());
    int nSidecarProcs(0), nSidecarProcsFromParmParse(-3), sidecarSignal(MySignal);
    int ts(0), nSteps(10);
    ParmParse pp;

    pp.get("nSidecars", nSidecarProcsFromParmParse);

    if(ParallelDescriptor::IOProcessor()) {
      std::cout << "nSidecarProcs from parmparse = " << nSidecarProcsFromParmParse << std::endl;
    }

    Array<int> howManySidecars(3);
    howManySidecars[0] = nSidecarProcsFromParmParse;
    howManySidecars[1] = 1;
    howManySidecars[2] = 4;

    for(int hMS(0); hMS < howManySidecars.size(); ++hMS) {
      nSidecarProcs = howManySidecars[hMS];
      if(ParallelDescriptor::IOProcessor()) {
        std::cout << myProcAll << ":: Resizing sidecars = " << nSidecarProcs << std::endl;
      }
      ParallelDescriptor::SetNProcsSidecar(nSidecarProcs);
      MPI_IntraGroup_Broadcast_Rank = ParallelDescriptor::IOProcessor() ? MPI_ROOT : MPI_PROC_NULL;

      if(ParallelDescriptor::InSidecarGroup()) {
        std::cout << myProcAll << ":: Calling SidecarEventLoop()." << std::endl;
        SidecarEventLoop();
      } else {
        for(int i(ts); i < ts + nSteps; ++i) {  // ----- do time steps.
          if(ParallelDescriptor::IOProcessor()) {
            std::cout << myProcAll << ":: Doing timestep = " << i << std::endl;
          }
	  if(nSidecarProcs > 0) {
            sidecarSignal = MySignal;
            ParallelDescriptor::Bcast(&sidecarSignal, 1, MPI_IntraGroup_Broadcast_Rank, ParallelDescriptor::CommunicatorInter());
            ParallelDescriptor::Bcast(&i, 1, MPI_IntraGroup_Broadcast_Rank, ParallelDescriptor::CommunicatorInter());
	  }
        }
	ts += nSteps;

	if(nSidecarProcs > 0) {
          // ---- stop the sidecars
          sidecarSignal = ParallelDescriptor::SidecarQuitSignal;
          ParallelDescriptor::Bcast(&sidecarSignal, 1, MPI_IntraGroup_Broadcast_Rank, ParallelDescriptor::CommunicatorInter());
	}
      }

      std::cout << myProcAll << ":: Finished timesteps for hMS = " << hMS << std::endl;
      USleep(1.4);
      ParallelDescriptor::Barrier();

    }


    nSidecarProcs = 0;
    ParallelDescriptor::SetNProcsSidecar(nSidecarProcs);

    USleep(0.3);
    ParallelDescriptor::Barrier();

    std::cout << "_calling Finalize()" << std::endl;
    BoxLib::Finalize();
    return 0;
}
Example #20
0
BOOL http_proxy_connect(BIO* bufferedBio, const char* hostname, UINT16 port)
{
	int status;
	wStream* s;
	char port_str[10], recv_buf[256], *eol;
	int resultsize;
	_itoa_s(port, port_str, sizeof(port_str), 10);
	s = Stream_New(NULL, 200);
	Stream_Write(s, "CONNECT ", 8);
	Stream_Write(s, hostname, strlen(hostname));
	Stream_Write_UINT8(s, ':');
	Stream_Write(s, port_str, strlen(port_str));
	Stream_Write(s, " HTTP/1.1" CRLF "Host: ", 17);
	Stream_Write(s, hostname, strlen(hostname));
	Stream_Write_UINT8(s, ':');
	Stream_Write(s, port_str, strlen(port_str));
	Stream_Write(s, CRLF CRLF, 4);
	status = BIO_write(bufferedBio, Stream_Buffer(s), Stream_GetPosition(s));

	if (status != Stream_GetPosition(s))
	{
		WLog_ERR(TAG, "HTTP proxy: failed to write CONNECT request");
		return FALSE;
	}

	Stream_Free(s, TRUE);
	s = NULL;
	/* Read result until CR-LF-CR-LF.
	 * Keep recv_buf a null-terminated string. */
	memset(recv_buf, '\0', sizeof(recv_buf));
	resultsize = 0;

	while (strstr(recv_buf, CRLF CRLF) == NULL)
	{
		if (resultsize >= sizeof(recv_buf) - 1)
		{
			WLog_ERR(TAG, "HTTP Reply headers too long.");
			return FALSE;
		}

		status = BIO_read(bufferedBio, (BYTE*)recv_buf + resultsize, sizeof(recv_buf) - resultsize - 1);

		if (status < 0)
		{
			/* Error? */
			if (BIO_should_retry(bufferedBio))
			{
				USleep(100);
				continue;
			}

			WLog_ERR(TAG, "Failed reading reply from HTTP proxy (Status %d)", status);
			return FALSE;
		}
		else if (status == 0)
		{
			/* Error? */
			WLog_ERR(TAG, "Failed reading reply from HTTP proxy (BIO_read returned zero)");
			return FALSE;
		}

		resultsize += status;
	}

	/* Extract HTTP status line */
	eol = strchr(recv_buf, '\r');

	if (!eol)
	{
		/* should never happen */
		return FALSE;
	}

	*eol = '\0';
	WLog_INFO(TAG, "HTTP Proxy: %s", recv_buf);

	if (strlen(recv_buf) < 12)
	{
		return FALSE;
	}

	recv_buf[7] = 'X';

	if (strncmp(recv_buf, "HTTP/1.X 200", 12))
		return FALSE;

	return TRUE;
}
Example #21
0
HttpResponse* http_response_recv(rdpTls* tls, BOOL readContentLength)
{
	size_t size;
	size_t position;
	size_t bodyLength = 0;
	size_t payloadOffset;
	HttpResponse* response;
	size = 2048;
	payloadOffset = 0;
	response = http_response_new();

	if (!response)
		return NULL;

	response->ContentLength = 0;

	while (payloadOffset == 0)
	{
		size_t s;
		char* end;
		/* Read until we encounter \r\n\r\n */
		int status = BIO_read(tls->bio, Stream_Pointer(response->data), 1);

		if (status <= 0)
		{
			if (!BIO_should_retry(tls->bio))
			{
				WLog_ERR(TAG, "%s: Retries exceeded", __FUNCTION__);
				ERR_print_errors_cb(print_bio_error, NULL);
				goto out_error;
			}

			USleep(100);
			continue;
		}

#ifdef HAVE_VALGRIND_MEMCHECK_H
		VALGRIND_MAKE_MEM_DEFINED(Stream_Pointer(response->data), status);
#endif
		Stream_Seek(response->data, (size_t)status);

		if (!Stream_EnsureRemainingCapacity(response->data, 1024))
			goto out_error;

		position = Stream_GetPosition(response->data);

		if (position < 4)
			continue;
		else if (position > RESPONSE_SIZE_LIMIT)
		{
			WLog_ERR(TAG, "Request header too large! (%"PRIdz" bytes) Aborting!", bodyLength);
			goto out_error;
		}

		/* Always check at most the lase 8 bytes for occurance of the desired
		 * sequence of \r\n\r\n */
		s = (position > 8) ? 8 : position;
		end = (char*)Stream_Pointer(response->data) - s;

		if (string_strnstr(end, "\r\n\r\n", s) != NULL)
			payloadOffset = Stream_GetPosition(response->data);
	}

	if (payloadOffset)
	{
		size_t count = 0;
		char* buffer = (char*)Stream_Buffer(response->data);
		char* line = (char*) Stream_Buffer(response->data);

		while ((line = string_strnstr(line, "\r\n", payloadOffset - (line - buffer) - 2UL)))
		{
			line += 2;
			count++;
		}

		response->count = count;

		if (count)
		{
			response->lines = (char**) calloc(response->count, sizeof(char*));

			if (!response->lines)
				goto out_error;
		}

		buffer[payloadOffset - 1] = '\0';
		buffer[payloadOffset - 2] = '\0';
		count = 0;
		line = strtok(buffer, "\r\n");

		while (line && (response->count > count))
		{
			response->lines[count] = line;
			line = strtok(NULL, "\r\n");
			count++;
		}

		if (!http_response_parse_header(response))
			goto out_error;

		response->BodyLength = Stream_GetPosition(response->data) - payloadOffset;
		bodyLength = response->BodyLength; /* expected body length */

		if (readContentLength)
		{
			const char* cur = response->ContentType;

			while (cur != NULL)
			{
				if (http_use_content_length(cur))
				{
					if (response->ContentLength < RESPONSE_SIZE_LIMIT)
						bodyLength = response->ContentLength;

					break;
				}

				cur = strchr(cur, ';');
			}
		}

		if (bodyLength > RESPONSE_SIZE_LIMIT)
		{
			WLog_ERR(TAG, "Expected request body too large! (%"PRIdz" bytes) Aborting!", bodyLength);
			goto out_error;
		}

		/* Fetch remaining body! */
		while (response->BodyLength < bodyLength)
		{
			int status;

			if (!Stream_EnsureRemainingCapacity(response->data, bodyLength - response->BodyLength))
				goto out_error;

			status = BIO_read(tls->bio, Stream_Pointer(response->data), bodyLength - response->BodyLength);

			if (status <= 0)
			{
				if (!BIO_should_retry(tls->bio))
				{
					WLog_ERR(TAG, "%s: Retries exceeded", __FUNCTION__);
					ERR_print_errors_cb(print_bio_error, NULL);
					goto out_error;
				}

				USleep(100);
				continue;
			}

			Stream_Seek(response->data, (size_t)status);
			response->BodyLength += (unsigned long)status;

			if (response->BodyLength > RESPONSE_SIZE_LIMIT)
			{
				WLog_ERR(TAG, "Request body too large! (%"PRIdz" bytes) Aborting!", response->BodyLength);
				goto out_error;
			}
		}

		if (response->BodyLength > 0)
			response->BodyContent = &(Stream_Buffer(response->data))[payloadOffset];

		if (bodyLength != response->BodyLength)
		{
			WLog_WARN(TAG, "%s: %s unexpected body length: actual: %d, expected: %d",
			          __FUNCTION__, response->ContentType, response->BodyLength, bodyLength);

			if (bodyLength > 0)
				response->BodyLength = MIN(bodyLength, response->BodyLength);
		}
	}

	return response;
out_error:
	http_response_free(response);
	return NULL;
}
Example #22
0
int transport_write(rdpTransport* transport, wStream* s)
{
	int length;
	int status = -1;

	WaitForSingleObject(transport->WriteMutex, INFINITE);

	length = Stream_GetPosition(s);
	Stream_SetPosition(s, 0);

#ifdef WITH_DEBUG_TRANSPORT
	if (length > 0)
	{
		fprintf(stderr, "Local > Remote\n");
		winpr_HexDump(Stream_Buffer(s), length);
	}
#endif

	if (length > 0)
	{
		WLog_Packet(transport->log, WLOG_TRACE, Stream_Buffer(s), length, WLOG_PACKET_OUTBOUND);
	}

	while (length > 0)
	{
		if (transport->layer == TRANSPORT_LAYER_TLS)
			status = tls_write(transport->TlsOut, Stream_Pointer(s), length);
		else if (transport->layer == TRANSPORT_LAYER_TCP)
			status = tcp_write(transport->TcpOut, Stream_Pointer(s), length);
		else if (transport->layer == TRANSPORT_LAYER_TSG)
			status = tsg_write(transport->tsg, Stream_Pointer(s), length);
		else if (transport->layer == TRANSPORT_LAYER_TSG_TLS)
			status = tls_write(transport->TsgTls, Stream_Pointer(s), length);

		if (status < 0)
			break; /* error occurred */

		if (status == 0)
		{
			/* when sending is blocked in nonblocking mode, the receiving buffer should be checked */
			if (!transport->blocking)
			{
				/* and in case we do have buffered some data, we set the event so next loop will get it */
				if (transport_read_nonblocking(transport) > 0)
					SetEvent(transport->ReceiveEvent);
			}

			if (transport->layer == TRANSPORT_LAYER_TLS)
				tls_wait_write(transport->TlsOut);
			else if (transport->layer == TRANSPORT_LAYER_TCP)
				tcp_wait_write(transport->TcpOut);
			else if (transport->layer == TRANSPORT_LAYER_TSG_TLS)
				tls_wait_write(transport->TsgTls);
			else
				USleep(transport->SleepInterval);
		}

		length -= status;
		Stream_Seek(s, status);
	}

	if (status < 0)
	{
		/* A write error indicates that the peer has dropped the connection */
		transport->layer = TRANSPORT_LAYER_CLOSED;
	}

	if (s->pool)
		Stream_Release(s);

	ReleaseMutex(transport->WriteMutex);

	return status;
}
Example #23
0
int tls_write_all(rdpTls* tls, const BYTE* data, int length)
{
	int status, nchunks, commitedBytes;
	rdpTcp *tcp;
#ifdef HAVE_POLL_H
	struct pollfd pollfds;
#else
	fd_set rset, wset;
	fd_set *rsetPtr, *wsetPtr;
	struct timeval tv;
#endif
	BIO* bio = tls->bio;
	DataChunk chunks[2];

	BIO* bufferedBio = findBufferedBio(bio);

	if (!bufferedBio)
	{
		DEBUG_WARN( "%s: error unable to retrieve the bufferedBio in the BIO chain\n", __FUNCTION__);
		return -1;
	}

	tcp = (rdpTcp*) bufferedBio->ptr;

	do
	{
		status = BIO_write(bio, data, length);

		if (status > 0)
			break;

		if (!BIO_should_retry(bio))
			return -1;
#ifdef HAVE_POLL_H
		pollfds.fd = tcp->sockfd;
		pollfds.revents = 0;
		pollfds.events = 0;

		if (tcp->writeBlocked)
		{
			pollfds.events |= POLLOUT;
		}
		else if (tcp->readBlocked)
		{
			pollfds.events |= POLLIN;
		}
		else
		{
			DEBUG_WARN( "%s: weird we're blocked but the underlying is not read or write blocked !\n", __FUNCTION__);
			USleep(10);
			continue;
		}

		do
		{
			status = poll(&pollfds, 1, 100);
		}
		while ((status < 0) && (errno == EINTR));
#else
		/* we try to handle SSL want_read and want_write nicely */
		rsetPtr = wsetPtr = NULL;

		if (tcp->writeBlocked)
		{
			wsetPtr = &wset;
			FD_ZERO(&wset);
			FD_SET(tcp->sockfd, &wset);
		}
		else if (tcp->readBlocked)
		{
			rsetPtr = &rset;
			FD_ZERO(&rset);
			FD_SET(tcp->sockfd, &rset);
		}
		else
		{
			DEBUG_WARN( "%s: weird we're blocked but the underlying is not read or write blocked !\n", __FUNCTION__);
			USleep(10);
			continue;
		}

		tv.tv_sec = 0;
		tv.tv_usec = 100 * 1000;

		status = _select(tcp->sockfd + 1, rsetPtr, wsetPtr, NULL, &tv);
#endif
		if (status < 0)
			return -1;
	}
	while (TRUE);

	/* make sure the output buffer is empty */
	commitedBytes = 0;
	while ((nchunks = ringbuffer_peek(&tcp->xmitBuffer, chunks, ringbuffer_used(&tcp->xmitBuffer))))
	{
		int i;

		for (i = 0; i < nchunks; i++)
		{
			while (chunks[i].size)
			{
				status = BIO_write(tcp->socketBio, chunks[i].data, chunks[i].size);

				if (status > 0)
				{
					chunks[i].size -= status;
					chunks[i].data += status;
					commitedBytes += status;
					continue;
				}

				if (!BIO_should_retry(tcp->socketBio))
					goto out_fail;

#ifdef HAVE_POLL_H
				pollfds.fd = tcp->sockfd;
				pollfds.events = POLLIN;
				pollfds.revents = 0;

				do
				{
					status = poll(&pollfds, 1, 100);
				}
				while ((status < 0) && (errno == EINTR));
#else
				FD_ZERO(&rset);
				FD_SET(tcp->sockfd, &rset);
				tv.tv_sec = 0;
				tv.tv_usec = 100 * 1000;

				status = _select(tcp->sockfd + 1, &rset, NULL, NULL, &tv);
#endif
				if (status < 0)
					goto out_fail;
			}

		}
	}

	ringbuffer_commit_read_bytes(&tcp->xmitBuffer, commitedBytes);
	return length;

out_fail:
	ringbuffer_commit_read_bytes(&tcp->xmitBuffer, commitedBytes);
	return -1;
}
Example #24
0
static void tsmf_sample_playback_video(TSMF_SAMPLE* sample)
{
	UINT64 t;
	RDP_VIDEO_FRAME_EVENT* vevent;
	TSMF_STREAM* stream = sample->stream;
	TSMF_PRESENTATION* presentation = stream->presentation;

	DEBUG_DVC("MessageId %d EndTime %d data_size %d consumed.",
		sample->sample_id, (int)sample->end_time, sample->data_size);

	if (sample->data)
	{
		t = get_current_time();

		if (stream->next_start_time > t &&
			(sample->end_time >= presentation->audio_start_time ||
			sample->end_time < stream->last_end_time))
		{
			USleep((stream->next_start_time - t) / 10);
		}
		stream->next_start_time = t + sample->duration - 50000;

		if (presentation->last_x != presentation->output_x ||
			presentation->last_y != presentation->output_y ||
			presentation->last_width != presentation->output_width ||
			presentation->last_height != presentation->output_height ||
			presentation->last_num_rects != presentation->output_num_rects ||
			(presentation->last_rects && presentation->output_rects &&
			memcmp(presentation->last_rects, presentation->output_rects,
			presentation->last_num_rects * sizeof(RDP_RECT)) != 0))
		{
			tsmf_presentation_restore_last_video_frame(presentation);

			presentation->last_x = presentation->output_x;
			presentation->last_y = presentation->output_y;
			presentation->last_width = presentation->output_width;
			presentation->last_height = presentation->output_height;

			if (presentation->last_rects)
			{
				free(presentation->last_rects);
				presentation->last_rects = NULL;
			}

			presentation->last_num_rects = presentation->output_num_rects;

			if (presentation->last_num_rects > 0)
			{
				presentation->last_rects = malloc(presentation->last_num_rects * sizeof(RDP_RECT));
				ZeroMemory(presentation->last_rects, presentation->last_num_rects * sizeof(RDP_RECT));

				memcpy(presentation->last_rects, presentation->output_rects,
					presentation->last_num_rects * sizeof(RDP_RECT));
			}
		}

		vevent = (RDP_VIDEO_FRAME_EVENT*) freerdp_event_new(TsmfChannel_Class, TsmfChannel_VideoFrame,
			NULL, NULL);

		vevent->frame_data = sample->data;
		vevent->frame_size = sample->decoded_size;
		vevent->frame_pixfmt = sample->pixfmt;
		vevent->frame_width = sample->stream->width;
		vevent->frame_height = sample->stream->height;
		vevent->x = presentation->output_x;
		vevent->y = presentation->output_y;
		vevent->width = presentation->output_width;
		vevent->height = presentation->output_height;

		if (presentation->output_num_rects > 0)
		{
			vevent->num_visible_rects = presentation->output_num_rects;

			vevent->visible_rects = (RDP_RECT*) malloc(presentation->output_num_rects * sizeof(RDP_RECT));
			ZeroMemory(vevent->visible_rects, presentation->output_num_rects * sizeof(RDP_RECT));

			memcpy(vevent->visible_rects, presentation->output_rects,
				presentation->output_num_rects * sizeof(RDP_RECT));
		}

		/* The frame data ownership is passed to the event object, and is freed after the event is processed. */
		sample->data = NULL;
		sample->decoded_size = 0;

		if (!tsmf_push_event(sample->channel_callback, (wMessage*) vevent))
		{
			freerdp_event_free((wMessage*) vevent);
		}

#if 0
		/* Dump a .ppm image for every 30 frames. Assuming the frame is in YUV format, we
		   extract the Y values to create a grayscale image. */
		static int frame_id = 0;
		char buf[100];
		FILE * fp;
		if ((frame_id % 30) == 0)
		{
			snprintf(buf, sizeof(buf), "/tmp/FreeRDP_Frame_%d.ppm", frame_id);
			fp = fopen(buf, "wb");
			fwrite("P5\n", 1, 3, fp);
			snprintf(buf, sizeof(buf), "%d %d\n", sample->stream->width, sample->stream->height);
			fwrite(buf, 1, strlen(buf), fp);
			fwrite("255\n", 1, 4, fp);
			fwrite(sample->data, 1, sample->stream->width * sample->stream->height, fp);
			fflush(fp);
			fclose(fp);
		}
		frame_id++;
#endif
	}
}