/*
  read_packet - Read a packet from the server and store it in the buffer

  This method reads the bytes sent by the server as a packet. All packets
  have a packet header defined as follows.

  Bytes                 Name
  -----                 ----
  3                     Packet Length
  1                     Packet Number

  Thus, the length of the packet (not including the packet header) can
  be found by reading the first 4 bytes from the server then reading
  N bytes for the packet payload.
*/
void MySQL_Packet::read_packet() {
  byte local[4];

  if (buffer != NULL)
    free(buffer);

  int avail_bytes = wait_for_client();
  while (avail_bytes < 4) {
    avail_bytes = wait_for_client();
  }

  // Read packet header
  for (int i = 0; i < 4; i++) {
    // Wait for client. Abort if no data after TIMEOUT_DATA milliseconds
    if (!wait_for_data()) {
      return;
    }
    local[i] = client->read();
  }

  // Get packet length
  packet_len = local[0];
  packet_len += (local[1] << 8);
  packet_len += ((uint32_t)local[2] << 16);
  // We must wait for slow arriving packets for Ethernet shields only.
  avail_bytes = wait_for_client();
  while (avail_bytes < packet_len) {
    avail_bytes = wait_for_client();
  }
  // Check for valid packet.
  if (packet_len < 0) {
    show_error(PACKET_ERROR, true);
    packet_len = 0;
  }
  buffer = (byte *)malloc(packet_len+4);
  if (buffer == NULL) {
    show_error(MEMORY_ERROR, true);
    return;
  }
  for (int i = 0; i < 4; i++)
    buffer[i] = local[i];

  for (int i = 4; i < packet_len+4; i++) {
    // Wait for client. Abort if no data after TIMEOUT_DATA milliseconds
    if (!wait_for_data()) {
      return;
    }
    buffer[i] = client->read();
  }
}
Esempio n. 2
0
void Client::handle_connect(Connection::connection_ptr connection, const boost::system::error_code& error)
{
    if (!error)
    {
        std::cout << "Connected" << std::endl;
        m_state = StateController::INITIALIZING;
        wait_for_data();
        m_drive_events();
    }
}
Esempio n. 3
0
/* 
 * read one byte from any source; whether from the controller,
 * the keyboard, or the aux device
 */
int
read_controller_data(KBDC p)
{
    if (availq(&kbdcp(p)->kbd)) 
        return removeq(&kbdcp(p)->kbd);
    if (availq(&kbdcp(p)->aux)) 
        return removeq(&kbdcp(p)->aux);
    if (!wait_for_data(kbdcp(p)))
        return -1;		/* timeout */
    return read_data(kbdcp(p));
}
Esempio n. 4
0
 void watch(const FuncT& f) {
     for(;;) {
         wait_for_data();
         f(
             wetness(),
             temperature(),
             atmospheric_pressure(),
             illumination()
         );
     }
 }
Esempio n. 5
0
void DecoderStack::decode_proc()
{
	optional<int64_t> sample_count;
	srd_session *session;
	srd_decoder_inst *prev_di = NULL;

	assert(_snapshot);

	// Create the session
	srd_session_new(&session);
	assert(session);

	// Create the decoders
	const unsigned int unit_size = _snapshot->unit_size();

	for (const shared_ptr<decode::Decoder> &dec : _stack)
	{
		srd_decoder_inst *const di = dec->create_decoder_inst(session, unit_size);

		if (!di)
		{
			_error_message = tr("Failed to create decoder instance");
			srd_session_destroy(session);
			return;
		}

		if (prev_di)
			srd_inst_stack (session, prev_di, di);

		prev_di = di;
	}

	// Get the intial sample count
	{
		unique_lock<mutex> input_lock(_input_mutex);
		sample_count = _sample_count = _snapshot->get_sample_count();
	}

	// Start the session
	srd_session_metadata_set(session, SRD_CONF_SAMPLERATE,
		g_variant_new_uint64((uint64_t)_samplerate));

	srd_pd_output_callback_add(session, SRD_OUTPUT_ANN,
		DecoderStack::annotation_callback, this);

	srd_session_start(session);

	do {
		decode_data(*sample_count, unit_size, session);
	} while(_error_message.isEmpty() && (sample_count = wait_for_data()));

	// Destroy the session
	srd_session_destroy(session);
}
Esempio n. 6
0
static int wait_for_output(void)
{
	int r;
	do {
		r = wait_for_data(ftp->data, false);
		if(r == -1)
			return -1;
		if(r == 0 && foo_hookf)
			foo_hookf(&ftp->ti);
	} while(r == 0);

	return 0;
}
Esempio n. 7
0
void PubSubClient::stop()
{
	if ((!available() && !connected()) || !json_enabled) {
		PubNub_BASE_CLIENT::stop();
		return;
	}
	/* We are still connected. Read the rest of the stream so that
	 * we catch the timetoken. */
	while (wait_for_data()) {
		char ch = read();
		this->_state_input(ch, NULL, 0);
	}
	json_enabled = false;
}
Esempio n. 8
0
static int wait_for_input(void)
{
	int r;
	do {
		r = wait_for_data(ftp->data, true);
		if(r == -1) {
			if(errno == EINTR)
				ftp->ti.interrupted = true;
			return -1;
		}
		if(r == 0 && foo_hookf)
			foo_hookf(&ftp->ti);
	} while(r == 0);

	return 0;
}
Esempio n. 9
0
static int
handshake (struct stream_data *data)
{
	int ret;
	int finished;

	SSL_library_init();
	SSL_load_error_strings();
	
	data->ssl_ctx = SSL_CTX_new(TLSv1_method());
	if(!data->ssl_ctx) return IKS_NOMEM;
	
	data->ssl = SSL_new(data->ssl_ctx);
	if(!data->ssl) return IKS_NOMEM;
	
	if( SSL_set_fd(data->ssl, (int)(intptr_t)data->sock) != 1 ) return IKS_NOMEM;
	
	/* Set both the read and write BIO's to non-blocking mode */
	BIO_set_nbio(SSL_get_rbio(data->ssl), 1);
	BIO_set_nbio(SSL_get_wbio(data->ssl), 1);

	finished = 0;
	
	do
	{
		ret = SSL_connect(data->ssl);
		
		if( ret != 1 ) 
		{
			if( wait_for_data(data, ret, 1) != IKS_OK ) 
			{
				finished = 1; 
				SSL_free(data->ssl);
			}
		}
	} while( ret != 1 && finished != 1 );
	
	if( ret == 1 )
	{
		data->flags &= (~SF_TRY_SECURE);
		data->flags |= SF_SECURE;
	
		iks_send_header (data->prs, data->server);
	}
	
	return ret == 1 ? IKS_OK : IKS_NET_TLSFAIL;
}
Esempio n. 10
0
static SSL *
open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS)
{
  SSL_CTX *ssl_ctx = NULL;
  SSL *ssl = NULL;
  int n, finished = 0;
  BIO *sbio;

  ssl_ctx = SSL_CTX_new (SSLv23_client_method ());
  SSL_CTX_set_default_verify_paths (ssl_ctx);
  SSL_CTX_set_verify (ssl_ctx, SSL_VERIFY_NONE, &ssl_verify);
  ssl = SSL_new (ssl_ctx);

  /* TODO: finetune this list, take into account anonTLS bool */
  SSL_set_cipher_list(ssl, "ALL");

  SSL_set_fd (ssl, sockfd);
  SSL_CTX_set_app_data (ssl_ctx, client);

  do
  {
    n = SSL_connect(ssl);
		
    if (n != 1) 
    {
      if (wait_for_data(ssl, n, 1) != 1) 
      {
        finished = 1; 
        if (ssl->ctx)
          SSL_CTX_free (ssl->ctx);
        SSL_free(ssl);
        SSL_shutdown (ssl);

        return NULL;
      }
    }
  } while( n != 1 && finished != 1 );

  return ssl;
}
Esempio n. 11
0
 mailbox_element* pop() {
     wait_for_data();
     return try_pop();
 }
Esempio n. 12
0
 T* pop() {
     wait_for_data();
     T* result = m_head;
     m_head = m_head->next;
     return result;
 }
Esempio n. 13
0
 std::unique_ptr<node> wait_pop_head()
 {
     std::unique_lock<std::mutex> head_lock(wait_for_data());
     return pop_head();
 }
Esempio n. 14
0
/* Fork a new child with a pty. */
gboolean pty_child_fork(struct child* c, gint new_stdin_fd,
		gint new_stdout_fd, gint new_stderr_fd) {

	gint pty_slave_fd = -1;
	gint pty_master_fd = -1;
	const gchar* pty_slave_name = NULL;

	c->args.argv[0] = c->exec_name;

	/* Delimit the args with NULL. */
	args_add(&(c->args), NULL);

	/* Setup a pty for the new shell. */
	/* Get master (pty) */
	if ((pty_master_fd = rxvt_get_pty(&pty_slave_fd, &pty_slave_name)) < 0) {
		g_critical("Could not open master side of pty");
		c->pid = -1;
		c->fd_in = -1;
		c->fd_out = -1;
		return FALSE;
	}

	/* Turn on non-blocking -- probably not necessary since we're in raw
	   terminal mode. */
	fcntl(pty_master_fd, F_SETFL, O_NDELAY);

	/* This will be the interface with the new shell. */
	c->fd_in = pty_master_fd;
	c->fd_out = pty_master_fd;

	switch (c->pid = fork()) {
		case -1:
			g_critical("Could not fork process: %s", g_strerror(errno));
			return FALSE;
			/*break;*/

		case 0:
			if (setsid() == -1) {
				g_critical("pty_child_fork(): setsid(): %s",
						g_strerror(errno));
				goto child_fail;
			}

			/* Get slave (tty) */
			if (pty_slave_fd < 0) {
				if ((pty_slave_fd = rxvt_get_tty(pty_slave_name)) < 0) {
					(void) close(pty_master_fd);
					g_critical("Could not open slave tty \"%s\"",
							pty_slave_name);
					goto child_fail;
				}
			}
			if (rxvt_control_tty(pty_slave_fd, pty_slave_name) < 0) {
				g_critical("Could not obtain control of tty \"%s\"",
						pty_slave_name);
				goto child_fail;
			}

			/* A parameter of NEW_PTY_FD means to use the slave side of the
			   new pty.  A parameter of CLOSE_FD means to just close that fd
			   right out. */
			if (new_stdin_fd == NEW_PTY_FD)
				new_stdin_fd = pty_slave_fd;
			if (new_stdout_fd == NEW_PTY_FD)
				new_stdout_fd = pty_slave_fd;
			if (new_stderr_fd == NEW_PTY_FD)
				new_stderr_fd = pty_slave_fd;

			if (new_stdin_fd == CLOSE_FD)
				(void)close(STDIN_FILENO);
			else if (dup2(new_stdin_fd, STDIN_FILENO) == -1) {
				g_critical("Could not replace stdin in child process: %s",
						g_strerror(errno));
				goto child_fail;
			}

			if (new_stdout_fd == CLOSE_FD)
				(void)close(STDOUT_FILENO);
			else if (dup2(new_stdout_fd, STDOUT_FILENO) == -1) {
				g_critical("Could not replace stdout in child process: %s",
						g_strerror(errno));
				goto child_fail;
			}

			if (new_stderr_fd == CLOSE_FD)
				(void)close(STDERR_FILENO);
			else if (dup2(new_stderr_fd, STDERR_FILENO) == -1) {
				g_critical("Could not replace stderr in child process: %s",
						g_strerror(errno));
				goto child_fail;
			}

			(void)close(pty_slave_fd);
			execvp(c->exec_name, c->args.argv);

			child_fail:
			g_critical("Exec failed: %s", g_strerror(errno));
			g_critical("If vgseer does not exit, you should do so manually");
			_exit(EXIT_FAILURE);
			break;
	}

	if (!wait_for_data(c->fd_out)) {
		g_critical("Did not receive go-ahead from child shell");
		return FALSE;
	}

	return TRUE;
}
Esempio n. 15
0
File: nwio.c Progetto: DeadZen/qse
int qse_nwio_init (
	qse_nwio_t* nwio, qse_mmgr_t* mmgr, const qse_nwad_t* nwad, 
	int flags, const qse_nwio_tmout_t* tmout)
{
	qse_skad_t addr;
	qse_sck_len_t addrlen;
	int family, type, tmp;

	QSE_MEMSET (nwio, 0, QSE_SIZEOF(*nwio));
	nwio->mmgr = mmgr;
	nwio->flags = flags;
	nwio->errnum = QSE_NWIO_ENOERR;
	if (tmout) nwio->tmout = *tmout;
	else
	{
		nwio->tmout.r.sec = -1;
		nwio->tmout.w.sec = -1;
		nwio->tmout.c.sec = -1;
		nwio->tmout.a.sec = -1;
	}

	tmp = qse_nwadtoskad (nwad, &addr);
	if (tmp <= -1) 
	{
		nwio->errnum = QSE_NWIO_EINVAL;
		return -1;
	}
	addrlen = tmp;

#if defined(SOCK_STREAM) && defined(SOCK_DGRAM)
	if (flags & QSE_NWIO_TCP) type = SOCK_STREAM;
	else if (flags & QSE_NWIO_UDP) type = SOCK_DGRAM;
	else
#endif
	{
		nwio->errnum = QSE_NWIO_EINVAL;
		return -1;
	}

	family = qse_skadfamily (&addr);

#if defined(_WIN32)
	nwio->handle = socket (family, type, 0);
	if (nwio->handle == INVALID_SOCKET)
	{
		nwio->errnum = skerr_to_errnum (WSAGetLastError());
		goto oops;
	}

	if ((flags & QSE_NWIO_TCP) && (flags & QSE_NWIO_KEEPALIVE))
	{
		int optval = 1;
		setsockopt (nwio->handle, SOL_SOCKET, SO_KEEPALIVE, (void*)&optval, QSE_SIZEOF(optval));
	}

	if (flags & QSE_NWIO_PASSIVE)
	{
		qse_nwio_hnd_t handle;

		if (flags & QSE_NWIO_REUSEADDR)
		{
			int optval = 1;
			setsockopt (nwio->handle, SOL_SOCKET, SO_REUSEADDR, (void*)&optval, QSE_SIZEOF(optval));
		}

		if (bind (nwio->handle, (struct sockaddr*)&addr, addrlen) == SOCKET_ERROR)
		{
			nwio->errnum = skerr_to_errnum (WSAGetLastError());
			goto oops;
		}

		if (flags & QSE_NWIO_TCP)
		{
			if (listen (nwio->handle, 10) == SOCKET_ERROR)
			{
				nwio->errnum = skerr_to_errnum (WSAGetLastError());
				goto oops;
			}

			if (TMOUT_ENABLED(nwio->tmout.a) &&
			    wait_for_data (nwio, &nwio->tmout.a, 0) <= -1) goto oops;

			handle = accept (nwio->handle, (struct sockaddr*)&addr, &addrlen);
			if (handle == INVALID_SOCKET)
			{
				nwio->errnum = skerr_to_errnum (WSAGetLastError());
				goto oops;
			}

			closesocket (nwio->handle);
			nwio->handle = handle;
		}
		else if (flags & QSE_NWIO_UDP)
		{
			nwio->status |= STATUS_UDP_CONNECT;
		}
	}
	else
	{
		int xret;

		if (TMOUT_ENABLED(nwio->tmout.c) && (flags & QSE_NWIO_TCP))
		{
			unsigned long cmd = 1;

			if (ioctlsocket(nwio->handle, FIONBIO, &cmd) == SOCKET_ERROR) 
			{
				nwio->errnum = skerr_to_errnum (WSAGetLastError());
				goto oops;
			}
		}

		xret = connect (nwio->handle, (struct sockaddr*)&addr, addrlen);

		if (TMOUT_ENABLED(nwio->tmout.c) && (flags & QSE_NWIO_TCP))
		{
			unsigned long cmd = 0;
			
			if ((xret == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) ||
			    ioctlsocket (nwio->handle, FIONBIO, &cmd) == SOCKET_ERROR)
			{
				nwio->errnum = skerr_to_errnum (WSAGetLastError());
				goto oops;
			}

			if (wait_for_data (nwio, &nwio->tmout.c, 1) <= -1) goto oops;
			else 
			{
				int xlen;
				DWORD xerr;

				xlen = QSE_SIZEOF(xerr);
				if (getsockopt (nwio->handle, SOL_SOCKET, SO_ERROR, (char*)&xerr, &xlen) == SOCKET_ERROR)
				{
					nwio->errnum = skerr_to_errnum (WSAGetLastError());
					goto oops;
				}
				else if (xerr != 0)
				{
					nwio->errnum = skerr_to_errnum (xerr);
					goto oops;
				}
			}
		}
		else
		{
			if (xret == SOCKET_ERROR)
			{
				nwio->errnum = skerr_to_errnum (WSAGetLastError());
				goto oops;
			}
		}
	}

#elif defined(__OS2__)
	nwio->handle = socket (family, type, 0);
	if (nwio->handle <= -1)
	{
		nwio->errnum = skerr_to_errnum (sock_errno());
		goto oops;
	}

	if ((flags & QSE_NWIO_TCP) && (flags & QSE_NWIO_KEEPALIVE))
	{
		int optval = 1;
		setsockopt (nwio->handle, SOL_SOCKET, SO_KEEPALIVE, (void*)&optval, QSE_SIZEOF(optval));
	}

	if (flags & QSE_NWIO_PASSIVE)
	{
		qse_nwio_hnd_t handle;

		if (flags & QSE_NWIO_REUSEADDR)
		{
			int optval = 1;
			setsockopt (nwio->handle, SOL_SOCKET, SO_REUSEADDR, (void*)&optval, QSE_SIZEOF(optval));
		}

		if (bind (nwio->handle, (struct sockaddr*)&addr, addrlen) <= -1)
		{
			nwio->errnum = skerr_to_errnum (sock_errno());
			goto oops;
		}

		if (flags & QSE_NWIO_TCP)
		{
			if (listen (nwio->handle, 10) <= -1)
			{
				nwio->errnum = skerr_to_errnum (sock_errno());
				goto oops;
			}

			if (TMOUT_ENABLED(nwio->tmout.a) &&
			    wait_for_data (nwio, &nwio->tmout.a, 0) <= -1) goto oops;

			handle = accept (nwio->handle, (struct sockaddr*)&addr, &addrlen);
			if (handle <= -1)
			{
				nwio->errnum = skerr_to_errnum (sock_errno());
				goto oops;
			}

			soclose (nwio->handle);
			nwio->handle = handle;
		}
		else if (flags & QSE_NWIO_UDP)
		{
			nwio->status |= STATUS_UDP_CONNECT;
		}
	}
	else
	{
		int xret;

		if (TMOUT_ENABLED(nwio->tmout.c) && (flags & QSE_NWIO_TCP))
		{
			int noblk = 1;

			if (ioctl (nwio->handle, FIONBIO, (void*)&noblk, QSE_SIZEOF(noblk)) <= -1)
			{
				nwio->errnum = skerr_to_errnum (sock_errno());
				goto oops;
			}
		}

		xret = connect (nwio->handle, (struct sockaddr*)&addr, addrlen);

		if (TMOUT_ENABLED(nwio->tmout.c) && (flags & QSE_NWIO_TCP))
		{
			int noblk = 0;
			
			if ((xret <= -1 && sock_errno() != SOCEINPROGRESS) ||
			    ioctl (nwio->handle, FIONBIO, (void*)&noblk, QSE_SIZEOF(noblk)) <= -1)
			{
				nwio->errnum = skerr_to_errnum (sock_errno());
				goto oops;
			}

			if (wait_for_data (nwio, &nwio->tmout.c, 1) <= -1) goto oops;
			else 
			{
				int xlen, xerr;

				xlen = QSE_SIZEOF(xerr);
				if (getsockopt (nwio->handle, SOL_SOCKET, SO_ERROR, (char*)&xerr, &xlen) <= -1)
				{
					nwio->errnum = skerr_to_errnum (sock_errno());
					goto oops;
				}
				else if (xerr != 0)
				{
					nwio->errnum = skerr_to_errnum (xerr);
					goto oops;
				}
			}
		}
		else
		{
			if (xret <= -1)
			{
				nwio->errnum = skerr_to_errnum (sock_errno());
				goto oops;
			}
		}
	}

#elif defined(__DOS__)

	nwio->handle = socket (family, type, 0);
	if (nwio->handle <= -1)
	{
		nwio->errnum = skerr_to_errnum (errno);
		goto oops;
	}

	if ((flags & QSE_NWIO_TCP) && (flags & QSE_NWIO_KEEPALIVE))
	{
		int optval = 1;
		setsockopt (nwio->handle, SOL_SOCKET, SO_KEEPALIVE, (void*)&optval, QSE_SIZEOF(optval));
	}

	if (flags & QSE_NWIO_PASSIVE)
	{
		qse_nwio_hnd_t handle;

	#if defined(SO_REUSEADDR)
		if (flags & QSE_NWIO_REUSEADDR)
		{
			int optval = 1;
			setsockopt (nwio->handle, SOL_SOCKET, SO_REUSEADDR, (void*)&optval, QSE_SIZEOF(optval));
		}
	#endif

		if (bind (nwio->handle, (struct sockaddr*)&addr, addrlen) <= -1)
		{
			nwio->errnum = skerr_to_errnum (errno);
			goto oops;
		}

		if (flags & QSE_NWIO_TCP)
		{
			if (listen (nwio->handle, 10) <= -1)
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}

			if (TMOUT_ENABLED(nwio->tmout.a) &&
			    wait_for_data (nwio, &nwio->tmout.a, 0) <= -1) goto oops;

			handle = accept (nwio->handle, (struct sockaddr*)&addr, &addrlen);
			if (handle <= -1)
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}

			close_s (nwio->handle);
			nwio->handle = handle;
		}
		else if (flags & QSE_NWIO_UDP)
		{
			nwio->status |= STATUS_UDP_CONNECT;
		}
	}
	else
	{
		int xret;

		if (TMOUT_ENABLED(nwio->tmout.c) && (flags & QSE_NWIO_TCP))
		{
			int cmd = 1;

			if (ioctlsocket(nwio->handle, FIONBIO, (char*)&cmd) == SOCKET_ERROR) 
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}
		}

		xret = connect (nwio->handle, (struct sockaddr*)&addr, addrlen);

		if (TMOUT_ENABLED(nwio->tmout.c) && (flags & QSE_NWIO_TCP))
		{
			int cmd = 0;

			if ((xret == SOCKET_ERROR && errno != EWOULDBLOCK) ||
			    ioctlsocket (nwio->handle, FIONBIO, (char*)&cmd) == SOCKET_ERROR)
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}

			if (wait_for_data (nwio, &nwio->tmout.c, 1) <= -1) goto oops;
			else 
			{
				int xlen, xerr;

				xlen = QSE_SIZEOF(xerr);
				if (getsockopt (nwio->handle, SOL_SOCKET, SO_ERROR, (char*)&xerr, &xlen) <= -1)
				{
					nwio->errnum = skerr_to_errnum (errno);
					goto oops;
				}
				else if (xerr != 0)
				{
					nwio->errnum = skerr_to_errnum (xerr);
					goto oops;
				}
			}
		}
		else
		{
			if (xret <= -1)
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}
		}
	}

#elif defined(USE_TLI)

	{

		static const qse_mchar_t* dev_path[2][2] = 
		{
			{ "/dev/tcp", "/dev/inet/tcp" },
			{ "/dev/udp", "/dev/inet/tcp" }
		};
		int dev_id;

		if (flags & QSE_NWIO_TCP) dev_id = 0;
		else 
		{
			QSE_ASSERT (flags & QSE_NWIO_UDP);
			dev_id = 1;
		}

		nwio->handle = t_open (dev_path[dev_id][0], O_RDWR, QSE_NULL);
		if (nwio->handle <= -1)
		{
			nwio->handle = t_open (dev_path[dev_id][1], O_RDWR, QSE_NULL);
			if (nwio->handle <= -1)
			{
				nwio->errnum = tlierr_to_errnum (t_errno, errno);
				goto oops;
			}
		}

		if (flags & QSE_NWIO_PASSIVE)
		{
			/* TODO: */
			nwio->errnum = QSE_NWIO_ENOIMPL;
			goto oops;
		}
		else
		{
			struct t_call call; /* for connecting */
			struct t_bind req, ret; /* for binding */
			qse_skad_t reqaddr, retaddr;
			qse_nwad_t reqnwad;

			/*
			call = t_alloc (nwio->handle, T_CALL, T_ADDR);
			if (!call)
			{
				nwio->errnum = tlierr_to_errnum (t_errno, errno);
				goto oops;
			}*/

			qse_clearnwad (&reqnwad, nwad->type);
			qse_nwadtoskad (&reqnwad, &reqaddr);

			QSE_MEMSET (&ret, 0, QSE_SIZEOF(req));
			req.addr.maxlen = addrlen;
			req.addr.len = addrlen;
			req.addr.buf = &reqaddr;

			QSE_MEMSET (&ret, 0, QSE_SIZEOF(ret));
			ret.addr.maxlen = addrlen;
			ret.addr.len = addrlen;
			ret.addr.buf = &retaddr;

			if (t_bind (nwio->handle, &req, &ret) <= -1)
			{
				nwio->errnum = tlierr_to_errnum (t_errno, errno);
				goto oops;
			}

/* TODO: should i use t_alloc() and t_free for call, ret, req? */
			QSE_MEMSET (&call, 0, QSE_SIZEOF(call));
			call.addr.maxlen = addrlen;
			call.addr.len = addrlen;
			call.addr.buf = &addr;

			if (TMOUT_ENABLED(nwio->tmout.c) && (flags & QSE_NWIO_TCP))
			{
				int orgfl;

				orgfl = fcntl (nwio->handle, F_GETFL, 0);
				if (orgfl <= -1 || fcntl (nwio->handle, F_SETFL, orgfl | O_NONBLOCK) <= -1)
				{
					nwio->errnum = skerr_to_errnum (errno);
					goto oops;
				}

				if (t_connect (nwio->handle, &call, 0) <= -1)
				{
					if (t_errno != TNODATA)
					{
						nwio->errnum = tlierr_to_errnum (t_errno, errno);
						goto oops;
					}

			/* TODO: this doesn't seem to work wel... REDO THE WORK */
					if (wait_for_data (nwio, &nwio->tmout.c, 0) <= -1) goto oops;

					if (t_rcvconnect (nwio->handle, QSE_NULL) <= -1)
					{
						nwio->errnum = tlierr_to_errnum (t_errno, errno);
						goto oops;
					}
				}

				if (fcntl (nwio->handle, F_SETFL, orgfl) <= -1) 
				{
					nwio->errnum = skerr_to_errnum (errno);
					goto oops;
				}
			}
			else
			{
				if (t_connect (nwio->handle, &call, 0) <= -1)
				{
					nwio->errnum = tlierr_to_errnum (t_errno, errno);
					goto oops;
				}
			}
		}
	}

#else
	#if defined(SOCK_CLOEXEC)
	nwio->handle = socket (family, type | SOCK_CLOEXEC, 0);
	#else
	nwio->handle = socket (family, type, 0);
	#endif
	if (nwio->handle <= -1)
	{
		nwio->errnum = skerr_to_errnum (errno);
		goto oops;
	}

	#if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
	{ 
		int tmp = fcntl (nwio->handle, F_GETFD);
		if (tmp >= 0) fcntl (nwio->handle, F_SETFD, tmp | FD_CLOEXEC);
	}
	#endif

	if ((flags & QSE_NWIO_TCP) && (flags & QSE_NWIO_KEEPALIVE))
	{
		int optval = 1;
		setsockopt (nwio->handle, SOL_SOCKET, SO_KEEPALIVE, (void*)&optval, QSE_SIZEOF(optval));
	}

	if (flags & QSE_NWIO_PASSIVE)
	{
		qse_nwio_hnd_t handle;

	#if defined(SO_REUSEADDR)
		if (flags & QSE_NWIO_REUSEADDR)
		{
			int optval = 1;
			setsockopt (nwio->handle, SOL_SOCKET, SO_REUSEADDR, (void*)&optval, QSE_SIZEOF(optval));
		}
	#endif

		if (bind (nwio->handle, (struct sockaddr*)&addr, addrlen) <= -1)
		{
			nwio->errnum = skerr_to_errnum (errno);
			goto oops;
		}

		if (flags & QSE_NWIO_TCP)
		{
			if (listen (nwio->handle, 10) <= -1)
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}

			if (TMOUT_ENABLED(nwio->tmout.a) &&
			    wait_for_data (nwio, &nwio->tmout.a, 0) <= -1) goto oops;

			handle = accept (nwio->handle, (struct sockaddr*)&addr, &addrlen);
			if (handle <= -1)
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}

			qse_closesckhnd (nwio->handle); /* close the listening socket */
			nwio->handle = handle; /* set the handle to the accepted socket */
		}
		else if (flags & QSE_NWIO_UDP)
		{
			nwio->status |= STATUS_UDP_CONNECT;
		}
	}
	else
	{
		int xret;

		if (TMOUT_ENABLED(nwio->tmout.c) && (flags & QSE_NWIO_TCP))
		{
			int orgfl;

			orgfl = fcntl (nwio->handle, F_GETFL, 0);
			if (orgfl <= -1 || fcntl (nwio->handle, F_SETFL, orgfl | O_NONBLOCK) <= -1)
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}
		
			xret = connect (nwio->handle, (struct sockaddr*)&addr, addrlen);
		
			if ((xret <= -1 && errno != EINPROGRESS) ||
			    fcntl (nwio->handle, F_SETFL, orgfl) <= -1) 
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}

			if (wait_for_data (nwio, &nwio->tmout.c, 1) <= -1) goto oops;
			else 
			{
				qse_sck_len_t xlen;
				xlen = QSE_SIZEOF(xret);
				if (getsockopt (nwio->handle, SOL_SOCKET, SO_ERROR, (char*)&xret, &xlen) <= -1)
				{
					nwio->errnum = skerr_to_errnum (errno);
					goto oops;
				}
				else if (xret != 0)
				{
					nwio->errnum = skerr_to_errnum (xret);
					goto oops;
				}
			}
		}
		else
		{
			xret = connect (nwio->handle, (struct sockaddr*)&addr, addrlen);
			if (xret <= -1)
			{
				nwio->errnum = skerr_to_errnum (errno);
				goto oops;
			}
		}
	}
#endif

	if (flags & QSE_NWIO_TEXT)
	{
		int topt = 0;

		if (flags & QSE_NWIO_IGNOREMBWCERR) topt |= QSE_TIO_IGNOREMBWCERR;
		if (flags & QSE_NWIO_NOAUTOFLUSH) topt |= QSE_TIO_NOAUTOFLUSH;

		nwio->tio = qse_tio_open (mmgr, QSE_SIZEOF(qse_nwio_t*), topt);
		if (nwio->tio == QSE_NULL)
		{
			nwio->errnum = QSE_NWIO_ENOMEM;
			goto oops;
		}

		/* store the back-reference to nwio in the extension area.*/
		*(qse_nwio_t**)QSE_XTN(nwio->tio) = nwio;

		if (qse_tio_attachin (nwio->tio, socket_input, QSE_NULL, 4096) <= -1 ||
		    qse_tio_attachout (nwio->tio, socket_output, QSE_NULL, 4096) <= -1)
		{
			if (nwio->errnum == QSE_NWIO_ENOERR) 
				nwio->errnum = tio_errnum_to_nwio_errnum (nwio->tio);
			goto oops;
		}
	}
Esempio n. 16
0
int ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{

  int test_failed = 0;

  u_long mask =  ACE_LOG_MSG->priority_mask(ACE_Log_Msg::PROCESS) ;
  ACE_LOG_MSG->priority_mask(mask | LM_TRACE | LM_DEBUG, ACE_Log_Msg::PROCESS) ;

  ACE_DEBUG((LM_DEBUG,"(%P|%t) FooTest5_0 main\n"));
  try
    {
      ::DDS::DomainParticipantFactory_var dpf = TheParticipantFactoryWithArgs(argc, argv);
      if (CORBA::is_nil (dpf.in ()))
      {
        ACE_ERROR ((LM_ERROR,
                   ACE_TEXT("(%P|%t) creating the DomainParticipantFactory failed.\n")));
        return 1 ;
      }

      // let the Service_Participant (in above line) strip out -DCPSxxx parameters
      // and then get application specific parameters.
      parse_args (argc, argv);

      ::Xyz::FooTypeSupport_var fts (new ::Xyz::FooTypeSupportImpl);

      ::DDS::DomainParticipant_var dp =
        dpf->create_participant(MY_DOMAIN,
                                PARTICIPANT_QOS_DEFAULT,
                                ::DDS::DomainParticipantListener::_nil(),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (dp.in ()))
      {
        ACE_ERROR ((LM_ERROR,
                   ACE_TEXT("(%P|%t) create_participant failed.\n")));
        return 1 ;
      }

      if (::DDS::RETCODE_OK != fts->register_type(dp.in (), MY_TYPE))
        {
          ACE_ERROR ((LM_ERROR,
            ACE_TEXT ("Failed to register the FooTypeSupport.")));
          return 1;
        }


      ::DDS::TopicQos topic_qos;
      dp->get_default_topic_qos(topic_qos);

      topic_qos.resource_limits.max_samples_per_instance =
            max_samples_per_instance ;

      topic_qos.history.depth = history_depth;

      ::DDS::Topic_var topic =
        dp->create_topic (MY_TOPIC,
                          MY_TYPE,
                          topic_qos,
                          ::DDS::TopicListener::_nil(),
                          ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (topic.in ()))
      {
        return 1 ;
      }

      ::DDS::TopicDescription_var description =
        dp->lookup_topicdescription(MY_TOPIC);
      if (CORBA::is_nil (description.in ()))
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT("(%P|%t) lookup_topicdescription failed.\n")),
                           1);
      }



      // Create the subscriber
      ::DDS::Subscriber_var sub =
        dp->create_subscriber(SUBSCRIBER_QOS_DEFAULT,
                             ::DDS::SubscriberListener::_nil(),
                             ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (sub.in ()))
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT("(%P|%t) create_subscriber failed.\n")),
                           1);
      }

      // Create the publisher
      ::DDS::Publisher_var pub =
        dp->create_publisher(PUBLISHER_QOS_DEFAULT,
                             ::DDS::PublisherListener::_nil(),
                             ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (pub.in ()))
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                          ACE_TEXT("(%P|%t) create_publisher failed.\n")),
                          1);
      }

      // Initialize the transport
      if (0 != ::init_tranport() )
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT("(%P|%t) init_transport failed!\n")),
                           1);
      }

      // Attach the subscriber to the transport.
      OpenDDS::DCPS::SubscriberImpl* sub_impl
        = dynamic_cast<OpenDDS::DCPS::SubscriberImpl*> (sub.in ());

      if (0 == sub_impl)
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                          ACE_TEXT("(%P|%t) Failed to obtain servant ::OpenDDS::DCPS::SubscriberImpl\n")),
                          1);
      }

      sub_impl->attach_transport(reader_transport_impl.in());


      // Attach the publisher to the transport.
      OpenDDS::DCPS::PublisherImpl* pub_impl
        = dynamic_cast<OpenDDS::DCPS::PublisherImpl*> (pub.in ());

      if (0 == pub_impl)
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                          ACE_TEXT("(%P|%t) Failed to obtain servant ::OpenDDS::DCPS::PublisherImpl\n")),
                          1);
      }

      pub_impl->attach_transport(writer_transport_impl.in());

      // Create the datawriter
      ::DDS::DataWriterQos dw_qos;
      pub->get_default_datawriter_qos (dw_qos);

      dw_qos.history.depth = history_depth  ;
      dw_qos.resource_limits.max_samples_per_instance =
            max_samples_per_instance ;

      ::DDS::DataWriter_var dw = pub->create_datawriter(topic.in (),
                                        dw_qos,
                                        ::DDS::DataWriterListener::_nil(),
                                        ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil (dw.in ()))
      {
        ACE_ERROR ((LM_ERROR,
          ACE_TEXT("(%P|%t) create_datawriter failed.\n")));
        return 1 ;
      }

      // Create the Datareader
      ::DDS::DataReaderQos dr_qos;
      sub->get_default_datareader_qos (dr_qos);

      dr_qos.history.depth = history_depth  ;
      dr_qos.resource_limits.max_samples_per_instance =
            max_samples_per_instance ;

      ::DDS::DataReader_var dr
        = sub->create_datareader(description.in (),
                                 dr_qos,
                                 ::DDS::DataReaderListener::_nil(),
                                 ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil (dr.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
            ACE_TEXT("(%P|%t) create_datareader failed.\n")),
            1);
        }

      ::Xyz::FooDataWriter_var foo_dw
           = ::Xyz::FooDataWriter::_narrow(dw.in ());
      if (CORBA::is_nil (foo_dw.in ()))
      {
        ACE_ERROR ((LM_ERROR,
          ACE_TEXT("(%P|%t) ::Xyz::FooDataWriter::_narrow failed.\n")));
        return 1; // failure
      }

      ::Xyz::FooDataWriterImpl* fast_dw
        = dynamic_cast<Xyz::FooDataWriterImpl*>(foo_dw.in());

      ::Xyz::FooDataReader_var foo_dr
        = ::Xyz::FooDataReader::_narrow(dr.in ());
      if (CORBA::is_nil (foo_dr.in ()))
      {
        ACE_ERROR ((LM_ERROR,
          ACE_TEXT("(%P|%t) ::Xyz::FooDataReader::_narrow failed.\n")));
        return 1; // failure
      }

      ::Xyz::FooDataReaderImpl* fast_dr
        = dynamic_cast<Xyz::FooDataReaderImpl*>(foo_dr.in());


      // wait for association establishement before writing.
      ACE_OS::sleep(5); //REMOVE if not needed


      // =============== do the test ====


      ::DDS::OfferedIncompatibleQosStatus incomp;
      if (foo_dw->get_offered_incompatible_qos_status (incomp) != ::DDS::RETCODE_OK)
      {
        ACE_ERROR_RETURN((LM_ERROR,
          ACE_TEXT ("ERROR: failed to get offered incompatible qos status\n")),
          1);
      }

      int incompatible_transport_found = 0;
      for (CORBA::ULong ii =0; ii < incomp.policies.length (); ii++)
        {
          if (incomp.policies[ii].policy_id
                        == ::OpenDDS::TRANSPORTTYPE_QOS_POLICY_ID)
            incompatible_transport_found = 1;
        }

      ::DDS::SubscriptionMatchedStatus matched;

      if (foo_dr->get_subscription_matched_status (matched) != ::DDS::RETCODE_OK)
      {
        ACE_ERROR_RETURN((LM_ERROR,
          ACE_TEXT ("ERROR: failed to get subscription matched status\n")),
          1);
      }

      ::DDS::InstanceHandle_t handle;

      if (pub_using_udp != sub_using_udp)
        {
          if (!incompatible_transport_found)
            ACE_ERROR_RETURN((LM_ERROR,
              "TEST ERROR: Expected offered_incompatible_qos"
              " with TRANSPORTTYPE_QOS_POLICY_ID"
              " but did not get it. %d incompatible_qos values.\n",
              incomp.policies.length ()),
              7);
          else
            {
              ACE_DEBUG((LM_DEBUG, "Got expected offered_incompatible_qos"
                " with TRANSPORTTYPE_QOS_POLICY_ID"
                " existing with success.\n"));
              goto cleanup;
            }
        }
      else
        {
          if (incompatible_transport_found)
            ACE_ERROR_RETURN((LM_ERROR,
              "TEST ERROR: Did not expect offered_incompatible_qos"
              " with TRANSPORTTYPE_QOS_POLICY_ID"
              " but got it. %d incompatible_qos values.\n",
              incomp.policies.length ()),
              8);

          if (matched.total_count != 1)
            ACE_ERROR_RETURN((LM_ERROR,
              "TEST ERROR: expected subscription_match"
              " with count 1 but got %d\n",
              matched.total_count),
              9);
        }

      ::Xyz::Foo foo;
      foo.key = 10101;
      foo.x = -1;
      foo.y = -1;

      handle
          = fast_dw->register_instance(foo);

      foo.x = 7;

      fast_dw->write(foo,
                     handle);

      ::Xyz::Foo sample;
      ::DDS::SampleInfo info ;

      // wait for new data for upto 10 seconds
      if (!wait_for_data(sub.in (), 5))
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT("(%P|%t) ERROR: timeout waiting for data.\n")),
                           1);

      DDS::ReturnCode_t status  ;
      status = fast_dr->read_next_sample(sample, info) ;

      if (status == ::DDS::RETCODE_OK)
      {
        ACE_DEBUG((LM_DEBUG,
            "read foo.x = %f foo.y = %f, foo.key = %d\n",
            sample.x, sample.y, sample.key));

        ACE_DEBUG((LM_DEBUG,
            "read SampleInfo.sample_rank = %d\n",
            info.sample_rank));
        if (foo.x != sample.x)
          {
            ACE_ERROR((LM_ERROR,
              "ERROR: unexpected foo value wrote %f got %f\n",
              foo.x, sample.x));
            test_failed = 1;
          }
      }
      else if (status == ::DDS::RETCODE_NO_DATA)
      {
        ACE_ERROR ((LM_ERROR,
          ACE_TEXT("(%P|%t) ERROR: reader received ::DDS::RETCODE_NO_DATA!\n")
                    ));
        test_failed = 1;
      }
      else
      {
        ACE_ERROR((LM_ERROR,
            ACE_TEXT("(%P|%t) ERROR: unexpected status %d!\n"),
            status ));
        test_failed = 1;
      }



      //======== clean up ============

cleanup:
      // Clean up publisher objects
//      pub->delete_contained_entities() ;

      pub->delete_datawriter(dw.in ());
      dp->delete_publisher(pub.in ());


      //clean up subscriber objects
//      sub->delete_contained_entities() ;

      sub->delete_datareader(dr.in ());
      dp->delete_subscriber(sub.in ());

      // clean up common objects
      dp->delete_topic(topic.in ());
      dpf->delete_participant(dp.in ());

      reader_transport_impl = 0;
      writer_transport_impl = 0;

      TheTransportFactory->release();
      TheServiceParticipant->shutdown ();

    }
  catch (const TestException&)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT("(%P|%t) TestException caught in main.cpp. ")));
      return 1;
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught in main.cpp:");
      return 1;
    }

  return test_failed;
}
Esempio n. 17
0
void Client::handle_read(const boost::system::error_code& error)
{
    if (!error)
    {
        switch (m_downMessage.m_type)
        {
        case DownMessage::PLAYER_CONNECTED :
        case DownMessage::PLAYER_LEFT :

            std::cout << "Room event : " << m_downMessage.m_info << std::endl;
            break;

        case DownMessage::WORLD_STATE :

            if (StateController::PLAYING == m_state)
            {
                std::cout << "World state" << std::endl;
                for (std::vector<Player>::iterator it = m_downMessage.m_players.begin(); m_downMessage.m_players.end() != it; it++)
                {
                    std::cout << it->m_area << it->m_tile.x << it->m_tile.y << it->m_zone.x << it->m_zone.y << std::endl;

                    if (it->m_number == m_player->m_number)
                    {
                        m_player->m_area = it->m_area;
                        m_player->m_tile = it->m_tile;
                        m_player->m_zone = it->m_zone;
                    }
                }
                SDL_FillRect(m_screen, 0, SDL_MapRGB(m_screen->format, 0, 0, 0));
                m_zoneDisplayZone->render(m_screen, m_world->getArea(m_player->m_area), m_downMessage.m_players);
                SDL_Flip(m_screen);
            }
            break;

        case DownMessage::DEFAULT_TYPE :

            std::cout << "Default message" << std::endl;
            break;

        case DownMessage::WELCOME :

            if (StateController::INITIALIZING == m_state)
            {
                m_world = new StaticWorld("scenario1", "data");
                m_player = new Player(m_downMessage.m_players.front());
                m_state = StateController::PLAYING;
                std::cout << "Welcome message" << std::endl;
            }
            break;

        default:

            std::cout << "???" << std::endl;
            break;

        }

        wait_for_data();
    }
    else
    {
        std::cout << error.message() << std::endl;
    }
}
Esempio n. 18
0
 std::unique_ptr<node> wait_pop_head(T& value)
 {
     std::unique_lock<std::mutex> head_lock(wait_for_data());
     value = std::move(*head->data);
     return pop_head();
 }